Overview
Integrate QrX into your Node.js applications using popular HTTP libraries like Axios or the native fetch API (Node.js 18+).Installation
Using Axios (Recommended)
Copy
npm install axios
Using Native Fetch
Available in Node.js 18+ (no installation needed).Basic Usage
With Axios
Copy
const axios = require("axios");
const fs = require("fs");
axios({
url: "https://qrgen.maybesurya.live/api/qrgen",
method: "GET",
params: { data: "Hello World" },
responseType: "stream",
})
.then((response) => {
response.data.pipe(fs.createWriteStream("qrcode.png"));
console.log("✓ QR code saved!");
})
.catch((error) => {
console.error("✗ Error:", error.message);
});
With Native Fetch (Node.js 18+)
Copy
const fs = require("fs");
const { Readable } = require("stream");
const { finished } = require("stream/promises");
async function generateQRCode() {
const response = await fetch(
"https://qrgen.maybesurya.live/api/qrgen?data=Hello%20World"
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const body = Readable.fromWeb(response.body);
const fileStream = fs.createWriteStream("qrcode.png");
await finished(body.pipe(fileStream));
console.log("✓ QR code saved!");
}
generateQRCode().catch(console.error);
Authenticated Requests
With API Key (Axios)
Copy
const axios = require("axios");
const fs = require("fs");
const apiKey = process.env.QRX_API_KEY; // Store in environment variable
axios({
url: "https://qrgen.maybesurya.live/api/qrgen",
method: "GET",
params: { data: "Hello World" },
headers: { "x-api-key": apiKey },
responseType: "stream",
})
.then((response) => {
response.data.pipe(fs.createWriteStream("qrcode.png"));
console.log("✓ QR code generated successfully!");
})
.catch((error) => {
if (error.response) {
console.error(`✗ Error: HTTP ${error.response.status}`);
} else {
console.error("✗ Network error:", error.message);
}
});
Set your API key as an environment variable:
bash export QRX_API_KEY="sk_YOUR_API_KEY" Or use a .env file with the dotenv
package.Complete Examples
QR Code Generator Module
Copy
// qrx-client.js
const axios = require("axios");
const fs = require("fs").promises;
const path = require("path");
class QRXClient {
constructor(apiKey = null) {
this.baseURL = "https://qrgen.maybesurya.live/api";
this.apiKey = apiKey || process.env.QRX_API_KEY;
this.client = axios.create({
baseURL: this.baseURL,
timeout: 10000,
headers: this.apiKey ? { "x-api-key": this.apiKey } : {},
});
}
async generate(data, outputPath) {
try {
const response = await this.client.get("/qrgen", {
params: { data },
responseType: "arraybuffer",
});
await fs.writeFile(outputPath, response.data);
return {
success: true,
path: outputPath,
data: data,
};
} catch (error) {
return {
success: false,
error: this.handleError(error),
data: data,
};
}
}
async batchGenerate(items, options = {}) {
const { delay = 600, outputDir = "." } = options;
const results = [];
for (let i = 0; i < items.length; i++) {
const item = items[i];
const outputPath = path.join(outputDir, item.filename);
console.log(`Processing ${i + 1}/${items.length}: ${item.data}`);
const result = await this.generate(item.data, outputPath);
results.push(result);
if (result.success) {
console.log(` ✓ Saved to ${result.path}`);
} else {
console.log(` ✗ Error: ${result.error}`);
}
// Delay between requests (respect rate limits)
if (i < items.length - 1) {
await this.sleep(delay);
}
}
return results;
}
handleError(error) {
if (error.response) {
const status = error.response.status;
switch (status) {
case 429:
return "Rate limit exceeded. Please wait and try again.";
case 401:
return "Invalid API key.";
case 400:
return "Bad request. Check your parameters.";
default:
return `HTTP error: ${status}`;
}
} else if (error.request) {
return "Network error. Please check your connection.";
} else {
return error.message;
}
}
sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
}
module.exports = QRXClient;
// Usage:
// const QRXClient = require('./qrx-client');
// const client = new QRXClient(process.env.QRX_API_KEY);
// await client.generate('https://maybesurya.dev', 'qrcode.png');
Express.js Integration
Copy
// server.js
const express = require("express");
const axios = require("axios");
require("dotenv").config();
const app = express();
const PORT = process.env.PORT || 3000;
const QRX_API_KEY = process.env.QRX_API_KEY;
app.get("/api/generate-qr", async (req, res) => {
const { data } = req.query;
if (!data) {
return res.status(400).json({ error: "Missing data parameter" });
}
try {
const response = await axios({
url: "https://qrgen.maybesurya.live/api/qrgen",
method: "GET",
params: { data },
headers: QRX_API_KEY ? { "x-api-key": QRX_API_KEY } : {},
responseType: "arraybuffer",
timeout: 10000,
});
res.set("Content-Type", "image/png");
res.set("Content-Disposition", 'inline; filename="qrcode.png"');
res.send(response.data);
} catch (error) {
console.error("Error generating QR code:", error.message);
if (error.response) {
const status = error.response.status;
if (status === 429) {
return res.status(429).json({ error: "Rate limit exceeded" });
} else if (status === 401) {
return res.status(401).json({ error: "Invalid API key" });
}
}
res.status(500).json({ error: "Failed to generate QR code" });
}
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
CLI Tool
Copy
#!/usr/bin/env node
// qrx-cli.js
const axios = require("axios");
const fs = require("fs").promises;
const { program } = require("commander");
require("dotenv").config();
program
.name("qrx")
.description("Generate QR codes using QrX API")
.version("1.0.0");
program
.argument("<data>", "Data to encode in QR code")
.option("-o, --output <path>", "Output file path", "qrcode.png")
.option("-k, --api-key <key>", "API key for authentication")
.action(async (data, options) => {
const apiKey = options.apiKey || process.env.QRX_API_KEY;
try {
console.log("Generating QR code...");
const response = await axios({
url: "https://qrgen.maybesurya.live/api/qrgen",
method: "GET",
params: { data },
headers: apiKey ? { "x-api-key": apiKey } : {},
responseType: "arraybuffer",
timeout: 10000,
});
await fs.writeFile(options.output, response.data);
console.log(`✓ QR code saved to ${options.output}`);
} catch (error) {
if (error.response) {
const status = error.response.status;
if (status === 429) {
console.error("✗ Rate limit exceeded. Please wait and try again.");
} else if (status === 401) {
console.error("✗ Invalid API key.");
} else {
console.error(`✗ HTTP error: ${status}`);
}
} else {
console.error("✗ Error:", error.message);
}
process.exit(1);
}
});
program.parse();
// Usage:
// node qrx-cli.js "https://maybesurya.dev"
// node qrx-cli.js "Hello World" -o hello.png
Batch Processing Script
Copy
// batch-generate.js
const QRXClient = require("./qrx-client");
const fs = require("fs").promises;
async function batchGenerateFromFile(inputFile, outputDir) {
// Read URLs from file
const content = await fs.readFile(inputFile, "utf-8");
const urls = content.split("\n").filter((line) => line.trim());
// Prepare batch items
const items = urls.map((url, index) => ({
data: url,
filename: `qr-${index + 1}.png`,
}));
// Generate QR codes
const client = new QRXClient(process.env.QRX_API_KEY);
const results = await client.batchGenerate(items, { outputDir });
// Print summary
const successful = results.filter((r) => r.success).length;
console.log(`\nCompleted: ${successful}/${results.length} successful`);
}
// Usage
batchGenerateFromFile("urls.txt", "./qrcodes").catch(console.error);
With TypeScript
Copy
// qrx-client.ts
import axios, { AxiosInstance } from "axios";
import * as fs from "fs/promises";
interface GenerateResult {
success: boolean;
path?: string;
error?: string;
data: string;
}
interface BatchItem {
data: string;
filename: string;
}
interface BatchOptions {
delay?: number;
outputDir?: string;
}
class QRXClient {
private client: AxiosInstance;
private apiKey: string | null;
constructor(apiKey: string | null = null) {
this.apiKey = apiKey || process.env.QRX_API_KEY || null;
this.client = axios.create({
baseURL: "https://qrgen.maybesurya.live/api",
timeout: 10000,
headers: this.apiKey ? { "x-api-key": this.apiKey } : {},
});
}
async generate(data: string, outputPath: string): Promise<GenerateResult> {
try {
const response = await this.client.get("/qrgen", {
params: { data },
responseType: "arraybuffer",
});
await fs.writeFile(outputPath, response.data);
return {
success: true,
path: outputPath,
data,
};
} catch (error) {
return {
success: false,
error: this.handleError(error),
data,
};
}
}
private handleError(error: any): string {
if (error.response) {
const status = error.response.status;
switch (status) {
case 429:
return "Rate limit exceeded";
case 401:
return "Invalid API key";
default:
return `HTTP error: ${status}`;
}
}
return error.message || "Unknown error";
}
}
export default QRXClient;
Best Practices
✅ Do: - Use environment variables for API keys - Implement proper error
handling - Use streaming for large files - Respect rate limits with delays -
Set reasonable timeouts
❌ Don’t: - Hardcode API keys in your code - Ignore HTTP status codes -
Make requests without error handling - Exceed rate limits - Commit
.env
files to Git