Tutorial

Build a QR Code Generator in 10 Minutes

Build a small web app that generates and downloads custom QR codes with the APIStack QR Code API, with the API key kept on the server.

By the APIStack team··Updated ·10 min read

A laptop, a tablet and a phone on a wooden desk

This tutorial builds a small web app that turns text or a URL into a QR code, with a choice of size and colours and a download link. It uses the APIStack QR Code API, plain HTML and JavaScript, and a short Node.js server with no dependencies. You need Node.js 18 or later and basic JavaScript.

The app has three files: a page, a browser script, and a server. The server exists for one reason: the API key must not be sent to the browser. The page calls your server, and your server calls APIStack.

Get an API key

Create a free account and copy your API key from the dashboard. The free plan includes 1,000 calls a month at up to 10 calls a minute, and each generated QR code is one call. If you want to see the output before writing any code, the QR code tool runs the same API in the browser.

Call the API once

The endpoint takes a POST request with a JSON body, authenticated with the x-api-key header. This request asks for a 300 pixel PNG that encodes a URL:

Shell
curl -X POST https://apistack.online/api/utilities/qr-code/v1 \
  -H "x-api-key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"type": "text", "text": "https://apistack.online", "format": "png", "size": 300}'

The response is JSON, not an image file. The image arrives as a data URL in data.qrCodeData. The example below is shortened; the real response also carries usage notes, an expiry time and your quota.

JSON
{
  "success": true,
  "message": "QR code generated successfully in PNG format",
  "data": {
    "qrCodeData": "data:image/png;base64,iVBORw0KGgo...",
    "filename": "qr-text-1763164800000-k3x9a2bq.png",
    "fileSize": 1874,
    "format": "png",
    "mimeType": "image/png",
    "metadata": {
      "type": "text",
      "size": 300,
      "margin": 4,
      "darkColor": "#000000",
      "lightColor": "#FFFFFF",
      "errorCorrectionLevel": "M"
    }
  }
}

The app reads two fields: data.qrCodeData, which works directly as an image source, and data.filename, which it uses as the download name. The response also has a data.downloadUrl field, but it can be null, so the tutorial does not depend on it.

These are the request parameters the app uses:

ParameterValuesDefault
typetext, url, wifi, vcard, email, sms, phone and otherstext
textThe content to encode for type text, up to 2,000 charactersrequired
formatpng, svg or dataurlpng
sizeWidth in pixels, 64 to 2048256
darkColorHex colour of the modules, including the ##000000
lightColorHex colour of the background, including the ##FFFFFF
errorCorrectionLevelL, M, Q or HM
marginQuiet zone around the code, in modules, up to 204

Write the server

Create a folder for the project and add a file named server.mjs. The server does two things: it serves the two static files, and it forwards POST /api/qr to APIStack with the key attached. It passes on only the four fields the page is allowed to set, and it relays the status code and the Retry-After header so the browser can react to errors.

JavaScript
import { createServer } from 'node:http'
import { readFile } from 'node:fs/promises'

const API_URL = 'https://apistack.online/api/utilities/qr-code/v1'
const API_KEY = process.env.APISTACK_API_KEY
const FILES = {
    '/': ['index.html', 'text/html; charset=utf-8'],
    '/script.js': ['script.js', 'text/javascript; charset=utf-8']
}

if (!API_KEY) {
    console.error('Set the APISTACK_API_KEY environment variable')
    process.exit(1)
}

function sendJson(res, status, body, headers = {}) {
    res.writeHead(status, { 'Content-Type': 'application/json', ...headers })
    res.end(typeof body === 'string' ? body : JSON.stringify(body))
}

async function generate(req, res) {
    let raw = ''
    for await (const chunk of req) raw += chunk

    let input
    try {
        input = JSON.parse(raw)
    } catch {
        return sendJson(res, 400, { success: false, error: 'Request body must be JSON' })
    }

    try {
        const upstream = await fetch(API_URL, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'x-api-key': API_KEY },
            body: JSON.stringify({
                type: 'text',
                text: input.text,
                format: 'png',
                size: input.size,
                darkColor: input.darkColor,
                lightColor: input.lightColor
            })
        })
        const retryAfter = upstream.headers.get('retry-after')
        sendJson(res, upstream.status, await upstream.text(), retryAfter ? { 'Retry-After': retryAfter } : {})
    } catch {
        sendJson(res, 502, { success: false, error: 'Could not reach the QR Code API' })
    }
}

createServer(async (req, res) => {
    if (req.method === 'POST' && req.url === '/api/qr') return generate(req, res)

    const file = FILES[req.url]
    if (req.method === 'GET' && file) {
        res.writeHead(200, { 'Content-Type': file[1] })
        return res.end(await readFile(new URL(file[0], import.meta.url)))
    }
    res.writeHead(404)
    res.end()
}).listen(3000, () => console.log('Open http://localhost:3000'))

Build the page

Add index.html next to the server. It is a form with a text area, a size field limited to the range the API accepts, and two colour pickers, followed by an empty image and a download link that stay hidden until there is a QR code to show.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>QR Code Generator</title>
    <style>
        body { font-family: system-ui, sans-serif; max-width: 420px; margin: 40px auto; padding: 0 16px; }
        label { display: block; margin-top: 16px; font-weight: 600; }
        textarea, input[type="number"] { width: 100%; padding: 8px; box-sizing: border-box; }
        button { margin-top: 20px; padding: 10px 16px; }
        img { display: block; max-width: 100%; margin: 24px 0 12px; }
    </style>
</head>
<body>
    <h1>QR Code Generator</h1>
    <form id="qr-form">
        <label for="qr-text">Text or URL</label>
        <textarea id="qr-text" rows="3" maxlength="2000" required placeholder="https://example.com"></textarea>

        <label for="qr-size">Size in pixels</label>
        <input type="number" id="qr-size" value="300" min="64" max="2048" required>

        <label for="qr-dark">Code colour</label>
        <input type="color" id="qr-dark" value="#000000">

        <label for="qr-light">Background colour</label>
        <input type="color" id="qr-light" value="#ffffff">

        <button type="submit" id="generate-btn">Generate QR code</button>
    </form>

    <p id="status" role="status"></p>
    <img id="qr-image" alt="Generated QR code" hidden>
    <a id="download-link" hidden>Download PNG</a>

    <script src="script.js"></script>
</body>
</html>

Add the browser script

Create script.js. On submit it posts the form values to /api/qr, then puts the returned data URL into the image and the download link. A colour input always produces a six-digit hex value with the #, which is the format the API expects, so the values go through unchanged.

JavaScript
const form = document.getElementById('qr-form')
const button = document.getElementById('generate-btn')
const status = document.getElementById('status')
const image = document.getElementById('qr-image')
const downloadLink = document.getElementById('download-link')

async function generateQR() {
    const response = await fetch('/api/qr', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            text: document.getElementById('qr-text').value.trim(),
            size: Number(document.getElementById('qr-size').value),
            darkColor: document.getElementById('qr-dark').value,
            lightColor: document.getElementById('qr-light').value
        })
    })
    const result = await response.json()

    if (response.status === 429) {
        const seconds = response.headers.get('Retry-After')
        throw new Error(seconds ? `Too many requests. Try again in ${seconds} seconds.` : result.error)
    }
    if (!response.ok || !result.success) {
        throw new Error(result.error || 'Could not generate the QR code')
    }

    image.src = result.data.qrCodeData
    image.hidden = false
    downloadLink.href = result.data.qrCodeData
    downloadLink.download = result.data.filename
    downloadLink.hidden = false
}

form.addEventListener('submit', async (event) => {
    event.preventDefault()
    button.disabled = true
    status.textContent = 'Generating...'
    try {
        await generateQR()
        status.textContent = ''
    } catch (error) {
        status.textContent = error.message
    } finally {
        button.disabled = false
    }
})

Because the image is a data URL, the download link needs no second request: the browser saves the same bytes it is already showing, under the file name the API returned.

Run and test it

Start the server with your key in the environment, then open http://localhost:3000:

Shell
APISTACK_API_KEY=your_key_here node server.mjs

Generate a code for a URL and scan it with a phone camera to confirm it opens the right page. Then change the colours and the size and generate again. Each press of the button is one API call, so there is no reason to regenerate on every keystroke.

Handle errors

Every error response has "success": false and an error string, and the script shows that string under the form. Three cases are worth knowing.

A 400 means the input failed validation, and the message says which field: empty text, text over 2,000 characters, a size outside 64 to 2048, or a colour that is not a hex value. A 401 means the key is missing or wrong, so check the APISTACK_API_KEY variable. A 429 means you are over a limit, either the per-minute rate limit, in which case the response carries a Retry-After header with the number of seconds to wait, or the monthly quota. The pricing page lists the larger plans and the top-up option.

If a generated code will not scan, the cause is almost always contrast or size. Use a dark code on a light background, not the reverse, and keep the default margin, because scanners rely on the quiet zone around the code.

Extend it

The same endpoint covers the common next steps without any new code on the server beyond passing more fields through.

For print, request "format": "svg". The response then carries the markup in data.svgContent, which scales to any size without blurring.

For a code that will be printed small, or may get scratched or partly covered, raise errorCorrectionLevel. The four levels trade capacity for redundancy: L recovers the least damage and H the most, as described in the QR code error correction overview from Denso Wave, the format's inventor. Higher levels produce a denser code for the same content.

For structured content, change type and send the fields in a data object. This body produces a code that joins a phone to a Wi-Fi network when scanned:

JSON
{
  "type": "wifi",
  "data": { "ssid": "Office Guest", "password": "correct-horse-battery", "security": "WPA" },
  "format": "png",
  "size": 400
}

Summary

  • The QR Code API is a POST to https://apistack.online/api/utilities/qr-code/v1 with an x-api-key header and a JSON body.
  • The response is JSON; the image is a data URL in data.qrCodeData, and data.filename gives a download name.
  • Keep the API key on a server and have the page call your own endpoint.
  • Colours are hex values with the #, sizes run from 64 to 2048 pixels, and text is limited to 2,000 characters.
  • Show the API's error message to the user, and honour Retry-After on a 429.

Build with APIStack

One API key for validation, dates and holidays, web checks and reference data, over REST or as MCP tools for your AI agents. The free plan includes 1,000 calls a month.

Keep reading