Node.js QR Code Generator

Generate QR codes with Node.js. Express.js REST APIs, streaming responses, and npm package integration.

Popular npm Packages

Installation

npm install qrcode express

Basic Node.js Example

Generate & Save

const QRCode = require('qrcode');

// Generate and save as file
QRCode.toFile('qrcode.png', 'https://example.com', {
  color: {
    dark: '#000000',
    light: '#FFFFFF'
  }
}, (err) => {
  if (err) throw err;
  console.log('QR code saved!');
});

// Or get data URL
QRCode.toDataURL('https://example.com', (err, url) => {
  if (err) throw err;
  console.log(url); // data:image/png;base64,...
});

Express.js REST API

Full Server Example

const express = require('express');
const QRCode = require('qrcode');
const app = express();

// Generate and stream PNG
app.get('/generate', async (req, res) => {
  try {
    const { data, size = 300 } = req.query;
    
    if (!data) {
      return res.status(400).json({ error: 'Missing data parameter' });
    }
    
    res.type('image/png');
    
    await QRCode.toStream(res, data, {
      width: size,
      color: {
        dark: '#185FA5',
        light: '#FFFFFF'
      },
      errorCorrectionLevel: 'H'
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Generate and return data URL
app.get('/generate-data-url', async (req, res) => {
  try {
    const { data } = req.query;
    const dataUrl = await QRCode.toDataURL(data);
    
    res.json({ qrCode: dataUrl });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Generate and download as file
app.get('/download', async (req, res) => {
  try {
    const { data } = req.query;
    
    res.setHeader('Content-Disposition', 'attachment; filename="qrcode.png"');
    res.type('image/png');
    
    await QRCode.toStream(res, data);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(3000, () => {
  console.log('QR Code server running on :3000');
});

Async/Await Pattern

const QRCode = require('qrcode');
const fs = require('fs').promises;

async function generateQRCode(data, filename) {
  try {
    await QRCode.toFile(filename, data, {
      errorCorrectionLevel: 'H',
      width: 300
    });
    console.log(`✓ Generated ${filename}`);
  } catch (error) {
    console.error('Error generating QR code:', error);
  }
}

// Usage
await generateQRCode('https://example.com', 'qrcode.png');

Batch Processing

const QRCode = require('qrcode');
const fs = require('fs').promises;

async function batchGenerate(urls, outputDir) {
  // Create output directory if needed
  await fs.mkdir(outputDir, { recursive: true });
  
  for (let i = 0; i < urls.length; i++) {
    const filename = `${outputDir}/qr_${i + 1}.png`;
    
    await QRCode.toFile(filename, urls[i], {
      width: 300,
      errorCorrectionLevel: 'H'
    });
    
    console.log(`✓ Generated ${i + 1}/${urls.length}`);
  }
  
  console.log('✓ Batch complete!');
}

// Usage
const urls = [
  'https://example.com/1',
  'https://example.com/2',
  'https://example.com/3'
];

batchGenerate(urls, './qrcodes');

Middleware Integration

const qrMiddleware = (req, res, next) => {
  res.qr = async (data, options = {}) => {
    try {
      res.type('image/png');
      await QRCode.toStream(res, data, {
        width: options.size || 300,
        errorCorrectionLevel: options.errorCorrection || 'H',
        ...options
      });
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  };
  next();
};

app.use(qrMiddleware);

// Usage in routes
app.get('/qr', (req, res) => {
  res.qr(req.query.url);
});

Options & Customization

const options = {
  // Size of QR code
  width: 300,
  
  // Error correction level
  errorCorrectionLevel: 'H',  // L, M, Q, H
  
  // Type of output
  type: 'image/png',
  
  // Margin around QR code
  margin: 1,
  
  // Color settings
  color: {
    dark: '#000000',
    light: '#FFFFFF'
  },
  
  // Quality (for jpeg)
  quality: 0.95
};

await QRCode.toFile('qrcode.png', 'https://example.com', options);

Error Handling Best Practices

const generateSafe = async (data) => {
  try {
    // Validate input
    if (!data || typeof data !== 'string') {
      throw new Error('Invalid data');
    }
    
    if (data.length > 2953) {
      throw new Error('Data too long');
    }
    
    const qrCode = await QRCode.toDataURL(data);
    return qrCode;
    
  } catch (error) {
    console.error('QR generation failed:', error.message);
    throw error;
  }
};

Generate Your QR Codes

➜ Create QR Codes Now