Dashboard

How to add QR codes to an AI-built app

Add QR codes to an AI-built app the way that holds up in print: static versus redirect codes, error correction, SVG code and an open-redirect trap.

Steve Jefferson
Steve Jefferson
Developer Advocate
18 October 20261 min read

To add QR codes to an AI-built app, encode a short URL that you control, not the final destination, generate the image on the server as SVG, and treat the redirect as security-sensitive code. That one choice, destination versus redirect, decides whether a printed code can ever be fixed after it leaves your building. Everything else is a library call.

This guide assumes you describe features to an AI builder and review what comes back. The prompts and checks below are written for that workflow.

How to add QR codes to an AI-built app: static or redirect

A QR code is just a picture of a string. Two designs matter.

Static. The string is the final URL, for example https://yourapp.com/events/42/checkin. It is simple and needs no database. But once it is printed on a poster, a badge or a menu, it cannot change. If the route moves or the event ends, every printed copy points at a dead page.

Redirect. The string is a short link such as https://yourapp.com/q/k3x9ab. Your app looks that code up and sends the visitor to the current destination. You can change the target later, count scans and switch a code off.

For anything printed or shared outside your control, use redirect. For a code that appears on screen for a few seconds, such as a login handoff to a phone, static is fine.

Where QR codes earn their place in an app

A QR code is worth adding when someone moves between a physical thing and your app. Typical cases:

  • Check-in: a code on a ticket, badge or table that opens the right record.

  • Handoff from desktop to phone: a code on a laptop screen that opens the same item on a phone, so nobody types a long URL.

  • Printed material: flyers, packaging, signs and receipts that point to a page you may need to change later.

  • Sharing a resource in a room: a code on a slide that opens a form or a document.

If nobody will ever hold a phone near it, a plain link is simpler. Always print the short URL in text beside the code as well, for people whose camera does not scan it and for accessibility.

The data model for redirect codes

Ask your AI builder for this table, and read the migration before it runs:

sql
create table qr_links (
  id          uuid primary key default gen_random_uuid(),
  code        text not null unique,        -- short random string, e.g. 8 chars
  target_path text not null,               -- relative path inside your app
  owner_id    uuid not null references users(id),
  active      boolean not null default true,
  scan_count  integer not null default 0,
  created_at  timestamptz not null default now()
);
create index on qr_links (owner_id);

Two design decisions are worth noticing. The code is random, not a counter, so people cannot walk through q/1, q/2 and find other users' links. And target_path is a relative path inside your own app, not a full URL. The second one is the security point, covered below.

Generating the image

The qrcode package for Node (MIT licensed) produces SVG strings and PNG data URLs. Its README shows QRCode.toString(text, { type: 'svg' }) for vector output and QRCode.toDataURL(text) for PNG, with PNG as the default type (node-qrcode on GitHub).

A server route that returns the SVG:

js
import QRCode from 'qrcode';

app.get('/api/qr/:code.svg', async (req, res) => {
  const link = await db.qrLinks.findActiveByCode(req.params.code);
  if (!link) return res.status(404).end();

  const url = `${process.env.PUBLIC_BASE_URL}/q/${link.code}`;
  const svg = await QRCode.toString(url, {
    type: 'svg',
    errorCorrectionLevel: 'Q',
    margin: 4,
  });

  res.type('image/svg+xml').send(svg);
});

Prefer SVG over PNG for anything that may be printed. It stays sharp at any size, and it is small. Keep the base URL in an environment variable, not a literal, so staging codes never point at production.

Pick an error correction level on purpose

QR codes carry redundancy so a damaged or partly covered code still scans. The library documents four levels and the share of damaged surface each tolerates: L about 7 percent, M about 15 percent, Q about 25 percent and H about 30 percent. Its default is M. Higher levels survive more damage but store less data, which makes the pattern denser.

A practical rule for this use:

  • On a screen: M is fine.

  • Printed and handled, such as stickers, table tents, badges: Q.

  • Printed with a logo in the middle: H, and test it, because the logo covers real data.

Because your payload is a short redirect URL, density is barely a concern. That is another reason the redirect design is kind to print.

The redirect route, and the open-redirect trap

The route that visitors hit looks harmless:

js
app.get('/q/:code', async (req, res) => {
  const link = await db.qrLinks.findActiveByCode(req.params.code);
  if (!link) return res.status(404).send('This code is no longer active.');

  await db.qrLinks.incrementScans(link.id);

  // target_path is validated at write time to start with a single "/"
  res.redirect(302, link.target_path);
});

The trap: if target_path could hold any URL, your domain becomes a trusted launcher for anyone's phishing page. A printed code from your brand that sends people somewhere else is exactly the thing an attacker wants. Close it in two places:

  1. At write time, accept only paths that start with a single / and not //, and reject anything containing a scheme or backslash.

  2. At read time, re-check before redirecting. Data can be edited later by a path you forgot.

Check this specifically when reviewing AI output. A generated redirect handler can easily accept a url parameter and pass it straight to res.redirect. Ask: what happens if I put https://example.com in the target field?

Use 302, not 301. A 301 is cached hard by browsers, which defeats the point of being able to change the destination.

Who may create and see codes

A code can reveal that a page exists. Apply the same ownership rule you use elsewhere: only the owner, or an admin, can create, edit or deactivate a code. If your app has roles, role-based access control for an AI-built app shows the pattern. And a QR that grants entry, such as a team invite, should carry a single-use token with an expiry, not a permanent link. Team invites in an AI-built app covers the token design.

Most failed codes fail in the physical world, not in the code:

  • Quiet zone. Keep the blank margin around the code, which is why the generator call above sets margin: 4. Do not let a design tool crop it.

  • Contrast. Dark code on a light background. Inverted codes scan poorly on some readers.

  • Size and distance. A code on a poster read from across a room needs to be much larger than one on a business card. Test at the real distance.

  • Surface. Glossy lamination and curved packaging cause glare. Test on the actual material.

Scan analytics, kept modest

scan_count is enough for most apps. If you also log time and a coarse device type, say so in your privacy page and do not store IP addresses you do not need. A counter you never read is a cost without a benefit.

Test like a customer

  1. Open the generated SVG at its smallest intended print size and scan it with two different phones, one older.

  2. Scan from an angle and in dim light.

  3. Deactivate the code in the database and confirm the "no longer active" page appears.

  4. Try the open-redirect probe described above.

  5. Print one copy on the actual material and scan it again.

A prompt to start from

Add QR code support. Create a qr_links table with a random 8 character code, a relative target_path, an owner, an active flag and a scan counter. Add GET /q/:code that increments the counter and redirects with a 302 to target_path, only when active. Reject any target_path that does not start with a single slash. Add GET /api/qr/:code.svg that returns an SVG with error correction level Q, 4 modules of margin and the base URL from an environment variable. Only the owner can create or deactivate codes.

Read the diff before accepting it. If you want a worked example of the same idea in a business setting, a QR code menu for a restaurant walks through one. The wider approach is in how to build an app with AI.

QR Code is a registered trademark of Denso Wave Incorporated, a note the library's own README carries, and one reason to say "QR code" in your UI and not use a stylised mark.

FAQ

Should a QR code contain the final URL or a short redirect?

Use a short redirect for anything printed, so you can change the destination and switch codes off. Use the final URL only for codes that live on a screen briefly.

Which error correction level should I use?

M for screens, Q for printed codes that get handled, and H only when you place a logo over the centre and have tested it.

Is SVG or PNG better for a QR code?

SVG for anything that will be printed or resized. PNG is fine for email or a quick download.

Can a QR code redirect be a security risk?

Yes. If the destination is not restricted to paths inside your own app, the code can become an open redirect that sends people to a malicious page under your brand.

How did this land?

About the author

Steve Jefferson
Steve Jefferson

Developer Advocate

Steve builds something with Swarmz every week and writes up what worked, what broke, and what he'd do differently. Tutorials and hands-on guides are his lane.

Share

Get the next post in your inbox

One email a month. Product updates, engineering posts, and the best of Built with Swarmz.

I agree to receive emails about AI building tips and Swarmz product news. Unsubscribe any time.