Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

qr api return svg format

Pedro Ladeira4facb8d8bcfa
diff --git a/apps/web/app/api/qr/route.tsx b/apps/web/app/api/qr/route.tsx
index 60d9d77138..77b47e5199 100644
--- a/apps/web/app/api/qr/route.tsx
+++ b/apps/web/app/api/qr/route.tsx
@@ -2,6 +2,7 @@ import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { ratelimitOrThrow } from "@/lib/api/utils";
import { getShortLinkViaEdge, getWorkspaceViaEdge } from "@/lib/planetscale";
import { getDomainViaEdge } from "@/lib/planetscale/get-domain-via-edge";
+import { getQRAsSVG } from "@/lib/qr/api";
import { QRCodeSVG } from "@/lib/qr/utils";
import { getQRCodeQuerySchema } from "@/lib/zod/schemas/qr";
import { DUB_QR_LOGO, getSearchParams, isDubDomain } from "@dub/utils";
@@ -21,37 +22,52 @@ export async function GET(req: NextRequest) {
await ratelimitOrThrow(req, "qr");
- const { logo, url, size, level, fgColor, bgColor, margin, hideLogo } =
- paramsParsed;
+ const {
+ logo,
+ url,
+ size,
+ level,
+ fgColor,
+ bgColor,
+ margin,
+ hideLogo,
+ format,
+ } = paramsParsed;
const qrCodeLogo = await getQRCodeLogo({ url, logo, hideLogo });
- return new ImageResponse(
- QRCodeSVG({
- value: url,
- size,
- level,
- fgColor,
- bgColor,
- margin,
- ...(qrCodeLogo
- ? {
- imageSettings: {
- src: qrCodeLogo,
- height: size / 4,
- width: size / 4,
- excavate: true,
- },
- }
- : {}),
- isOGContext: true,
- }),
- {
- width: size,
- height: size,
- headers: CORS_HEADERS,
- },
- );
+ const qrProps = {
+ value: url,
+ size,
+ level,
+ fgColor,
+ bgColor,
+ margin,
+ ...(qrCodeLogo
+ ? {
+ imageSettings: {
+ src: qrCodeLogo,
+ height: size / 4,
+ width: size / 4,
+ excavate: true,
+ },
+ }
+ : {}),
+ };
+
+ if (format === "svg") {
+ const svgString = await getQRAsSVG(qrProps);
+ const headers = new Headers(CORS_HEADERS);
+ headers.set("Content-Type", "image/svg+xml");
+ headers.set("Content-Disposition", "inline; filename=qr.svg");
+ return new Response(svgString, { headers });
+ }
+
+ return new ImageResponse(QRCodeSVG({ ...qrProps, isOGContext: true }), {
+ width: size,
+ height: size,
+ headers: CORS_HEADERS,
+ });
} catch (error) {
return handleAndReturnErrorResponse(error, CORS_HEADERS);
}
diff --git a/apps/web/lib/openapi/qr/index.ts b/apps/web/lib/openapi/qr/index.ts
index 30134c0991..65de0a016a 100644
--- a/apps/web/lib/openapi/qr/index.ts
+++ b/apps/web/lib/openapi/qr/index.ts
@@ -19,6 +19,9 @@ export const getQRCode: ZodOpenApiOperationObject = {
"image/png": {
schema: z.string(),
},
+ "image/svg+xml": {
+ schema: z.string(),
+ },
},
},
...openApiErrorResponses,
diff --git a/apps/web/lib/qr/api.tsx b/apps/web/lib/qr/api.tsx
index 0d3312f182..9e3c81cf18 100644
--- a/apps/web/lib/qr/api.tsx
+++ b/apps/web/lib/qr/api.tsx
@@ -1,6 +1,5 @@
import qrcodegen from "./codegen";
import {
- DEFAULT_BGCOLOR,
DEFAULT_FGCOLOR,
DEFAULT_LEVEL,
DEFAULT_MARGIN,
@@ -10,21 +9,24 @@ import {
import { QRPropsSVG } from "./types";
import { excavateModules, generatePath, getImageSettings } from "./utils";
-export async function getQRAsSVG(props: QRPropsSVG) {
+export async function getQRAsSVG(props: QRPropsSVG): Promise<string> {
const {
value,
size = DEFAULT_SIZE,
level = DEFAULT_LEVEL,
- bgColor = DEFAULT_BGCOLOR,
fgColor = DEFAULT_FGCOLOR,
margin = DEFAULT_MARGIN,
imageSettings,
- ...otherProps
} = props;
+ const shouldUseHigherErrorLevel =
+ imageSettings?.excavate && (level === "L" || level === "M");
+
+ const effectiveLevel = shouldUseHigherErrorLevel ? "Q" : level;
+
let cells = qrcodegen.QrCode.encodeText(
value,
- ERROR_LEVEL_MAP[level],
+ ERROR_LEVEL_MAP[effectiveLevel],
).getModules();
const numCells = cells.length + margin * 2;
@@ -35,51 +37,44 @@ export async function getQRAsSVG(props: QRPropsSVG) {
imageSettings,
);
- let image = <></>;
+ let image = "";
if (imageSettings != null && calculatedImageSettings != null) {
if (calculatedImageSettings.excavation != null) {
cells = excavateModules(cells, calculatedImageSettings.excavation);
}
- const base64Image = await fetch(
- `https://wsrv.nl/?url=${imageSettings.src}&w=100&h=100&encoding=base64`,
- ).then((res) => res.text());
+ try {
+ const base64Image = await fetch(
+ `https://wsrv.nl/?url=${encodeURIComponent(imageSettings.src)}&w=100&h=100&encoding=base64`,
+ ).then((res) => {
+ if (!res.ok) {
+ throw new Error(`Failed to fetch logo: ${res.status}`);
+ }
+ return res.text();
+ });
- image = (
- <image
- href={base64Image}
- height={calculatedImageSettings.h}
- width={calculatedImageSettings.w}
- x={calculatedImageSettings.x + margin}
- y={calculatedImageSettings.y + margin}
- preserveAspectRatio="none"
- />
- );
+ image = [
+ `<image href="${base64Image}"`,
+ `height="${calculatedImageSettings.h}"`,
+ `width="${calculatedImageSettings.w}"`,
+ `x="${calculatedImageSettings.x + margin}"`,
+ `y="${calculatedImageSettings.y + margin}"`,
+ 'preserveAspectRatio="none"></image>',
+ ].join(" ");
+ } catch {
+ // Omit logo if embedding fails; still return a valid QR SVG.
+ }
}
// Drawing strategy: instead of a rect per module, we're going to create a
- // single path for the dark modules and layer that on top of a light rect,
- // for a total of 2 DOM nodes. We pay a bit more in string concat but that's
- // way faster than DOM ops.
- // For level 1, 441 nodes -> 2
- // For level 40, 31329 -> 2
+ // single path for the dark modules. Background is omitted so SVGs are
+ // transparent (bgColor applies to PNG only).
const fgPath = generatePath(cells, margin);
- return (
- <svg
- height={size}
- width={size}
- viewBox={`0 0 ${numCells} ${numCells}`}
- xmlns="http://www.w3.org/2000/svg"
- {...otherProps}
- >
- <path
- fill={bgColor}
- d={`M0,0 h${numCells}v${numCells}H0z`}
- shapeRendering="crispEdges"
- />
- <path fill={fgColor} d={fgPath} shapeRendering="crispEdges" />
- {image}
- </svg>
- );
+ return [
+ `<svg xmlns="http://www.w3.org/2000/svg" height="${size}" width="${size}" viewBox="0 0 ${numCells} ${numCells}">`,
+ `<path fill="${fgColor}" d="${fgPath}" shape-rendering="crispEdges"></path>`,
+ image,
+ "</svg>",
+ ].join("");
}
diff --git a/apps/web/lib/qr/index.tsx b/apps/web/lib/qr/index.tsx
index 9b753ed749..e2c3af9680 100644
--- a/apps/web/lib/qr/index.tsx
+++ b/apps/web/lib/qr/index.tsx
@@ -386,9 +386,9 @@ export async function getQRAsSVGDataUri(props: QRProps) {
)
.join("");
+ // Omit the background fill so downloaded SVGs have a transparent background.
const svgData = [
`<svg xmlns="http://www.w3.org/2000/svg" height="${size}" width="${size}" viewBox="0 0 ${numCells} ${numCells}">`,
- `<path fill="${bgColor}" d="M0,0 h${numCells}v${numCells}H0z" shape-rendering="crispEdges"></path>`,
`<path fill="${fgColor}" d="${fgPath}" shape-rendering="crispEdges"></path>`,
finderSVG,
image,
diff --git a/apps/web/lib/zod/schemas/qr.ts b/apps/web/lib/zod/schemas/qr.ts
index 1e8180080d..04426845e5 100644
--- a/apps/web/lib/zod/schemas/qr.ts
+++ b/apps/web/lib/zod/schemas/qr.ts
@@ -42,7 +42,7 @@ export const getQRCodeQuerySchema = z.object({
.optional()
.default(DEFAULT_BGCOLOR)
.describe(
- "The background color of the QR code in hex format. Defaults to `#ffffff` if not provided.",
+ "The background color of the QR code in hex format. Defaults to `#ffffff` if not provided. Only applies to `png` format; `svg` responses have a transparent background.",
),
hideLogo: booleanQuerySchema
.optional()
@@ -64,4 +64,9 @@ export const getQRCodeQuerySchema = z.object({
"DEPRECATED: Margin is included by default. Use the `margin` prop to customize the margin size.",
)
.meta({ deprecated: true }),
+ format: z
+ .enum(["png", "svg"])
+ .optional()
+ .default("png")
+ .describe("The format of the QR code. Defaults to `png` if not provided."),
});