The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
add withSessionEdge
Kiran Kea191ad63534
diff --git a/apps/web/app/api/track/conversions/route.ts b/apps/web/app/api/track/conversions/route.tsindex 6ae8879c4d..21f9e0f76d 100644--- a/apps/web/app/api/track/conversions/route.ts+++ b/apps/web/app/api/track/conversions/route.ts@@ -1,5 +1,5 @@import { parseRequestBody } from "@/lib/api/utils";-import { withWorkspace } from "@/lib/auth";+import { withSessionEdge } from "@/lib/auth";import { getClickEvent, recordConversion } from "@/lib/tinybird";import { conversionRequestSchema } from "@/lib/zod/schemas/conversions";import { NextResponse } from "next/server";@@ -11,10 +11,11 @@ import { NextResponse } from "next/server";// Replace withWorkspace// POST /api/track/conversions – post conversion event-export const POST = withWorkspace(async ({ req }) => {+export const POST = withSessionEdge(async ({ req }) => {const body = await parseRequestBody(req);- const { clickId, eventName, eventType, metadata, customerId } =- conversionRequestSchema.parse(body);+ const parsed = conversionRequestSchema.parse(body);++ const { clickId, eventName, eventType, metadata, customerId } = parsed;const clickEvent = await getClickEvent(clickId);diff --git a/apps/web/lib/auth/edge.ts b/apps/web/lib/auth/edge.tsnew file mode 100644index 0000000000..8b7848b68e--- /dev/null+++ b/apps/web/lib/auth/edge.ts@@ -0,0 +1,106 @@+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";+import prisma from "@/lib/prisma";+import { getSearchParams } from "@dub/utils";+import { ratelimit } from "../upstash";+import { WithSessionHandler } from "./session";+import { hashToken } from "./utils";++export const withSessionEdge =+ (handler: WithSessionHandler) =>+ async (req: Request, { params }: { params: Record<string, string> }) => {+ let headers = {};+ const authorizationHeader = req.headers.get("Authorization");++ try {+ if (!authorizationHeader) {+ throw new DubApiError({+ code: "bad_request",+ message:+ "Missing authorization header. Did you forget to add 'Bearer '? Learn more: https://d.to/auth",+ });+ }++ if (authorizationHeader) {+ if (!authorizationHeader.includes("Bearer ")) {+ throw new DubApiError({+ code: "bad_request",+ message:+ "Misconfigured authorization header. Did you forget to add 'Bearer '? Learn more: https://d.to/auth",+ });+ }+ }++ const apiKey = authorizationHeader.replace("Bearer ", "");+ const hashedKey = hashToken(apiKey, {+ noSecret: true,+ });++ // Find user by token+ const user = await prisma.user.findFirst({+ where: {+ tokens: {+ some: {+ hashedKey,+ },+ },+ },+ select: {+ id: true,+ name: true,+ email: true,+ },+ });++ if (!user) {+ throw new DubApiError({+ code: "unauthorized",+ message: "Unauthorized: Invalid API key.",+ });+ }++ // Check rate limit+ const { success, limit, reset, remaining } = await ratelimit(+ 600,+ "1 m",+ ).limit(apiKey);++ headers = {+ "Retry-After": reset.toString(),+ "X-RateLimit-Limit": limit.toString(),+ "X-RateLimit-Remaining": remaining.toString(),+ "X-RateLimit-Reset": reset.toString(),+ };++ if (!success) {+ throw new DubApiError({+ code: "rate_limit_exceeded",+ message: "Too many requests.",+ });+ }++ // Update token last used+ await prisma.token.update({+ where: {+ hashedKey,+ },+ data: {+ lastUsed: new Date(),+ },+ });++ const session = {+ user: {+ id: user.id,+ name: user.name || "",+ email: user.email || "",+ },+ };++ // Fetch search params+ const searchParams = getSearchParams(req.url);++ return await handler({ req, params, searchParams, session });+ } catch (error) {+ return handleAndReturnErrorResponse(error, headers);+ }+ };diff --git a/apps/web/lib/auth/index.ts b/apps/web/lib/auth/index.tsindex 56caca89ac..456bc9a167 100644--- a/apps/web/lib/auth/index.ts+++ b/apps/web/lib/auth/index.ts@@ -3,3 +3,4 @@ export * from "./options";export * from "./session";export * from "./utils";export * from "./workspace";+export * from "./edge";diff --git a/apps/web/lib/auth/session.ts b/apps/web/lib/auth/session.tsindex b6d8c16b78..3e0bc079a1 100644--- a/apps/web/lib/auth/session.ts+++ b/apps/web/lib/auth/session.ts@@ -4,7 +4,7 @@ import { getSearchParams } from "@dub/utils";import { ratelimit } from "../upstash";import { Session, getSession, hashToken } from "./utils";-interface WithSessionHandler {+export interface WithSessionHandler {({req,params,