# Running in a worker

> Generate and read large xlsx files in a Web Worker without freezing the page, transfer the bytes efficiently, and use the Excel Engine in Node.

Writing a workbook with 100,000 rows takes long enough to freeze a page for a noticeable moment. The Excel Engine needs no DOM, so you can move that work into a Web Worker and keep scrolling, typing and animations smooth. The same code runs unchanged in Node for server-side exports.

## What runs where

| Function | Main thread | Web Worker | Node 20+ |
| --- | --- | --- | --- |
| `writeXlsx()` | Yes | Yes | Yes |
| `writeXlsxSync()` | Yes | Yes | Yes |
| `readXlsx()` | Yes | Yes | Yes |
| `downloadXlsx()` | Yes | No | No |

`downloadXlsx()` needs a `document` to trigger the download, so it throws in a worker. Write the bytes in the worker, send them to the page, and start the download there.

## Writing in a worker

The worker receives plain data, builds the workbook and returns the file bytes. Transfer the underlying `ArrayBuffer` instead of copying it, so a 20 MB file moves between threads instantly.

```ts title="export.worker.ts"
import { writeXlsx, type XlsxWorkbook } from '@birchui/excel';

interface ShipmentRow {
  tracking: string;
  customer: string;
  depot: string;
  shippedAt: string;
  weightKg: number;
  delivered: boolean;
}

interface ExportRequest {
  rows: ShipmentRow[];
  fileName: string;
}

self.onmessage = async (event: MessageEvent<ExportRequest>) => {
  const { rows, fileName } = event.data;
  const workbook: XlsxWorkbook = {
    sheets: [
      {
        name: 'Shipments',
        freeze: { rows: 1 },
        autoFilter: true,
        columns: [{ width: 16 }, { width: 28 }, { width: 14 }, { width: 18, style: { numFmt: 'yyyy-mm-dd hh:mm' } }, { width: 10 }, { width: 10 }],
        rows: [
          ['Tracking', 'Customer', 'Depot', 'Shipped', 'Weight (kg)', 'Delivered'].map((value) => ({ value, style: { bold: true } })),
          ...rows.map((row) => [row.tracking, row.customer, row.depot, new Date(row.shippedAt), row.weightKg, row.delivered]),
        ],
      },
    ],
  };
  const bytes = await writeXlsx(workbook);
  const buffer = bytes.buffer as ArrayBuffer;
  self.postMessage({ fileName, buffer }, { transfer: [buffer] });
};
```

```ts title="export-button.ts"
const worker = new Worker(new URL('./export.worker.ts', import.meta.url), { type: 'module' });

worker.onmessage = (event: MessageEvent<{ fileName: string; buffer: ArrayBuffer }>) => {
  const { fileName, buffer } = event.data;
  const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = fileName;
  link.click();
  setTimeout(() => URL.revokeObjectURL(url), 30_000);
  exportButton.disabled = false;
};

exportButton.addEventListener('click', () => {
  exportButton.disabled = true;
  worker.postMessage({ rows: shipments, fileName: 'shipments-october.xlsx' });
});
```

`new URL('./export.worker.ts', import.meta.url)` is the pattern Vite, webpack 5, Rollup and esbuild recognise for bundling module workers. Pass ISO strings or timestamps for dates and create the `Date` objects inside the worker, as above; `Date` objects survive `postMessage` too, but plain values keep the message format obvious.

> **Tip**
>
> The data you send to the worker is copied. For very large exports, send only the columns you need, or fetch the data inside the worker so it never passes through the page.

## License keys in workers

A worker runs its own copy of every module it imports, including `@birchui/license`. A key set with `setLicenseKey()` on the page is not visible inside the worker, so give the worker the key as well, either by calling `setLicenseKey()` at the top of the worker or by passing `licenseKey` to each call:

```ts title="export.worker.ts"
import { setLicenseKey } from '@birchui/license';

setLicenseKey(import.meta.env.VITE_BIRCHUI_LICENSE_KEY);
```

Without a key the worker still writes and reads files normally and logs one console warning.

## Reading in a worker

Reading follows the same pattern in the other direction. A `File` can be posted to a worker directly; it is passed by reference, not copied.

```ts title="import.worker.ts"
import { readXlsx, sheetToObjects } from '@birchui/excel';

self.onmessage = async (event: MessageEvent<File>) => {
  try {
    const { sheets } = await readXlsx(event.data);
    const records = sheets.length ? sheetToObjects(sheets[0]) : [];
    self.postMessage({ ok: true, records });
  } catch (error) {
    self.postMessage({ ok: false, message: (error as Error).message });
  }
};
```

```ts title="import-input.ts"
const importer = new Worker(new URL('./import.worker.ts', import.meta.url), { type: 'module' });

importer.onmessage = (event) => {
  if (event.data.ok) grid.setRows(event.data.records);
  else showError(event.data.message);
};

fileInput.addEventListener('change', () => {
  const file = fileInput.files?.[0];
  if (file) importer.postMessage(file);
});
```

Records contain only strings, numbers, booleans, `Date` objects and `null`, all of which can be posted back to the page.

## Node

In Node 20 and later, `writeXlsx()` and `readXlsx()` work as they do in the browser, using the built-in `CompressionStream` and `DecompressionStream`.

```ts title="scripts/monthly-report.ts"
import { readFile, writeFile } from 'node:fs/promises';
import { readXlsx, sheetToObjects, writeXlsx } from '@birchui/excel';

const orders = await loadOrdersFromDatabase('2026-10');
const licenseKey = process.env.BIRCHUI_LICENSE_KEY;

const bytes = await writeXlsx({
  creator: 'Order desk',
  sheets: [
    {
      name: 'October 2026',
      freeze: { rows: 1 },
      rows: [
        ['Order', 'Customer', 'Total'],
        ...orders.map((order) => [order.number, order.customer, order.total]),
      ],
    },
  ],
}, { licenseKey });
await writeFile('reports/orders-2026-10.xlsx', bytes);

const upload = await readXlsx(await readFile('incoming/price-list.xlsx'), { licenseKey });
console.log(sheetToObjects(upload.sheets[0]).length, 'prices read');
```

To return a file from an HTTP handler, send the bytes with the xlsx content type:

```ts
const bytes = await writeXlsx(workbook);
return new Response(bytes, {
  headers: {
    'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'Content-Disposition': 'attachment; filename="orders-2026-10.xlsx"',
  },
});
```

## Sync or async

`writeXlsxSync()` returns immediately with an uncompressed file. It is convenient in tests and scripts where file size does not matter. `writeXlsx()` compresses the file, which is typically several times smaller for text-heavy sheets, and is the right choice for anything users download.

Both build the whole file in memory. For exports beyond a few hundred thousand rows, split data across sheets or files, and remember Excel's limit of 1,048,576 rows per sheet.
