AI app builders · Updated 2026-12-03
Generate PDFs from a Supabase Edge Function
A common first attempt at PDFs in a Supabase app is to run Puppeteer inside an Edge Function. It does not fit. This guide explains why, then builds a function that sends your data to DevilPDF, saves the finished PDF to Supabase Storage, and returns a link. The same function works for apps built with Lovable or Bolt on Supabase.
#Why headless Chrome does not fit
Supabase publishes its Edge Functions limits. As of this writing they include:
| Limit | Value |
|---|---|
| Maximum memory | 256 MB |
| Maximum CPU time | 2 s per worker, not counting async I/O |
| Maximum function size | 20 MB bundled with the CLI, 5 MB bundled server-side (Dashboard or Management API) |
| Wall clock | 150 s on the Free plan, 400 s on paid plans |
The same page lists among other restrictions that the "Web Worker API (or Node vm API) are not available" and that "Node Libraries that require multithreading are not supported".
For comparison, the @sparticuz/chromium README, the usual Chromium build for serverless functions, gives the Chromium binary as 130.62 MiB uncompressed and 33.21 MiB at the best Brotli compression level. Both are above the 20 MB function size limit before you add a line of your own code. Fonts for non-Latin scripts would add more.
So the PDF has to be rendered somewhere else. A rendering API keeps the Edge Function to what it is good at: a short HTTP request.
#What you will build
An Edge Function invoice-pdf that:
- receives an invoice id,
- loads the invoice from your database,
- asks DevilPDF to render the
invoicetemplate with that data, - uploads the PDF to a private Storage bucket,
- returns a signed URL.
You need the Supabase CLI and a DevilPDF API key. The free plan includes 500 documents a month.
#1. Store the API key as a secret
Sign up and create a key under API keys. Then save it as an Edge Function secret:
supabase secrets set DEVILPDF_API_KEY=dp_live_...For local development, put the same line in supabase/functions/.env. Never put the key in your frontend code or in a VITE_ or NEXT_PUBLIC_ variable: anything the browser loads, anyone can read.
#2. Create a bucket
Create a private bucket named invoices in the Dashboard under Storage, or with SQL:
insert into storage.buckets (id, name, public) values ('invoices', 'invoices', false);#3. Write the function
supabase functions new invoice-pdfimport { createClient } from "npm:@supabase/supabase-js@2";
const DEVILPDF_API_KEY = Deno.env.get("DEVILPDF_API_KEY")!;
const SUPABASE_URL = Deno.env.get("SUPABASE_URL")!;
const SECRET_KEY =
JSON.parse(Deno.env.get("SUPABASE_SECRET_KEYS") ?? "{}")["default"] ??
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!;
Deno.serve(async (req) => {
const admin = createClient(SUPABASE_URL, SECRET_KEY);
// Only signed-in users. Read the caller from their JWT.
const jwt = req.headers.get("Authorization")?.replace("Bearer ", "") ?? "";
const { data: { user } } = await admin.auth.getUser(jwt);
if (!user) return new Response("Unauthorized", { status: 401 });
const { invoice_id } = await req.json();
// Load the invoice and its lines. Adjust to your schema.
const { data: invoice, error } = await admin
.from("invoices")
.select("number, issued_on, currency, customer_name, customer_address, user_id, invoice_lines(name, quantity, unit_price)")
.eq("id", invoice_id)
.single();
if (error || !invoice || invoice.user_id !== user.id) {
return new Response("Not found", { status: 404 });
}
// Render the PDF.
const render = await fetch("https://devilpdf.com/v1/render", {
method: "POST",
headers: {
Authorization: `Bearer ${DEVILPDF_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
template: "invoice",
output: "file",
data: {
number: invoice.number,
issue_date: invoice.issued_on,
currency: invoice.currency,
customer: { name: invoice.customer_name, address: invoice.customer_address },
items: invoice.invoice_lines,
},
}),
});
if (!render.ok) {
const { error } = await render.json();
return Response.json({ error: error.message }, { status: 502 });
}
const pdf = await render.arrayBuffer();
// Save it to Storage and return a link that works for one hour.
const path = `${user.id}/${invoice.number}.pdf`;
const upload = await admin.storage
.from("invoices")
.upload(path, pdf, { contentType: "application/pdf", upsert: true });
if (upload.error) return Response.json({ error: upload.error.message }, { status: 500 });
const { data: signed } = await admin.storage.from("invoices").createSignedUrl(path, 3600);
return Response.json({ path, url: signed?.signedUrl });
});How it fits together:
SUPABASE_URLand the secret keys are injected into every Edge Function by Supabase. The code reads the newerSUPABASE_SECRET_KEYS, and falls back to the legacySUPABASE_SERVICE_ROLE_KEYon older projects. These keys bypass Row Level Security, so the function checks ownership itself (invoice.user_id !== user.id)."output": "file"returns the PDF bytes, which go straight into Storage. DevilPDF keeps no copy.- The
invoicestarter adds up line items and tax itself, soinvoice_linesonly needsname,quantityandunit_price. FetchGET https://devilpdf.com/v1/templates/invoiceto see every field it accepts.
Deploy it:
supabase functions deploy invoice-pdf#4. Call it from your app
From the frontend, supabase.functions.invoke sends the user's session token for you:
const { data, error } = await supabase.functions.invoke("invoice-pdf", {
body: { invoice_id: invoice.id },
});
if (error) throw error;
window.open(data.url, "_blank");The browser never sees the DevilPDF key.
#Languages
Add locale to the render body and the starter's labels, dates and money follow the language. Arabic, Hebrew, Persian and Urdu mirror the page right to left. Fonts for every script are included, which is one more thing you would otherwise have to fit into a function.
const body = {
template: "invoice",
locale: "ar",
output: "file",
data: { number: "INV-1002", currency: "SAR", items: [{ name: "استشارات", quantity: 3, unit_price: 1250 }] },
};#When you have many to generate
An Edge Function has a 2 second CPU limit, but waiting on a network response does not count toward it. For one PDF per request that is fine. For a month-end run of hundreds of invoices, use POST /v1/render/batch with a webhook_url pointing at another Edge Function, and save each file when its document.succeeded event arrives. See async and batch and webhooks.