Repository navigation
How to configure PDF.js worker in React Router v7 #1973
Replies: 1 comment
|
I reproduced this exact error and found the cause. The Vite only rewrites The usual way to get there is pnpm: node -p "require.resolve('pdfjs-dist/package.json')"
# Error: Cannot find module 'pdfjs-dist/package.json' → this is your problemFixAdd node -p "require('react-pdf/package.json').dependencies['pdfjs-dist']" # e.g. 4.8.69
pnpm add pdfjs-dist@4.8.69
rm -rf node_modules/.vite # Vite caches the untransformed module(Hoisting with Two things caught me while testing:
After that, the same line works unchanged. In dev the worker loads from If you are on react-pdf 10+ with SSR onOnce the worker resolves, newer versions hit a second problem in React Router's default SSR mode: the server fails on import with // app/components/pdf-viewer.tsx
import { Document, Page, pdfjs } from "react-pdf";
import "react-pdf/dist/Page/TextLayer.css";
import "react-pdf/dist/Page/AnnotationLayer.css";
pdfjs.GlobalWorkerOptions.workerSrc = new URL(
"pdfjs-dist/build/pdf.worker.min.mjs",
import.meta.url,
).toString();
export default function PdfViewer({ file }: { file: string }) {
return (
<Document file={file}>
<Page pageNumber={1} />
</Document>
);
}// app/routes/home.tsx
import { lazy, Suspense, useEffect, useState } from "react";
const PdfViewer = lazy(() => import("../components/pdf-viewer"));
export default function Home() {
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
if (!mounted) return <p>Loading PDF…</p>;
return (
<Suspense fallback={<p>Loading PDF…</p>}>
<PdfViewer file="/sample.pdf" />
</Suspense>
);
}The What I ran (headless Chromium, checking that the canvas had actually been drawn):
With npm's normal hoisting I could not reproduce the 404 at all. So if Disclosure: I build a hosted HTML→PDF API. It isn't linked here and isn't needed for this. I wrote this answer with AI help and checked every step above in the setups listed before posting. |
Uh oh!
There was an error while loading. Please reload this page.
I successfully configured PDF.js using the external CDN pattern, but I'm struggling with the recommended "Import worker" approach in React Router v7. How should I properly configure the PDF.js worker using the import method in a React Router v7 application?
pdfjs.GlobalWorkerOptions.workerSrc = new URL("pdfjs-dist/build/pdf.worker.min.mjs", import.meta.url).toString();All reactions