Next.js route handler
Accept a PDF upload in an App Router route handler and return page images.
Config first
Add serverExternalPackages: ["pdf-raster"] to next.config.ts. See
Installation.
This route takes a PDF from a form upload, renders the first page as WebP and returns it as a data URL. For a client page that uploads files and shows every page, see Upload and preview.
import { convert, PdfToImagesError } from "pdf-raster";
export const runtime = "nodejs";
export async function POST(request: Request) {
const formData = await request.formData();
const upload = formData.get("file");
if (!(upload instanceof File) || !upload.name.toLowerCase().endsWith(".pdf")) {
return Response.json(
{ code: "INVALID_INPUT", message: "Upload a PDF file." },
{ status: 400 },
);
}
try {
const pages = await convert(await upload.arrayBuffer(), {
pages: [0],
dpi: 150,
outputFormat: "webp",
maxPixels: 50_000_000,
});
return Response.json({
pages: pages.map((page) => ({
pageIndex: page.pageIndex,
width: page.width,
height: page.height,
src: `data:${page.mimeType};base64,${page.data.toString("base64")}`,
})),
});
} catch (error) {
if (error instanceof PdfToImagesError) {
const status = error.code === "PDFIUM_UNAVAILABLE" ? 500 : 400;
return Response.json(
{ code: error.code, message: error.message },
{ status },
);
}
console.error(error);
return Response.json(
{ code: "RENDER_ERROR", message: "Conversion failed." },
{ status: 500 },
);
}
}Notes
runtime = "nodejs"keeps the route off the Edge runtime, which cannot load native code.maxPixelscaps the memory one request can claim if a client uploads a PDF with huge pages.- The handler only imports pdf-raster on the server. The browser receives image data and never loads the package.
Return images, not JSON
To serve a single page as an image, for example from <img src="/api/cover">,
return the buffer directly:
const [page] = await convert(bytes, { pages: [0], outputFormat: "webp" });
return new Response(new Uint8Array(page.data), {
headers: { "Content-Type": page.mimeType },
});Data URLs grow fast
Base64 makes each image about a third larger, and a 300 DPI page is often 1 MB or more. For more than a few pages, upload the images to storage and return their URLs.