Skip to main content

Overview

These examples work in any modern browser. Just use the standard Fetch API - no libraries needed!

Basic Usage

Simple Fetch Request

fetch("https://qrgen.maybesurya.live/api/qrgen?data=Hello%20World")
  .then((response) => response.blob())
  .then((blob) => {
    const imageUrl = URL.createObjectURL(blob);
    const img = document.createElement("img");
    img.src = imageUrl;
    document.body.appendChild(img);
  })
  .catch((error) => console.error("Error:", error));

With Authentication

Using Your API Key

const apiKey = "YOUR_API_KEY"; // Keep this secret!

fetch("https://qrgen.maybesurya.live/api/qrgen?data=Hello%20World", {
  headers: {
    "x-api-key": apiKey,
  },
})
  .then((response) => {
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.blob();
  })
  .then((blob) => {
    const imageUrl = URL.createObjectURL(blob);
    console.log("QR Code generated:", imageUrl);
  })
  .catch((error) => console.error("Error:", error));
Never expose API keys in client-side code! Use a backend proxy to make authenticated requests.

Complete Examples

Display QR Code in an Image Element

async function displayQRCode(data) {
  try {
    const response = await fetch(
      `https://qrgen.maybesurya.live/api/qrgen?data=${encodeURIComponent(data)}`
    );

    if (!response.ok) {
      throw new Error(`Failed to generate QR code: ${response.status}`);
    }

    const blob = await response.blob();
    const imageUrl = URL.createObjectURL(blob);

    // Display in existing img element
    const imgElement = document.getElementById("qr-code");
    imgElement.src = imageUrl;
    imgElement.alt = `QR Code for ${data}`;
  } catch (error) {
    console.error("Error generating QR code:", error);
    alert("Failed to generate QR code. Please try again.");
  }
}

// Usage
displayQRCode("https://maybesurya.dev");

Download QR Code

async function downloadQRCode(data, filename = "qrcode.png") {
  try {
    const response = await fetch(
      `https://qrgen.maybesurya.live/api/qrgen?data=${encodeURIComponent(data)}`
    );

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

    const blob = await response.blob();
    const url = URL.createObjectURL(blob);

    // Create download link
    const a = document.createElement("a");
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);

    // Cleanup
    URL.revokeObjectURL(url);

    console.log("QR code downloaded successfully!");
  } catch (error) {
    console.error("Error downloading QR code:", error);
  }
}

// Usage
downloadQRCode("https://maybesurya.dev", "maybesurya-qr.png");

Form Integration

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>QR Code Generator</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        max-width: 600px;
        margin: 50px auto;
        padding: 20px;
      }
      input,
      button {
        padding: 10px;
        font-size: 16px;
      }
      input {
        width: 70%;
      }
      button {
        width: 25%;
        background: #6366f1;
        color: white;
        border: none;
        cursor: pointer;
      }
      button:hover {
        background: #4f46e5;
      }
      #qr-result {
        margin-top: 20px;
        text-align: center;
      }
      #qr-result img {
        max-width: 300px;
        border: 1px solid #ddd;
        padding: 10px;
      }
    </style>
  </head>
  <body>
    <h1>QR Code Generator</h1>

    <div>
      <input type="text" id="qr-input" placeholder="Enter URL or text" />
      <button onclick="generateQR()">Generate</button>
    </div>

    <div id="qr-result"></div>

    <script>
      async function generateQR() {
        const input = document.getElementById("qr-input");
        const result = document.getElementById("qr-result");
        const data = input.value.trim();

        if (!data) {
          alert("Please enter some text or a URL");
          return;
        }

        result.innerHTML = "<p>Generating...</p>";

        try {
          const response = await fetch(
            `https://qrgen.maybesurya.live/api/qrgen?data=${encodeURIComponent(
              data
            )}`
          );

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

          const blob = await response.blob();
          const imageUrl = URL.createObjectURL(blob);

          result.innerHTML = `
          <img src="${imageUrl}" alt="QR Code">
          <p>QR Code generated successfully!</p>
          <button onclick="downloadCurrentQR('${imageUrl}')">Download</button>
        `;
        } catch (error) {
          console.error("Error:", error);
          result.innerHTML = `<p style="color: red;">Error: ${error.message}</p>`;
        }
      }

      function downloadCurrentQR(imageUrl) {
        const a = document.createElement("a");
        a.href = imageUrl;
        a.download = "qrcode.png";
        a.click();
      }
    </script>
  </body>
</html>

React Component

import React, { useState } from "react";

function QRCodeGenerator() {
  const [inputValue, setInputValue] = useState("");
  const [qrImageUrl, setQrImageUrl] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const generateQRCode = async () => {
    if (!inputValue.trim()) {
      setError("Please enter some text or a URL");
      return;
    }

    setLoading(true);
    setError(null);

    try {
      const response = await fetch(
        `https://qrgen.maybesurya.live/api/qrgen?data=${encodeURIComponent(
          inputValue
        )}`
      );

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

      const blob = await response.blob();
      const imageUrl = URL.createObjectURL(blob);
      setQrImageUrl(imageUrl);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const downloadQRCode = () => {
    if (!qrImageUrl) return;

    const a = document.createElement("a");
    a.href = qrImageUrl;
    a.download = "qrcode.png";
    a.click();
  };

  return (
    <div style={{ maxWidth: "600px", margin: "50px auto", padding: "20px" }}>
      <h1>QR Code Generator</h1>

      <div>
        <input
          type="text"
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          placeholder="Enter URL or text"
          style={{ padding: "10px", width: "70%", fontSize: "16px" }}
        />
        <button
          onClick={generateQRCode}
          disabled={loading}
          style={{
            padding: "10px",
            width: "25%",
            fontSize: "16px",
            background: "#6366F1",
            color: "white",
            border: "none",
            cursor: "pointer",
          }}
        >
          {loading ? "Loading..." : "Generate"}
        </button>
      </div>

      {error && (
        <p style={{ color: "red", marginTop: "20px" }}>Error: {error}</p>
      )}

      {qrImageUrl && (
        <div style={{ marginTop: "20px", textAlign: "center" }}>
          <img
            src={qrImageUrl}
            alt="QR Code"
            style={{
              maxWidth: "300px",
              border: "1px solid #ddd",
              padding: "10px",
            }}
          />
          <div style={{ marginTop: "10px" }}>
            <button onClick={downloadQRCode}>Download QR Code</button>
          </div>
        </div>
      )}
    </div>
  );
}

export default QRCodeGenerator;

Error Handling

async function generateQRCodeWithErrorHandling(data) {
  try {
    const response = await fetch(
      `https://qrgen.maybesurya.live/api/qrgen?data=${encodeURIComponent(
        data
      )}`,
      {
        headers: {
          "x-api-key": "YOUR_API_KEY", // If using authentication
        },
      }
    );

    // Handle specific HTTP status codes
    if (response.status === 429) {
      throw new Error("Rate limit exceeded. Please wait a moment.");
    }

    if (response.status === 401) {
      throw new Error("Invalid API key.");
    }

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

    const blob = await response.blob();
    return URL.createObjectURL(blob);
  } catch (error) {
    if (error.name === "TypeError") {
      console.error("Network error:", error);
      throw new Error("Network error. Please check your connection.");
    }
    throw error;
  }
}

Best Practices

✅ Do: - Always use encodeURIComponent() for data - Handle errors gracefully - Show loading states - Clean up blob URLs with URL.revokeObjectURL() - Use async/await for cleaner code
❌ Don’t: - Expose API keys in client-side code - Forget error handling
  • Make requests on every keystroke - Ignore network errors - Leave blob URLs unreleased

Next Steps