GuidesDevelopers

How to generate QR codes in Node.js

Generate QR codes in Node.js with the qrcode package for static codes, or with the PikaQR API for dynamic codes you can change and track.

The short answer

For a code that never needs to change, install the qrcode package from npm and call QRCode.toFile or QRCode.toString. It runs on your own machine, needs no account, and takes three lines.

For a code you’ll want to change after it’s printed, or count scans for, create a dynamic code with an HTTP request to the PikaQR API. You get back a short link and an image, and you can change where it goes later.

Static or dynamic: which do you need?

A static code holds its content in the pattern itself. Once it’s printed, it can’t change, and nobody can tell how often it’s scanned. That’s fine for a Wi-Fi password on a fridge, a link on a ticket that’s thrown away the next day, or anything you draw on screen and never print.

A dynamic code holds a short link instead. When someone scans it, the link decides where they go. You can change the destination from your own code, add rules, and read every scan. Pick dynamic for anything printed in numbers, stuck to a wall, or used in a campaign you want to measure.

Static codes with the qrcode package

The qrcode package is the common choice for Node.js. It writes PNG and SVG files, returns data URLs for an img tag, and works in the browser too. Install it, then save the sample as a .mjs file so top-level await works.

// npm install qrcode
// Save as static.mjs and run: node static.mjs
import QRCode from 'qrcode';

const url = 'https://example.com/menu';

// A PNG file, 600 pixels wide
await QRCode.toFile('menu.png', url, {
  width: 600,
  margin: 4,
  errorCorrectionLevel: 'M',
});

// An SVG, which stays sharp at any print size
const svg = await QRCode.toString(url, { type: 'svg', margin: 4 });
console.log(svg.length, 'characters of SVG');

// A data URL you can put straight into <img src="...">
const dataUrl = await QRCode.toDataURL(url, { width: 300 });
console.log(dataUrl.slice(0, 40));

Options worth knowing

A few settings decide whether a code prints well and scans easily.

  • width: the image width in pixels. Make print files large and let the printer scale them down.
  • margin: the quiet zone around the code, in modules. Keep it at 4 for print. Scanners need that clear border.
  • errorCorrectionLevel: L, M, Q or H. Higher levels survive more damage but need more squares. M is a sensible default.
  • color: an object with dark and light hex colors. Keep strong contrast, with the dark color on the squares.
// Save as wifi.mjs and run: node wifi.mjs
import QRCode from 'qrcode';

// A Wi-Fi code: phones offer to join the network when they scan it.
// Escape \ ; , : and " in the name or password with a backslash.
const wifi = 'WIFI:T:WPA;S:Lobby Guest;P:welcome2027;;';

await QRCode.toFile('wifi.png', wifi, {
  width: 800,
  margin: 4,
  errorCorrectionLevel: 'Q',
  color: { dark: '#1a1a2e', light: '#ffffff' },
});

Serve a code from a web route

To show a code on a page, you don’t need to save a file. QRCode.toBuffer returns the PNG as bytes, and you send them with an image/png content type. The sample uses Node’s own http module, and the same two lines work inside an Express or Fastify handler.

Codes made this way are drawn fresh on every request, which is cheap. If the same text is asked for often, cache the result.

// Save as server.mjs, run: node server.mjs
// then open http://localhost:3000/qr?text=hello
import { createServer } from 'node:http';
import QRCode from 'qrcode';

createServer(async (req, res) => {
  const text = new URL(req.url, 'http://localhost').searchParams.get('text');
  if (!text) {
    res.writeHead(400).end('Add ?text= to the address');
    return;
  }
  const png = await QRCode.toBuffer(text, { width: 400, margin: 4 });
  res.writeHead(200, { 'Content-Type': 'image/png' }).end(png);
}).listen(3000);

Dynamic codes with the PikaQR API

Sign up for free, open the Developers page in your dashboard and create an API key. Keep it in an environment variable rather than in your code. Node.js 18 and later has fetch built in, so you don’t need another package.

One POST creates the code. The reply has its id and its short_url, which is what the printed code holds. A second request fetches the image as a PNG or an SVG, from 64 to 2048 pixels wide.

// Save as dynamic.mjs and run: PIKAQR_KEY=pk_... node dynamic.mjs
import { writeFile } from 'node:fs/promises';

const BASE = 'https://pikaqr.com/api/v1';
const auth = { Authorization: `Bearer ${process.env.PIKAQR_KEY}` };

const res = await fetch(`${BASE}/qr`, {
  method: 'POST',
  headers: { ...auth, 'Content-Type': 'application/json' },
  body: JSON.stringify({
    title: 'Spring flyer',
    destination_url: 'https://example.com/spring',
    tags: ['flyers'],
    metadata: { campaign: 'spring-2027' },
  }),
});

const code = await res.json();
if (!res.ok) throw new Error(`${code.code}: ${code.error}`);
console.log(code.id, code.short_url);

// The image holds the short link, so it keeps working when the destination changes.
const image = await fetch(`${BASE}/qr/${code.id}/image?format=png&size=1024`, { headers: auth });
await writeFile('spring-flyer.png', Buffer.from(await image.arrayBuffer()));

Change it and count the scans

Send a new destination_url with PATCH, and every printed copy goes to the new address straight away. The old one stays in the code’s history.

Read totals from the analytics endpoint. It returns total and unique scans, and counts by day, device, country and language. The Free plan covers the last 7 days.

// Save as update.mjs and run: PIKAQR_KEY=pk_... CODE_ID=... node update.mjs
const BASE = 'https://pikaqr.com/api/v1';
const auth = { Authorization: `Bearer ${process.env.PIKAQR_KEY}` };
const id = process.env.CODE_ID;

// Point the printed code somewhere new
const update = await fetch(`${BASE}/qr/${id}`, {
  method: 'PATCH',
  headers: { ...auth, 'Content-Type': 'application/json' },
  body: JSON.stringify({ destination_url: 'https://example.com/summer' }),
});
console.log(await update.json()); // { success: true, version: 2 }

// How many scans in the last 7 days
const stats = await fetch(`${BASE}/qr/${id}/analytics?days=7`, { headers: auth }).then((r) => r.json());
console.log(stats.total_scans, 'scans,', stats.unique_scans, 'unique');

Handle errors and limits

Every error has an error sentence for people and a code for programs, such as plan_limit or invalid_destination. Match on the code: it won’t change.

The Free plan allows 1,000 requests an hour and Premium allows 10,000. Each reply carries X-RateLimit-Remaining. If you go over, you get a 429 with a Retry-After header, in seconds. Wait that long and send the same request again.

On Premium you can also add a webhook, and each scan arrives at your server as a signed POST, with the metadata you attached to the code.

Questions

Which npm package should I use to generate QR codes?

The qrcode package is the usual choice. It makes PNG files, SVG strings and data URLs, and runs in Node.js and in the browser. It only makes static codes.

Can I generate a QR code in Node.js without a package?

Not sensibly. Encoding a QR code means error correction and masking, which is a lot of code to write and test. Use a package for static codes, or the PikaQR API, which returns the finished image.

How big should the QR code image be?

For screens, 300 to 400 pixels is plenty. For print, make it large, such as 1000 pixels, or use SVG, and keep the printed code at least 2 cm (0.8 in) wide.

Can I change a QR code made with the qrcode package?

No. The content is in the pattern, so a new destination means a new code. If it might change, create a dynamic code with the API instead.

Make a code you can change

Get a free API key and create dynamic QR codes you can track and point somewhere new at any time.

Get a free API key

More guides

How to generate QR codes in PythonDynamic vs static QR codes: which one do you need?How to make a QR code menu for your restaurantWhat size should a QR code be for print?
How to generate QR codes in Node.js · PikaQR