javascriptreactjsnext.jsreact-dompdftron

Next.js PDFtron Webviewer - ReferenceError: window is not defined


I'm trying to create a PDF viewer on my nextjs static page but i dont know how! hope you guys can help me solving this error or showing one other way to do this. (I'm new to Next.js) I was following this working example here

index.js

import SiteLayout from "../../components/SiteLayout";
import React from 'react';
import ReactDOM from "react-dom";
import Viewer from "../resume/viewer.js";

export default function Resume({ resume }) {
  return (   
    <div>
      <Viewer />
    </div> 
  );
}

viewer.js

import React, { useRef, useEffect } from "react";
import WebViewer from "@pdftron/webviewer";

const Viewer = (props) => {
  const viewer = useRef(null);

  useEffect(() => {       
    WebViewer({
      path: "/lib",
      initialDoc: "/pdf/GustavoMorilla.pdf"
    }, viewer.current);
  }, []);

  return (
    <div className="Viewer">
      <div className="header">React sample</div>
      <div className="webviewer" ref={viewer}></div>
    </div>
  );
};

export default Viewer;

Solution

  • WebViewer needs the window object to work. In nextjs there is a prerender phase server side and on that side window is not defined.

    To solve your problem you can use next/dynamic in viewer.js

    import dynamic from 'next/dynamic';
    const WebViewer = dynamic(() => import('@pdftron/webviewer'), {ssr: false});
    

    Alternatively you can import Viewer in index.js with dynamic import

    import dynamic from 'next/dynamic';
    const Viewer = dynamic(() => import('../resume/viewer.js'), {ssr: false});