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
- Basic knowledge of JavaScript
- Node.js installed (for server-side examples)
- A free QR Code API key (get one here)
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:
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:
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:
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:
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:
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
- Create dynamic QR codes that can be updated after creation
- Track QR code scans with analytics
- Add your logo to QR codes
- Check out our Node.js integration guide for more examples
Ready to Generate QR Codes?
Get your free API key and start generating QR codes in JavaScript today.
Get Your Free API Key