How to Generate QR Codes in JavaScript

A complete guide to generating QR codes using JavaScript, including Node.js and browser examples with the QR Code API.

📅 Updated December 2025 ⏱️ 8 min read

QR codes are everywhere—from restaurant menus to payment systems. In this tutorial, you'll learn how to generate QR codes in JavaScript using the QR Code API. We'll cover both Node.js (server-side) and browser (client-side) implementations.

Prerequisites

Quick Start (5 Minutes)

1Get Your API Key

Sign up at qrcodeapi.io to get your free API key. You'll get 100 free QR codes per month.

2Make Your First Request

Here's the simplest way to generate a QR code:

JavaScript (Node.js)
const generateQRCode = async (data) => {
  const response = await fetch('https://www.qrcodeapi.io/api/generate', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      data: data,
      size: 300,
      format: 'png'
    })
  });
  
  return response.blob();
};

// Usage
const qrCode = await generateQRCode('https://example.com');

Node.js Implementation

For server-side applications, here's a complete implementation with error handling:

Node.js - Complete Example
const fs = require('fs');

async function generateAndSaveQR(data, filename) {
  try {
    const response = await fetch('https://www.qrcodeapi.io/api/generate', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.QR_API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        data: data,
        size: 400,
        format: 'png',
        color: '#000000',
        background: '#ffffff',
        errorCorrection: 'M'
      })
    });

    if (!response.ok) {
      throw new Error(`API error: ${response.status}`);
    }

    const buffer = Buffer.from(await response.arrayBuffer());
    fs.writeFileSync(filename, buffer);
    
    console.log(`QR code saved to ${filename}`);
    return filename;
  } catch (error) {
    console.error('Failed to generate QR code:', error);
    throw error;
  }
}

// Generate a QR code
generateAndSaveQR('https://mywebsite.com', 'qrcode.png');

Browser Implementation

For client-side JavaScript, you can display the QR code directly in an image element:

Browser JavaScript
async function displayQRCode(data, imgElement) {
  const response = await fetch('https://www.qrcodeapi.io/api/generate', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ data, size: 300, format: 'png' })
  });
  
  const blob = await response.blob();
  const url = URL.createObjectURL(blob);
  imgElement.src = url;
}

// Usage
const img = document.getElementById('qr-code');
displayQRCode('https://example.com', img);

Customization Options

The API supports various customization options:

Full Options Example
const options = {
  data: 'https://example.com',    // Required: URL or text to encode
  size: 400,                         // Size in pixels (default: 200)
  format: 'png',                   // 'png' or 'svg'
  color: '#1a1a1a',                // QR code color
  background: '#ffffff',           // Background color
  errorCorrection: 'H',            // L, M, Q, or H
  margin: 4                          // Quiet zone margin
};

Error Handling Best Practices

Always handle errors gracefully in production:

Error Handling
async function safeGenerateQR(data) {
  try {
    const response = await fetch('https://www.qrcodeapi.io/api/generate', {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ data })
    });

    if (response.status === 401) {
      throw new Error('Invalid API key');
    }
    
    if (response.status === 429) {
      throw new Error('Rate limit exceeded');
    }
    
    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message);
    }
    
    return await response.blob();
  } catch (error) {
    console.error('QR generation failed:', error.message);
    return null;
  }
}

Next Steps

Ready to Generate QR Codes?

Get your free API key and start generating QR codes in JavaScript today.

Get Your Free API Key