Article

Dynamic QR codes for printed packaging: short links that keep working

Print QR codes that keep working: encode a short link on your own domain, redirect it, add UTM tags and test it with Datadog synthetic tests.

Published Updated 7 min read

This guide shows how to put QR codes on printed packaging that keep working when your site changes. The code holds a short link on your own domain, and a server-side redirect sends that link to the real page. A Node.js script makes branded codes in SVG and PNG from a CSV file, and Datadog synthetic tests check the redirects. The examples use qrcode 1.5.4, sharp 0.35.6 and csv-parse 7.0.3 on Node.js 24, the current npm versions on 1 December 2026.

Install the packages:

npm install qrcode sharp csv-parse
npm install --save-dev @types/qrcode

A printed code cannot change, but product pages can: a product gets a new URL, a market gets a new locale structure, or a campaign page goes offline. If the code holds the final URL, every such change breaks the packaging that is already in stores and in homes.

So the code holds a short link on your own domain, for example https://example.com/go/a1b2, and the redirect behind it can point anywhere and change at any time. Use your own domain rather than a third-party link shortener, so that the links work for as long as you own the domain.

A short link also gives a simpler code, because a QR code needs more modules for more data. With less text, each module is larger at the same print size, and phones read the code more easily.

Redirect on the server

The redirect does three things:

  • It looks up the target for the code.
  • It falls back to a default target, such as the home page, when no target is set yet, so a scan never ends on an error page.
  • It adds UTM parameters, so visits from the packaging show up in your analytics.

Use a temporary redirect, 302 or 307. RFC 9110 says that a 301 response is heuristically cacheable, so a browser can store it without any cache headers and keep the old target after you change it. A 302 is only cached when the response says so, and the example also sends Cache-Control: no-store.

const HOME = 'https://example.com/';
const TARGETS: Record<string, string> = {
  a1b2: 'https://example.com/products/rose-hand-cream',
  c3d4: '',
};

export function resolve(code: string): string {
  const url = new URL(TARGETS[code] || HOME);
  url.searchParams.set('utm_source', 'qr');
  url.searchParams.set('utm_medium', 'packaging');
  url.searchParams.set('utm_campaign', 'sample-packaging');
  url.searchParams.set('utm_content', code);
  return url.toString();
}

export function handle(request: Request): Response {
  const code = new URL(request.url).pathname.match(/^\/go\/([a-z0-9]+)\/?$/)?.[1];
  if (!code) return new Response('Not found', { status: 404 });
  return new Response(null, {
    status: 302,
    headers: { Location: resolve(code), 'Cache-Control': 'no-store' },
  });
}

A request to /go/a1b2 now redirects to:

https://example.com/products/rose-hand-cream?utm_source=qr&utm_medium=packaging&utm_campaign=sample-packaging&utm_content=a1b2

handle uses the standard Request and Response classes of the Fetch API, so many edge platforms and server runtimes accept a handler like this. Your CDN may also have its own redirect rules or a key-value store, and the idea stays the same: a table from code to target, a default, and UTM parameters.

Google Analytics says to always set utm_source, utm_medium and utm_campaign, while utm_content tells different creatives apart, so the code itself goes there. Because the UTM parameters live in the redirect and not in the printed code, you can add or change them without a reprint.

Design a branded code that still scans

A branded code has brand colours and a logo in the middle. Both make the code harder to read, so keep to a few rules:

  • Error correction level H. QR codes can restore part of the data when it is damaged or covered. The qrcode package supports four levels: L (about 7%), M (about 15%, the default), Q (about 25%) and H (about 30%). A logo covers part of the code, so use H.
  • Small logo in the centre. The example uses 20% of the width, on a white square. Keep the logo away from the three large squares in the corners, because phones use them to find the code.
  • Quiet zone. Keep an empty border around the code, which the margin option sets in modules (the default is 4), and make sure the packaging design does not crop it.
  • Contrast. Use dark modules on a light background and do not invert the code, because the qrcode README says the dark colour should always be darker than the light colour.
  • Test on paper. Print the code at its real size, on the real material, and scan it with several phones.

Use SVG for print, because it scales without loss, and PNG for previews and for tools that do not accept SVG.

Generate SVG and PNG from a CSV

The input is a CSV file with one row per product, where the target column can stay empty until the page exists.

code,product,target
a1b2,Body cream sample,
c3d4,"Hand wash, travel size",https://example.com/products/hand-wash

The script reads the CSV, makes an SVG per row, adds the logo, renders a PNG with sharp and writes a mapping table.

import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { parse } from 'csv-parse/sync';
import QRCode from 'qrcode';
import sharp from 'sharp';

type Row = { code: string; product: string; target: string };

const SHORT_BASE = 'https://example.com/go/';
const DEFAULT_TARGET = 'https://example.com/';
const COLOR = { dark: '#4a2c2aff', light: '#ffffffff' };
const LOGO_SHARE = 0.2; // logo width as a share of the code width
const SIZE = 1024;

const [csvPath = 'products.csv', outDir = 'out'] = process.argv.slice(2);
const logo = await readFile('logo.svg');
const rows: Row[] = parse(await readFile(csvPath), {
  columns: true,
  skip_empty_lines: true,
  trim: true,
});

await mkdir(outDir, { recursive: true });
const mapping = [['code', 'product', 'short_link', 'target']];

for (const row of rows) {
  const shortLink = SHORT_BASE + row.code;
  const svg = await QRCode.toString(shortLink, {
    type: 'svg',
    errorCorrectionLevel: 'H',
    margin: 4,
    width: SIZE,
    color: COLOR,
  });
  const branded = addLogo(svg, logo);

  await writeFile(`${outDir}/qr-${row.code}.svg`, branded);
  await sharp(Buffer.from(branded)).png().toFile(`${outDir}/qr-${row.code}.png`);
  mapping.push([row.code, row.product, shortLink, row.target || DEFAULT_TARGET]);
}

const csv = mapping.map((cells) => cells.map(quote).join(',')).join('\n');
await writeFile(`${outDir}/mapping.csv`, csv + '\n');

function addLogo(svg: string, logoSvg: Buffer): string {
  const size = Number(svg.match(/viewBox="0 0 (\d+) \d+"/)?.[1]);
  const box = size * LOGO_SHARE;
  const pos = (size - box) / 2;
  const href = `data:image/svg+xml;base64,${logoSvg.toString('base64')}`;
  const overlay =
    `<rect x="${pos}" y="${pos}" width="${box}" height="${box}" fill="#ffffff"/>` +
    `<image href="${href}" x="${pos}" y="${pos}" width="${box}" height="${box}"/>`;
  return svg.replace('</svg>', `${overlay}</svg>`);
}

function quote(value: string): string {
  return `"${value.replaceAll('"', '""')}"`;
}

Run it with node generate.mts products.csv out, since Node.js 24 runs the TypeScript file directly.

How it works:

  • QRCode.toString with type: 'svg' returns the code as an SVG string whose viewBox counts modules, including the quiet zone, while width sets the rendered size in pixels.
  • color.dark and color.light take hex colours with an alpha channel, which here give a dark brown for the modules and white for the background.
  • addLogo reads the size from the viewBox and places a white square with the logo in the centre. The logo is embedded as a data URL, so the SVG file works on its own.
  • sharp renders the same SVG to PNG, so both files show the same code.

Keep a mapping table

The script writes mapping.csv:

"code","product","short_link","target"
"a1b2","Body cream sample","https://example.com/go/a1b2","https://example.com/"
"c3d4","Hand wash, travel size","https://example.com/go/c3d4","https://example.com/products/hand-wash"

This table is the contract between the code on the box and the redirect. The team that owns the redirects loads it into its redirect rules, and the tests in the next section read it too. Keep it in version control next to the CSV input, and when a target changes, update the table and the redirect together.

Test the redirects with Datadog synthetic tests

A redirect can break without anyone noticing: a CDN rule changes, a key-value entry is deleted, or a migration drops a path. A Datadog synthetic API test calls the short link on a schedule and checks the answer.

Turn off “follow redirects” so that the test checks the redirect itself. It checks two things: that the status code is 302, and that the location header contains the target and the UTM source. The script below creates one test per row of the mapping table through the Datadog Synthetics API.

import { readFile } from 'node:fs/promises';
import { parse } from 'csv-parse/sync';

type Mapping = { code: string; product: string; short_link: string; target: string };

const { DD_SITE = 'datadoghq.eu', DD_API_KEY = '', DD_APP_KEY = '' } = process.env;
const rows: Mapping[] = parse(await readFile('out/mapping.csv'), { columns: true });

for (const row of rows) {
  const test = {
    name: `QR redirect ${row.code} (${row.product})`,
    type: 'api',
    subtype: 'http',
    config: {
      request: { method: 'GET', url: row.short_link },
      assertions: [
        { type: 'statusCode', operator: 'is', target: 302 },
        { type: 'header', property: 'location', operator: 'contains', target: row.target },
        { type: 'header', property: 'location', operator: 'contains', target: 'utm_source=qr' },
      ],
    },
    locations: ['aws:eu-west-3'],
    options: { tick_every: 3600, follow_redirects: false, min_location_failed: 1 },
    message: `QR code ${row.code} does not redirect to its target. @slack-qr-alerts`,
    tags: ['service:qr-redirects', `qr_code:${row.code}`],
  };
  const res = await fetch(`https://api.${DD_SITE}/api/v1/synthetics/tests/api`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'DD-API-KEY': DD_API_KEY,
      'DD-APPLICATION-KEY': DD_APP_KEY,
    },
    body: JSON.stringify(test),
  });
  if (!res.ok) throw new Error(`${row.code}: Datadog answered ${res.status}`);
}

Some notes:

  • The Synthetics API needs an API key and an application key.
  • tick_every is in seconds, and once an hour is enough for links that change rarely.
  • aws:eu-west-3 is a managed location in Paris. Pick locations close to your customers.
  • The script creates new tests on every run, so run it for new codes only or delete the old tests first.
  • The @slack-qr-alerts handle sends the alert to a Slack channel through the Datadog Slack integration.

A second test can follow redirects and check that the final page returns 200, which also catches a target page that was removed. With “follow redirects” on, Datadog follows up to ten redirects.

In practice

An international cosmetics retailer wanted QR codes on the packaging of its sample products. Working in the client’s architecture team, we built the generator in February 2026: a command-line tool that reads a CSV file or a list of URLs. For each row, it makes a QR code in SVG and PNG in the brand colours, with an optional logo in the middle. It also writes a table that maps each code to its link.

Each code holds a short link on the client’s domain, and a redirect sends that link to the target page, or to the home page until a target is set. The target can still change after the packaging is printed, and other teams own the redirects. The first use was 16 codes for 15 sample products.

In September 2026, the links got UTM parameters so that visits from the packaging show up in analytics. In November 2026, we added synthetic tests in Datadog that check the redirects of the short links. Read the case study on branded QR codes for packaging.

Checklist

  • Encode a short link on your own domain, never the final URL.
  • Redirect with 302 or 307, not 301.
  • Send codes without a target to a default page.
  • Add UTM parameters in the redirect, not in the code.
  • Use error correction level H when you add a logo.
  • Keep the logo small and away from the corner squares.
  • Keep the quiet zone and use dark modules on a light background.
  • Print a test at real size and scan it with several phones.
  • Keep the mapping table in version control.
  • Test every short link with a synthetic test that does not follow redirects.

For a review of your redirects, synthetic tests and alerts as part of your frontend monitoring, see the frontend observability assessment or get in touch.

Sources

Let's connect

Talk about your project

Tell us about your team and your problem. In 30 minutes we find out whether one of our offers fits, and if none does, we tell you.

Book a 30-minute call