Axonpack
@axonpdf/react

Web Worker

Render in a Web Worker with useWorker and usePDFWorker, so the page stays responsive during a long render.

A render on the page's main thread blocks scrolling, typing and clicks until it finishes. For a few pages nobody notices. For a long report they do. @axonpdf/react/worker runs the whole render, React and the engine included, in a Web Worker and hands the page a Blob.

You write two things: a worker file that calls expose, and a page that starts the worker and asks it for the PDF.

The worker file

Write the worker as a plain .js file and build the document with createElement. That file works whether a bundler processes it or not:

axonpdf.worker.js
import { createElement } from 'react';
import { expose } from '@axonpdf/react/worker';
import { Report } from './report';

expose((props) => createElement(Report, props));

expose takes a function from props to the <Document>. Report is your own component, in a file next to the worker. It can be a .jsx or .tsx file when a bundler builds the worker.

With a bundler

In Vite, start the worker with new URL(..., import.meta.url). Vite sees that pattern, bundles the worker file with its imports, and copies the engine's WebAssembly file into the build for you:

report-download.jsx
import { usePDFWorker, useWorker } from '@axonpdf/react/worker';

export function ReportDownload({ rows }) {
  const worker = useWorker(
    () => new Worker(new URL('./axonpdf.worker.js', import.meta.url), { type: 'module' }),
  );
  const { loading, url, error } = usePDFWorker(worker, { rows, title: 'March' });

  if (error) return <p>The PDF failed</p>;
  if (loading || !url) return <p>Preparing...</p>;
  return (
    <a href={url} download="report.pdf">
      Download
    </a>
  );
}

This works under vite and in a vite build served with vite preview. The worker file can also be axonpdf.worker.tsx, with JSX in it.

Under the vite dev server, @vitejs/plugin-react adds fast refresh code to every .jsx and .tsx file, and that code needs window, which a worker doesn't have. Keep the worker and the components it imports in one folder, such as src/pdf/, and leave that folder out of the plugin:

vite.config.ts
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [react({ exclude: [/\/pdf\//, /\/node_modules\//] })],
});

Keep node_modules in the list. exclude replaces the plugin's default, which is node_modules.

In Next.js

Next.js bundles the worker through the same new URL(..., import.meta.url) line, in next dev and next build, with Turbopack or webpack. This needs @axonpdf/react 0.0.6 or later.

Put the worker file from above in src/app/axonpdf.worker.js, with your Report component beside it. A small one to start from:

src/app/report.tsx
import { Document, Page, Text } from '@axonpdf/react';

export type ReportProps = { rows: string[]; title: string };

export function Report({ rows, title }: ReportProps) {
  return (
    <Document>
      <Page size="A4">
        <Text>{title}</Text>
        {rows.map((row) => (
          <Text key={row}>{row}</Text>
        ))}
      </Page>
    </Document>
  );
}

The component that starts the worker needs 'use client' as its first line, because Next.js renders pages on the server first and the worker only exists in the browser:

src/app/report-download.jsx
'use client';

import { usePDFWorker, useWorker } from '@axonpdf/react/worker';

export function ReportDownload({ rows }) {
  const worker = useWorker(
    () => new Worker(new URL('./axonpdf.worker.js', import.meta.url), { type: 'module' }),
  );
  const { loading, url, error } = usePDFWorker(worker, { rows, title: 'March' });

  if (error) return <p>The PDF failed</p>;
  if (loading || !url) return <p>Preparing...</p>;
  return (
    <a href={url} download="report.pdf">
      Download
    </a>
  );
}

Then use it in a page:

src/app/page.tsx
import { ReportDownload } from './report-download';

export default function Home() {
  return <ReportDownload rows={['First row', 'Second row']} />;
}

Without a bundler, or from public/

A worker loaded by its path, such as one in public/, is served as it is. Nothing compiles it or resolves its imports, so build it into one file first. With esbuild:

npx esbuild src/axonpdf.worker.js --bundle --format=esm --platform=browser --minify \
  --define:process.env.NODE_ENV='"production"' --outfile=public/workers/axonpdf.worker.js
cp node_modules/@axonpdf/core/wasm/axonpdf.wasm public/workers/

The engine loads axonpdf.wasm from the folder the worker file is in, so copy it next to the worker. Run both lines again after you upgrade @axonpdf/react. You end up with:

public/
  workers/
    axonpdf.worker.js
    axonpdf.wasm

Then start the worker by its path:

const worker = useWorker(() => new Worker('/workers/axonpdf.worker.js', { type: 'module' }));

The worker file can be .ts or .tsx, since esbuild compiles it. Add --jsx=automatic when it has JSX in it.

A classic worker

new Worker(path) without { type: 'module' } starts a classic worker, which can't run import or import.meta. Build it with --format=iife, and give the engine the worker's own address in place of import.meta.url, which it uses to find axonpdf.wasm:

npx esbuild src/pdf.worker.tsx --bundle --format=iife --platform=browser --minify --jsx=automatic \
  --define:process.env.NODE_ENV='"production"' --define:import.meta.url=self.location.href \
  --outfile=public/workers/pdf.worker.js
cp node_modules/@axonpdf/core/wasm/axonpdf.wasm public/workers/

A worker you already have

expose is optional. A worker with its own message handling can call pdf() the way the page would:

pdf.worker.tsx
import { pdf } from '@axonpdf/react';
import { Report, type ReportProps } from './report';

self.onmessage = async (event: MessageEvent<ReportProps>) => {
  const blob = await pdf(<Report {...event.data} />).toBlob();
  self.postMessage({ url: URL.createObjectURL(blob) });
};

The page can use that URL directly, since a worker and its page share object URLs. Build the file as in Without a bundler, and copy axonpdf.wasm next to it.

What the hooks do

useWorker(create) calls create() once, when the component mounts, and terminates that worker when it unmounts. It returns null until the worker exists.

usePDFWorker(worker, props) returns { loading, blob, url, error }, the same shape usePDF gives. While worker is null it waits. It renders again whenever props change, and it compares them by value as JSON, so a new object with the same contents doesn't start a render. A result that arrives for older props is dropped, and the old object URL is revoked when a new one replaces it or the component unmounts.

With the browser components

PDFViewer, PDFDownloadLink and BlobProvider take the worker directly, with worker and props:

<PDFDownloadLink worker={worker} props={{ rows }} fileName="report.pdf">
  Download
</PDFDownloadLink>;

<PDFViewer worker={worker} props={{ rows }} width="100%" height={600} />;

<BlobProvider worker={worker} props={{ rows }}>
  {({ url, loading }) => (loading ? null : <a href={url}>Open</a>)}
</BlobProvider>;

When worker is set, the component renders from props in the worker, and document (or children on PDFViewer) is not used. Pass one or the other.

Calling the worker with renderInWorker

renderInWorker is the lower-level way to call the worker, outside React or when you want the Blob yourself:

import { renderInWorker } from '@axonpdf/react/worker';

const worker = new Worker(new URL('./axonpdf.worker.js', import.meta.url), { type: 'module' });

const blob = await renderInWorker(worker, { rows, title: 'March' });

It resolves with the PDF as a Blob of type application/pdf. When the render throws in the worker, the worker posts the error back and renderInWorker rejects with it.

A worker answers every call it gets. Each call carries its own id and the answer is matched to it, so several renders can be in flight on one worker. End it when you no longer need it:

const [march, april] = await Promise.all([
  renderInWorker(worker, { month: 'March' }),
  renderInWorker(worker, { month: 'April' }),
]);

worker.terminate();

Fonts and images

The worker has its own module scope, so a Font.register call on the page doesn't reach it. Register fonts in the worker file, before expose:

axonpdf.worker.js
import { createElement } from 'react';
import { Font } from '@axonpdf/react';
import { expose } from '@axonpdf/react/worker';
import { Report } from './report.js';

Font.register({ family: 'Lato', src: '/fonts/Lato-Regular.ttf' });

expose((props) => createElement(Report, props));

Font and image src values must be URLs the worker can fetch: absolute URLs, paths on your own site, or data: URLs. File paths only work in Node.

TypeScript

Export the props type with the component, and use it on both sides:

src/pdf/axonpdf.worker.tsx
import { expose } from '@axonpdf/react/worker';
import { Report, type ReportProps } from './report';

expose((props: ReportProps) => <Report {...props} />);
const { url } = usePDFWorker<ReportProps>(worker, { rows, title: 'March' });

usePDFWorker then checks the props you pass against the ones the worker expects.

What props can hold

Props travel from the page to the worker through postMessage, so they must be structured cloneable: plain objects, arrays, strings, numbers, dates, Blobs and typed arrays. Functions, React elements and class instances can't cross. Pass the data, and build the elements in the worker.

Common problems

  • The PDF stays on "loading" and the console shows the worker failed to load. A worker loaded by its path was a .tsx or .ts file, which the browser can't run. Build it to .js first, as in Without a bundler.
  • The build fails with "The JSX syntax extension is not currently enabled". A .js worker has JSX in it. Use createElement, as in the worker file above, or name the file .jsx or .tsx and let the bundler compile it.
  • Under vite the terminal shows window is not defined and the PDF stays on "Preparing...". The worker imports a .jsx or .tsx file that fast refresh changed. Leave its folder out of @vitejs/plugin-react, as in With a bundler.
  • useState is not a function or its return value is not iterable while Next.js prerenders a page. The file that calls useWorker has no 'use client' line. Add it as the first line, as in In Next.js.
  • In Next.js the PDF stays on "Preparing..." and the console shows Failed to parse URL from /_next/static/media/axonpdf...wasm. The app has @axonpdf/react 0.0.5 or older. Update it.
  • WebAssembly.instantiate(): expected magic word in a prebuilt worker. axonpdf.wasm isn't next to the worker file, so the server answered with an HTML page. Copy it into the same folder.
  • A registered font isn't used. Font.register ran on the page, not in the worker file.
  • The error Failed to execute 'postMessage' on 'Worker': ... could not be cloned. A prop holds a function, a React element or a class instance. Pass plain data instead.

When to use it

Use a worker for long documents rendered in the browser, or any render that runs while someone is using the page. In the browser run of 2026-11-23 (one flowing <Page>, 100 pages), rendering on the main thread froze the page for 832 ms, against 18 ms in a worker. The live benchmark app (axonpdf-demo.axonpack.dev) lets you switch to the main thread up to 100 pages and watch it; see Benchmarks.

On this page