You install PDF.js, render your first page, and the console shows an error about a fake worker. Or the page works locally and breaks in production.
Most PDF.js setup problems come down to the worker file. PDF.js does heavy parsing in a separate worker, and your app must tell it where that file lives.
- Point to the worker with your bundler Let the bundler resolve the path so it ends up in your build:
(https://dev-to-uploads.s3.us-east-2.amazonaws.com/uploads/articles/co2ps9w08l7135490kvk.JPG)
The file name depends on the version. Newer releases use .mjs, and older ones use .js. Check node_modules/pdfjs-dist/build to see which you have.
Keep the API and worker versions identical
A version mismatch error means the main library and the worker came from different releases, often because the worker loads from a CDN. Pin the version, and load both from the same package.Don't render on the server
In Next.js, loading PDF.js during server rendering can fail with browser-only errors. Load the viewer on the client only:
import dynamic from 'next/dynamic';
const PdfViewer = dynamic(() => import('./PdfViewer'), { ssr: false });
Check production
The worker file exists in the build output and returns a 200.
Your server sends a correct JavaScript content type for .mjs.
Your Content Security Policy allows workers from your own origin.
If the worker comes from another origin, CORS is configured.Debug in order
Check the console, then the network tab for the worker request, then versions. That order finds most problems in minutes.
Try it
If you would rather build on an existing viewer, we've been working on TeamSync PDF Viewer, an open-source React SDK for rendering, search and annotations: https://github.com/angelbot-ai/TeamSync-PDF-Viewer. If you hit a setup problem with it, open an issue with your framework and version.
Question for you: which framework gave you the most trouble with PDF.js?
Top comments (0)