Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions .github/workflows/nextjs.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
name: Next.js PDF starter
on:
pull_request:
paths: ['examples/nextjs/**', '.github/workflows/nextjs.yml']
push:
branches: [main]
paths: ['examples/nextjs/**', '.github/workflows/nextjs.yml']
workflow_dispatch:
permissions:
contents: read
concurrency:
group: nextjs-${{ github.ref }}
cancel-in-progress: true
jobs:
standalone:
strategy:
fail-fast: false
matrix:
include:
- { os: ubuntu-latest, node: '22' }
- { os: ubuntu-latest, node: '24' }
- { os: windows-latest, node: '24' }
runs-on: ${{ matrix.os }}
timeout-minutes: 15
defaults:
run:
working-directory: examples/nextjs
env:
NEXT_TELEMETRY_DISABLED: '1'
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v6
with:
node-version: ${{ matrix.node }}
cache: npm
cache-dependency-path: examples/nextjs/package-lock.json
- run: npm ci --ignore-scripts --no-audit --no-fund
- run: npm run preview:pdf
- run: npm run build
- run: npm run verify
- uses: actions/upload-artifact@v4
if: always()
with:
name: nextjs-${{ matrix.os }}-${{ matrix.node }}
path: |
examples/nextjs/output/
examples/nextjs/public/invoice.png
retention-days: 14
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,14 @@ npm run example
Open `output/invoice/invoice.pdf` and `page-1.png`. The [three-page report
sources](examples/report.html) demonstrate pagination, tables, and vector artwork.

## Use it in Next.js

For a web application, start with the [Next.js PDF download example](examples/nextjs).
It includes a designed invoice, an App Router handler, production build settings
for the worker and bundled assets, and a standalone-server verification script.
The route bounds rendering and returns private PDF attachments from fictional
data; connect your own authenticated record lookup when adapting it.

## Fonts and assets

Supply file bytes explicitly. Additional fonts are registered alongside the
Expand Down
4 changes: 4 additions & 0 deletions examples/nextjs/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules/
.next/
output/
.env*.local
21 changes: 21 additions & 0 deletions examples/nextjs/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 Fullbleed Contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
101 changes: 101 additions & 0 deletions examples/nextjs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# Fullbleed PDF downloads in Next.js

A runnable App Router starter that serves a designed invoice from a Node.js
route. It includes the HTML/CSS, an actual PDF preview, and an isolated
standalone-server check. All invoice data is fictional; the public fixture
lookup is not an authentication system.

## Run it

Use Node.js 22 or newer. From this directory:

```sh
npm ci --ignore-scripts
npm run build
npm start
```

Open `http://127.0.0.1:3000` and select **Download sample PDF**. The route
`/api/invoices/NS-1042` returns the one-page invoice as an attachment. Unknown
IDs return 404. Use `npm run dev` while editing the app. `PORT` changes the port;
`FULLBLEED_HOST` changes the production server's loopback binding.

The lockfile pins Next.js 16.3.8, React 19.3.0 and the released Fullbleed Node
0.1.1 tarball (engine 2.5.5). Fullbleed does not yet have a configured npm
registry publisher; the dependency uses the verified GitHub release URL.
Installing this starter needs no Python, Rust, system fonts or browser renderer.

## Adapt the document

Edit `templates/invoice.html` and `templates/invoice.css`. The sample uses
bundled Inter, DM Serif Display and Bebas Neue. `lib/invoice.mjs` inserts an
escaped customer name from the fictional fixture. Amounts and dates are sample
content, not an invoicing ledger or tax calculation.

After changing the template, regenerate and inspect the PDF and preview:

```sh
npm run preview:pdf
```

Open `output/invoice.pdf` and `public/invoice.png`, then rebuild the app. The
checked-in image is output from Fullbleed, not a browser screenshot or mockup.

## Keep the renderer on the server

The route declares `runtime = 'nodejs'`. It uses filesystem reads, worker
threads and WebAssembly, so this integration needs the Node runtime.
`serverExternalPackages: ['fullbleed']` keeps Next.js from bundling the engine's
Node entrypoint. Explicit output tracing includes the worker, WASM, fonts,
WASI dependency and template files needed by the standalone server.
See Next.js's [external-package configuration](https://nextjs.org/docs/app/api-reference/config/next-config-js/serverExternalPackages)
and [standalone output documentation](https://nextjs.org/docs/app/api-reference/config/next-config-js/output).

`npm run build` copies the public preview and browser chunks into
`.next/standalone`, after Next generates it. That folder is the deployment
artifact. Start its `server.js` with Node on a host that supports workers and
WebAssembly; set the host's normal `PORT` and `HOSTNAME` environment variables.
The local start script defaults to loopback. Hosting-provider limits and
serverless or Edge deployments have not been verified by this starter.

## Adapt the route for real accounts

Replace `getDemoInvoice(id)` with a session-authenticated lookup that verifies
the invoice belongs to that account **before rendering**. Keep order fields
escaped. Never accept arbitrary HTML, filesystem paths or remote asset URLs
from this public endpoint.

The example renders at most one document at a time per server process. Extra
requests receive `503 BUSY` and `Retry-After: 2`; they do not enter an unbounded
queue. Successful PDFs have `private, no-store`, a fixed filename, a complete
content length and `nosniff`. Jobs have a 15-second rendering deadline and a
five-page cap, and receive the request's abort signal. No generated PDF is
written to application storage by the route.

Use shared rate/usage controls for multiple processes or replicas. Measure your
host's memory and CPU before increasing capacity; each render worker can grow
to the package's 512 MiB WASM ceiling. Private document delivery also requires
your application's normal access controls, monitoring and retention policies.

## Verify the production artifact

After building:

```sh
npm run verify
```

The check copies the standalone artifact to a fresh temporary directory outside
the app and starts it on an available loopback port. It compares a real HTTP
PDF to the direct engine output, checks headers and missing IDs, sends a
concurrent burst, then verifies recovery from actual missing-glyph and page-cap
failures. Client JavaScript is checked for accidental engine/worker inclusion.
Results and the downloaded PDF are retained under `output/`.

Temporary artifact directories use the `fullbleed-nextjs-` prefix and are kept
for inspection. The verification script closes its own server when it finishes.
These checks cover a fictional fixture; they do not establish application
authorization, PDF standards compliance, or a hosting provider's limits.

[Fullbleed Node API](https://github.com/fullbleed-engine/fullbleed-node) ·
[Documentation](https://docs.fullbleed.dev/) · [MIT license](LICENSE)
46 changes: 46 additions & 0 deletions examples/nextjs/app/api/invoices/[id]/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// SPDX-License-Identifier: MIT
import { renderPdf, FullbleedError } from 'fullbleed';
import { getDemoInvoice, invoiceTemplate } from '../../../../lib/invoice.mjs';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

// One active render per process; there is no unbounded waiting queue.
// Add authentication and a shared rate/usage limit for a deployed application.
let active = 0;
const privateHeaders = {
'Cache-Control': 'private, no-store',
'X-Content-Type-Options': 'nosniff',
};
const errorResponse = (status, code, message, extra = {}) => Response.json(
{ error: { code, message } }, { status, headers: { ...privateHeaders, ...extra } },
);

export async function GET(request, { params }) {
const { id } = await params;
const invoice = getDemoInvoice(id);
if (!invoice) return errorResponse(404, 'NOT_FOUND', 'Sample invoice not found.');
if (active >= 1) return errorResponse(503, 'BUSY', 'A document is being prepared. Try again shortly.', { 'Retry-After': '2' });
active++;
try {
const template = await invoiceTemplate(invoice);
const { pdf } = await renderPdf({ ...template, maxPages: 5, timeoutMs: 15_000, signal: request.signal });
return new Response(pdf, {
headers: {
...privateHeaders,
'Content-Type': 'application/pdf',
'Content-Disposition': `attachment; filename="invoice-${invoice.id}.pdf"`,
'Content-Length': String(pdf.length),
},
});
} catch (error) {
const code = error instanceof FullbleedError ? error.code : 'UNEXPECTED';
// Log an operational code only; never log customer data or document input.
console.error('Fullbleed invoice render failed:', code);
if (code === 'TIMEOUT') return errorResponse(504, code, 'Document preparation timed out.');
if (code === 'ABORTED') return errorResponse(408, code, 'Document preparation was cancelled.');
return errorResponse(500, 'RENDER_FAILED', 'The document could not be prepared.');
} finally {
active--;
}
}
38 changes: 38 additions & 0 deletions examples/nextjs/app/globals.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/* SPDX-License-Identifier: MIT */
:root { color-scheme: light; --ink: #203b32; --muted: #627169; --paper: #f7f5ee; --accent: #bb4e2c; }
* { box-sizing: border-box; }
body { margin: 0; background: var(--paper); color: var(--ink); font: 16px/1.6 system-ui, sans-serif; }
a { color: inherit; text-underline-offset: .2em; }
.nav, main, footer { max-width: 1240px; margin: auto; padding-left: 40px; padding-right: 40px; }
.nav { min-height: 104px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #cdd2c8; }
.wordmark { font-weight: 850; font-size: 30px; letter-spacing: -1.5px; text-decoration: none; }
.wordmark span { color: var(--accent); }
.eyebrow { font-size: 10px; font-weight: 750; letter-spacing: 2px; }
.hero { display: grid; grid-template-columns: 1fr .88fr; align-items: center; gap: 76px; padding: 62px 0 76px; }
h1 { font: 56px/1.06 Georgia, serif; letter-spacing: -2px; margin: 22px 0; }
h1 em { color: var(--accent); font-weight: 400; }
.lede { max-width: 430px; color: var(--muted); font-size: 17px; line-height: 1.7; margin-bottom: 30px; }
.button { display: inline-flex; justify-content: space-between; gap: 38px; align-items: center; background: var(--ink); color: white; padding: 15px 22px; font-weight: 650; text-decoration: none; }
.button:hover { background: #345949; }
a:focus-visible { outline: 3px solid var(--accent); outline-offset: 5px; }
.caption { font-size: 11px; color: var(--muted); margin-top: 13px; }
.note { border-top: 1px solid #cdd2c8; max-width: 430px; padding-top: 28px; margin-top: 45px; }
.note span, .steps article > span { font-size: 10px; font-weight: 750; letter-spacing: 1.3px; }
.note p { font-size: 13px; color: var(--muted); margin-bottom: 0; }
.paper { margin: 0; padding: 18px 18px 0; background: #dedfd3; border: 1px solid #cdd2c8; }
.paper img { display: block; width: 100%; height: auto; box-shadow: 0 7px 18px #203b3214; }
.paper figcaption { font-size: 10px; text-align: center; padding: 12px 0; color: #4b5d51; }
.steps { display: grid; grid-template-columns: repeat(3, 1fr); gap: 42px; padding: 35px 0 52px; border-top: 1px solid #cdd2c8; }
.steps article > span { color: var(--accent); }
.steps h2 { font-size: 17px; line-height: 1.4; margin: 12px 0; }
.steps p { color: var(--muted); font-size: 13px; }
footer { border-top: 1px solid #cdd2c8; display: flex; gap: 28px; padding-top: 24px; padding-bottom: 28px; font-size: 11px; }
footer span { margin-right: auto; }
@media (max-width: 850px) { .hero { gap: 30px; } h1 { font-size: 43px; } }
@media (max-width: 650px) {
.nav, main, footer { padding-left: 22px; padding-right: 22px; }
.nav { min-height: 82px; } .hero { grid-template-columns: 1fr; gap: 35px; padding: 36px 0; }
h1 { font-size: 44px; } .lede { font-size: 16px; } .note { margin-top: 30px; padding-top: 20px; }
.steps { grid-template-columns: 1fr; gap: 24px; } .steps p { margin-bottom: 0; }
footer { flex-wrap: wrap; gap: 14px 25px; } footer span { width: 100%; }
}
11 changes: 11 additions & 0 deletions examples/nextjs/app/layout.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// SPDX-License-Identifier: MIT
import './globals.css';

export const metadata = {
title: 'A better PDF download | Fullbleed + Next.js',
description: 'A runnable Next.js starter serving a designed invoice with Fullbleed. Fictional sample data.',
};

export default function Layout({ children }) {
return <html lang="en"><body>{children}</body></html>;
}
25 changes: 25 additions & 0 deletions examples/nextjs/app/page.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// SPDX-License-Identifier: MIT
export default function Page() {
return <>
<header className="nav"><a className="wordmark" href="https://www.fullbleed.dev/">fullbleed<span>.</span></a><span className="eyebrow">NEXT.JS STARTER</span></header>
<main>
<section className="hero">
<div className="intro">
<p className="eyebrow">A SMALL ROUTE. A BETTER DOCUMENT.</p>
<h1>Make the download<br /><em>worth opening.</em></h1>
<p className="lede">Serve a designed PDF from your Next.js app. Start with this studio invoice, then make the HTML and CSS your own.</p>
<a className="button" href="/api/invoices/NS-1042" download>Download sample PDF <span aria-hidden="true">↗</span></a>
<p className="caption">One page · Fictional invoice NS-1042 · No sign-in</p>
<div className="note"><span>YOUR APP. YOUR DOCUMENTS.</span><p>The PDF is generated on your Node.js server with bundled fonts. Your HTML and CSS define the printed page.</p></div>
</div>
<figure className="paper"><img src="/invoice.png" width="794" height="1123" alt="Actual Fullbleed PDF: a Northstar Studio invoice with cream paper, green tables, oversized type and an orange accent." /><figcaption>Actual PDF output · Northstar Studio</figcaption></figure>
</section>
<section className="steps" aria-label="Make it your own">
<article><span>01 / DESIGN</span><h2>Keep your HTML &amp; CSS.</h2><p>Edit the included template. Use the bundled typefaces or supply your own font files.</p></article>
<article><span>02 / CONNECT</span><h2>Use your application data.</h2><p>The sample route looks up a fictional invoice. Connect your own authorized record lookup when adapting it.</p></article>
<article><span>03 / DELIVER</span><h2>Send a real PDF.</h2><p>A normal download link calls the server route. Rendering has a page limit, deadline and capacity limit.</p></article>
</section>
</main>
<footer><span>Fullbleed · MIT licensed</span><a href="https://docs.fullbleed.dev/getting-started/node/">Node.js guide</a><a href="https://github.com/fullbleed-engine/fullbleed-node/tree/main/examples/nextjs">Explore the source</a></footer>
</>;
}
25 changes: 25 additions & 0 deletions examples/nextjs/lib/invoice.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// SPDX-License-Identifier: MIT
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';

// Fictional public fixture, not an authorization implementation. In your app,
// replace this with an authenticated lookup scoped to the requesting account.
const invoices = new Map([
['NS-1042', { id: 'NS-1042', customer: 'Maple & Finch' }],
]);

export function getDemoInvoice(id) {
return invoices.get(id);
}

const escapeHtml = value => String(value).replace(/[&<>"']/g, char => ({
'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
})[char]);

export async function invoiceTemplate(invoice) {
const [html, css] = await Promise.all([
readFile(join(process.cwd(), 'templates/invoice.html'), 'utf8'),
readFile(join(process.cwd(), 'templates/invoice.css'), 'utf8'),
]);
return { html: html.replace('{{customer}}', () => escapeHtml(invoice.customer)), css };
}
19 changes: 19 additions & 0 deletions examples/nextjs/next.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// SPDX-License-Identifier: MIT
import { fileURLToPath } from 'node:url';

const root = fileURLToPath(new URL('.', import.meta.url));

export default {
output: 'standalone',
poweredByHeader: false,
serverExternalPackages: ['fullbleed'],
outputFileTracingRoot: root,
turbopack: { root },
outputFileTracingIncludes: {
'/api/invoices/*': [
'./templates/**/*',
'./node_modules/fullbleed/**/*',
'./node_modules/@bjorn3/browser_wasi_shim/**/*',
],
},
};
Loading
Loading