QR codes

What it's for

Event tickets, check-in links, a table's ordering page, a Wi-Fi login: a QR code your users scan from a screen or paper. The module draws one as an SVG image from any text, with the qrcode crate. SVG stays sharp at any size and prints well.

The route

An API route that gives a ticket's owner their ticket's QR code. tickets has a code text field and an owner relation to users:

// pb_pages/tickets/[id]/qr.ts: a ticket's QR code, for its owner, as SVG
export async function get(ctx: any) {
  if (!ctx.auth) throw ctx.httpError(401, "Sign in first")
  const ticket = ctx.app.findRecordById("tickets", ctx.params.id)
  if (ticket.get("owner") !== ctx.auth.id) throw ctx.httpError(403, "Not your ticket")
  const svg = await $wasm.run.async<string>("qrcode", `https://example.com/check-in/${ticket.get("code")}`)
  return ctx.res.json({ svg })
}

A plain <img src> doesn't send the user's PocketBase token, so fetch the SVG with it (the JS SDK's pb.send) and show it from a blob URL (new Blob([svg], { type: "image/svg+xml" })). Or draw it once, when the ticket is created, and save it in a protected file field: then an <img> with a file token shows it.

The module

The text is stdin; the SVG is stdout (src/main.rs):

let code = QrCode::with_error_correction_level(&input, EcLevel::M)
    .unwrap_or_else(|e| fail("too_long", &format!("can't encode it: {e}")));
let image = code.render::<svg::Color>().min_dimensions(200, 200).build();
std::io::stdout().write_all(image.as_bytes()).unwrap();

Error correction M survives about 15% of the code being damaged or covered. Change the colors with .dark_color(svg::Color("#1d4ed8")).

Build

cd ext/wasm/example/qrcode
cargo build --release --target wasm32-wasip1   # rustup target add wasm32-wasip1 first
cp target/wasm32-wasip1/release/qrcode.wasm pb_hooks/qrcode.pb.wasm

Cost

109 KB. The first call compiles it (about 30 ms); later calls load it from the cache in about 1.3 ms and draw a code in about 2 ms.

Limits

  • A QR code holds at most 2,331 bytes at level M; longer text fails with too_long.
  • An empty input fails with empty_input.