Appearance
TypeScript / JavaScript SDK
Official TypeScript SDK for QR Code API with full type safety.
Installation
bash
npm install @qrcodeapi/sdk
# or
yarn add @qrcodeapi/sdk
# or
pnpm add @qrcodeapi/sdkQuick Start
typescript
import { QRCodeAPI } from '@qrcodeapi/sdk';
const client = new QRCodeAPI({
apiKey: process.env.QRCODE_API_KEY
});
// Generate a QR code
const qr = await client.generate({
data: 'https://example.com',
size: 400,
color: '22c55e'
});
// Save to file (Node.js)
import { writeFileSync } from 'fs';
writeFileSync('qr.png', Buffer.from(await qr.arrayBuffer()));
// Use in browser
const url = URL.createObjectURL(qr);
document.getElementById('qr').src = url;Configuration
typescript
import { QRCodeAPI } from '@qrcodeapi/sdk';
const client = new QRCodeAPI({
apiKey: 'your-api-key',
// Optional: Custom base URL (for self-hosted)
baseUrl: 'https://www.qrcodeapi.io/api',
// Optional: Request timeout in ms
timeout: 30000,
// Optional: Retry configuration
retry: {
maxRetries: 3,
retryDelay: 1000
}
});API Reference
generate()
Generate a QR code image.
typescript
interface GenerateOptions {
data: string; // Required: Content to encode
size?: number; // 50-2000 (default: 300)
format?: 'png' | 'svg'; // Output format (default: 'png')
color?: string; // Hex color without # (default: '000000')
background?: string; // Hex color without # (default: 'ffffff')
errorCorrection?: 'L' | 'M' | 'Q' | 'H'; // Default: 'M'
margin?: number; // 0-10 (default: 4)
logo?: string; // URL to logo image (Pro plan)
logoSize?: number; // 10-40 as % of QR size (default: 20)
}
const qr: Blob = await client.generate(options);createLink()
Create a dynamic link for trackable QR codes.
typescript
interface CreateLinkOptions {
name: string; // Display name
targetUrl: string; // Destination URL
}
interface DynamicLink {
id: string;
name: string;
shortCode: string;
targetUrl: string;
scanCount: number;
createdAt: string;
updatedAt: string;
}
const link: DynamicLink = await client.links.create({
name: 'My Campaign',
targetUrl: 'https://example.com'
});links.list()
Get all your dynamic links.
typescript
const { links }: { links: DynamicLink[] } = await client.links.list();links.get()
Get a single dynamic link by ID.
typescript
const link: DynamicLink = await client.links.get('link-id');links.update()
Update a dynamic link.
typescript
const updated: DynamicLink = await client.links.update('link-id', {
name: 'New Name',
targetUrl: 'https://new-url.com'
});links.delete()
Delete a dynamic link.
typescript
await client.links.delete('link-id');analytics.get()
Get scan analytics for a dynamic link.
typescript
interface AnalyticsOptions {
linkId: string;
startDate?: string; // ISO date
endDate?: string; // ISO date
}
interface Analytics {
totalScans: number;
uniqueScans: number;
scansByDay: { date: string; scans: number }[];
scansByCountry: { country: string; scans: number }[];
scansByDevice: { device: string; scans: number }[];
scansByBrowser: { browser: string; scans: number }[];
}
const analytics: Analytics = await client.analytics.get({
linkId: 'link-id',
startDate: '2024-01-01',
endDate: '2024-01-31'
});batch.generate()
Generate multiple QR codes at once (Pro plan).
typescript
interface BatchItem {
data: string;
filename?: string;
size?: number;
color?: string;
}
interface BatchOptions {
items: BatchItem[];
defaults?: Partial<GenerateOptions>;
}
const zip: Blob = await client.batch.generate({
items: [
{ data: 'https://example.com/1', filename: 'qr1.png' },
{ data: 'https://example.com/2', filename: 'qr2.png' }
],
defaults: {
size: 400,
color: '4f46e5'
}
});Complete Example
typescript
import { QRCodeAPI } from '@qrcodeapi/sdk';
import { writeFileSync } from 'fs';
async function main() {
const client = new QRCodeAPI({
apiKey: process.env.QRCODE_API_KEY!
});
// 1. Create a dynamic link
const link = await client.links.create({
name: 'Product Launch',
targetUrl: 'https://company.com/launch'
});
console.log(`Created link: ${link.shortCode}`);
// 2. Generate QR code for the link
const qr = await client.generate({
data: `https://www.qrcodeapi.io/r/${link.shortCode}`,
size: 500,
color: '1e40af',
errorCorrection: 'H'
});
writeFileSync('launch-qr.png', Buffer.from(await qr.arrayBuffer()));
console.log('Saved launch-qr.png');
// 3. Later: update the target URL
await client.links.update(link.id, {
targetUrl: 'https://company.com/launch-v2'
});
console.log('Updated link target');
// 4. Check analytics
const analytics = await client.analytics.get({ linkId: link.id });
console.log(`Total scans: ${analytics.totalScans}`);
}
main();Error Handling
typescript
import { QRCodeAPI, QRCodeAPIError } from '@qrcodeapi/sdk';
const client = new QRCodeAPI({ apiKey: 'your-key' });
try {
const qr = await client.generate({ data: 'test' });
} catch (error) {
if (error instanceof QRCodeAPIError) {
console.error(`API Error: ${error.message}`);
console.error(`Status: ${error.status}`);
console.error(`Code: ${error.code}`);
if (error.status === 429) {
console.log(`Retry after: ${error.retryAfter} seconds`);
}
} else {
throw error;
}
}TypeScript Types
All types are exported for your convenience:
typescript
import type {
GenerateOptions,
DynamicLink,
Analytics,
AnalyticsOptions,
BatchItem,
BatchOptions,
QRCodeAPIConfig,
QRCodeAPIError
} from '@qrcodeapi/sdk';React Integration
tsx
import { QRCodeAPI } from '@qrcodeapi/sdk';
import { useState, useEffect } from 'react';
const client = new QRCodeAPI({ apiKey: process.env.NEXT_PUBLIC_API_KEY });
function useQRCode(data: string, options?: Partial<GenerateOptions>) {
const [url, setUrl] = useState<string>('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
if (!data) return;
setLoading(true);
client.generate({ data, ...options })
.then(blob => setUrl(URL.createObjectURL(blob)))
.catch(setError)
.finally(() => setLoading(false));
}, [data, JSON.stringify(options)]);
return { url, loading, error };
}
// Usage
function QRCode({ data }: { data: string }) {
const { url, loading, error } = useQRCode(data, { size: 300 });
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return <img src={url} alt="QR Code" />;
}Node.js Streams
typescript
import { QRCodeAPI } from '@qrcodeapi/sdk';
import { createWriteStream } from 'fs';
import { Readable } from 'stream';
const client = new QRCodeAPI({ apiKey: process.env.API_KEY });
async function saveQRToStream(data: string, outputPath: string) {
const blob = await client.generate({ data });
const buffer = Buffer.from(await blob.arrayBuffer());
const stream = Readable.from(buffer);
return new Promise((resolve, reject) => {
stream
.pipe(createWriteStream(outputPath))
.on('finish', resolve)
.on('error', reject);
});
}Related
- JavaScript Guide - More examples
- API Reference - Full API docs
- npm Package - npm page