Generate a QR as a data URL
Builds the QR value based on the type (text, URL, email, or phone) and returns a base64 PNG.
typescript
import QRCode from "qrcode";
type QrContentType = "text" | "url" | "email" | "phone";
function buildQrValue(contentType: QrContentType, input: string): string {
const trimmed = input.trim();
if (contentType === "email") return `mailto:${trimmed}`;
if (contentType === "phone") return `tel:${trimmed.replace(/\s+/g, "")}`;
return trimmed;
}
export async function generateQrDataUrl(
contentType: QrContentType,
input: string,
size = 512,
): Promise<string> {
const value = buildQrValue(contentType, input);
return QRCode.toDataURL(value, {
errorCorrectionLevel: "M",
margin: 2,
width: size,
color: { dark: "#13202b", light: "#f3f7fa" },
});
}Dependencias
qrcodeNotas de uso
- Install the dependency: npm i qrcode (and npm i -D @types/qrcode if you use TypeScript).
- The data URL can go directly into an <img> src or be converted to a Blob to download.
Limitaciones
- Very long content produces dense QRs that are hard to scan.
- Aimed at browser use; for Node adjust the output options.