The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Custom `keyLength` prop
Steven Teyf85b5d901f99
diff --git a/apps/web/app/api/links/random/route.ts b/apps/web/app/api/links/random/route.tsindex 2cfd84d2cd..a38098458f 100644--- a/apps/web/app/api/links/random/route.ts+++ b/apps/web/app/api/links/random/route.ts@@ -17,10 +17,7 @@ export const GET = async (req: NextRequest) => {await ratelimitOrThrow(req, "links-random");- const response = await getRandomKey({- domain,- long: domain === "loooooooo.ng",- });+ const response = await getRandomKey({ domain });return NextResponse.json(response);} catch (error) {return handleAndReturnErrorResponse(error);diff --git a/apps/web/lib/api/links/process-link.ts b/apps/web/lib/api/links/process-link.tsindex aa6d4e360b..e032210f3b 100644--- a/apps/web/lib/api/links/process-link.ts+++ b/apps/web/lib/api/links/process-link.ts@@ -55,6 +55,7 @@ export async function processLink<T extends Record<string, any>>({let {domain,key,+ keyLength,url,image,proxy,@@ -252,10 +253,11 @@ export async function processLink<T extends Record<string, any>>({}if (!key) {+ console.log("keyLength", keyLength, domain);key = await getRandomKey({domain,prefix: payload["prefix"],- long: domain === "loooooooo.ng",+ length: keyLength || (domain === "loooooooo.ng" ? 69 : 7),});} else if (!skipKeyChecks) {const processedKey = processKey({ domain, key });@@ -534,6 +536,7 @@ export async function processLink<T extends Record<string, any>>({// remove polyfill attributes from payloaddelete payload["shortLink"];delete payload["qrCode"];+ delete payload["keyLength"];delete payload["prefix"];UTMTags.forEach((tag) => {delete payload[tag];diff --git a/apps/web/lib/planetscale/get-random-key.ts b/apps/web/lib/planetscale/get-random-key.tsindex 04dd769b26..125c349afc 100644--- a/apps/web/lib/planetscale/get-random-key.ts+++ b/apps/web/lib/planetscale/get-random-key.ts@@ -3,15 +3,15 @@ import { checkIfKeyExists } from "./check-if-key-exists";export async function getRandomKey({domain,+ length = 7,prefix,- long,}: {domain: string;+ length?: number;prefix?: string;- long?: boolean;}): Promise<string> {/* recursively get random key till it gets one that's available */- let key = long ? nanoid(69) : nanoid();+ let key = nanoid(length);if (prefix) {key = `${prefix.replace(/^\/|\/$/g, "")}/${key}`;}@@ -20,7 +20,7 @@ export async function getRandomKey({if (exists) {// by the off chance that key already exists- return getRandomKey({ domain, prefix, long });+ return getRandomKey({ domain, length, prefix });} else {return key;}diff --git a/apps/web/lib/zod/schemas/links.ts b/apps/web/lib/zod/schemas/links.tsindex 27448a104e..82cc7620ee 100644--- a/apps/web/lib/zod/schemas/links.ts+++ b/apps/web/lib/zod/schemas/links.ts@@ -246,6 +246,12 @@ export const createLinkBodySchema = z.object({.describe("The short link slug. If not provided, a random 7-character slug will be generated.",),+ keyLength: z+ .number()+ .optional()+ .describe(+ "The length of the short link slug. Defaults to 7 if not provided. When used with `prefix`, the total length of the key will be `prefix.length + keyLength`.",+ ),externalId: z.string().min(1)diff --git a/apps/web/tests/links/create-link.test.ts b/apps/web/tests/links/create-link.test.tsindex fcfcf7253a..83ea54ba04 100644--- a/apps/web/tests/links/create-link.test.ts+++ b/apps/web/tests/links/create-link.test.ts@@ -144,6 +144,72 @@ describe.sequential("POST /links", async () => {expect(LinkSchema.strict().parse(link)).toBeTruthy();});+ test("custom keyLength", async () => {+ const keyLength = 12;++ onTestFinished(async () => {+ await h.deleteLink(link.id);+ });++ const { status, data: link } = await http.post<Link>({+ path: "/links",+ body: {+ url,+ domain,+ keyLength,+ },+ });++ expect(status).toEqual(200);+ // The key should be exactly keyLength characters long+ expect(link.key).toHaveLength(keyLength);+ expect(link).toStrictEqual({+ ...expectedLink,+ url,+ userId: user.id,+ projectId,+ workspaceId,+ shortLink: `https://${domain}/${link.key}`,+ qrCode: `https://api.dub.co/qr?url=https://${domain}/${link.key}?qr=1`,+ });+ expect(LinkSchema.strict().parse(link)).toBeTruthy();+ });++ test("custom keyLength with prefix", async () => {+ const keyLength = 10;+ const prefix = "test";++ onTestFinished(async () => {+ await h.deleteLink(link.id);+ });++ const { status, data: link } = await http.post<Link>({+ path: "/links",+ body: {+ url,+ domain,+ keyLength,+ prefix,+ },+ });++ expect(status).toEqual(200);+ // The key should start with the prefix and have the specified length+ expect(link.key.startsWith(prefix)).toBeTruthy();+ // The total length should be prefix.length + "/" + keyLength+ expect(link.key).toHaveLength(prefix.length + 1 + keyLength);+ expect(link).toStrictEqual({+ ...expectedLink,+ url,+ userId: user.id,+ projectId,+ workspaceId,+ shortLink: `https://${domain}/${link.key}`,+ qrCode: `https://api.dub.co/qr?url=https://${domain}/${link.key}?qr=1`,+ });+ expect(LinkSchema.strict().parse(link)).toBeTruthy();+ });+test("utm builder", async () => {const longUrl = new URL(url);const utm = {