The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
import { DubApiError, ErrorCodes } from "@/lib/api/errors";
import { createLink, getLinksForWorkspace, processLink } from "@/lib/api/links";
import { throwIfLinksUsageExceeded } from "@/lib/api/links/usage-checks";
import { validateLinksQueryFilters } from "@/lib/api/links/validate-links-query-filters";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import {
MEGA_WORKSPACE_LINKS_LIMIT,
SORTABLE_LINKS_LIMIT,
} from "@/lib/constants/misc";
import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";
import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
import {
createLinkBodySchemaAsync,
getLinksQuerySchemaExtended,
linkEventSchema,
} from "@/lib/zod/schemas/links";
import { LOCALHOST_IP } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
// GET /api/links – get all links for a workspace
export const GET = withWorkspace(
async ({ headers, searchParams, workspace, session }) => {
const filters = getLinksQuerySchemaExtended.parse(searchParams);
const { folderIds } = await validateLinksQueryFilters({
...filters,
workspace,
sessionUserId: session.user.id,
});
const response = await getLinksForWorkspace({
...filters,
workspaceId: workspace.id,
folderIds,
sortBy:
workspace.totalLinks > SORTABLE_LINKS_LIMIT
? "createdAt"
: filters.sortBy,
searchMode:
workspace.totalLinks > MEGA_WORKSPACE_LINKS_LIMIT ? "exact" : "fuzzy",
});
return NextResponse.json(response, {
headers,
});
},
{
requiredPermissions: ["links.read"],
},
);
// POST /api/links – create a new link
export const POST = withWorkspace(
async ({ req, headers, session, workspace }) => {
if (workspace) {
throwIfLinksUsageExceeded(workspace);
}
const body = await createLinkBodySchemaAsync.parseAsync(
await parseRequestBody(req),
);
if (!session) {
const ip = req.headers.get("x-forwarded-for") || LOCALHOST_IP;
await assertRateLimit({
policy: RATELIMIT_POLICIES.anonymousLinkCreate,
identifier: ip,
});
}
const { link, error, code } = await processLink({
payload: body,
workspace,
...(session && { userId: session.user.id }),
});
if (error != null) {
throw new DubApiError({
code: code as ErrorCodes,
message: error,
});
}
try {
const response = await createLink(link);
if (response.projectId && response.userId) {
waitUntil(
sendWorkspaceWebhook({
trigger: "link.created",
workspace,
data: linkEventSchema.parse(response),
}),
);
}
return NextResponse.json(response, {
headers,
});
} catch (error) {
throw new DubApiError({
code: "unprocessable_entity",
message: error.message,
});
}
},
{
requiredPermissions: ["links.write"],
},
);