From 10a0ac4a35784155ad4f79db4209abf48a57610c Mon Sep 17 00:00:00 2001 From: Jonas Schell Date: Tue, 14 Jan 2025 14:36:03 +0100 Subject: [PATCH] feat(api): add cookie handling for random participant postfix in connection details (#385) --- app/api/connection-details/route.ts | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/app/api/connection-details/route.ts b/app/api/connection-details/route.ts index 48d73e1c..ff3f9634 100644 --- a/app/api/connection-details/route.ts +++ b/app/api/connection-details/route.ts @@ -6,6 +6,7 @@ import { NextRequest, NextResponse } from 'next/server'; const API_KEY = process.env.LIVEKIT_API_KEY; const API_SECRET = process.env.LIVEKIT_API_SECRET; const LIVEKIT_URL = process.env.LIVEKIT_URL; +const COOKIE_KEY = 'random-participant-postfix'; export async function GET(request: NextRequest) { try { @@ -15,6 +16,7 @@ export async function GET(request: NextRequest) { const metadata = request.nextUrl.searchParams.get('metadata') ?? ''; const region = request.nextUrl.searchParams.get('region'); const livekitServerUrl = region ? getLiveKitURL(region) : LIVEKIT_URL; + let randomParticipantPostfix = request.cookies.get(COOKIE_KEY)?.value; if (livekitServerUrl === undefined) { throw new Error('Invalid region'); } @@ -27,9 +29,12 @@ export async function GET(request: NextRequest) { } // Generate participant token + if (!randomParticipantPostfix) { + randomParticipantPostfix = randomString(4); + } const participantToken = await createParticipantToken( { - identity: `${participantName}__${randomString(4)}`, + identity: `${participantName}__${randomParticipantPostfix}`, name: participantName, metadata, }, @@ -43,7 +48,12 @@ export async function GET(request: NextRequest) { participantToken: participantToken, participantName: participantName, }; - return NextResponse.json(data); + return new NextResponse(JSON.stringify(data), { + headers: { + 'Content-Type': 'application/json', + 'Set-Cookie': `${COOKIE_KEY}=${randomParticipantPostfix}; Path=/; HttpOnly; SameSite=Strict; Secure; Expires=${getCookieExpirationTime()}`, + }, + }); } catch (error) { if (error instanceof Error) { return new NextResponse(error.message, { status: 500 }); @@ -79,3 +89,11 @@ function getLiveKitURL(region: string | null): string { } return url; } + +function getCookieExpirationTime(): string { + var now = new Date(); + var time = now.getTime(); + var expireTime = time + 60 * 120 * 1000; + now.setTime(expireTime); + return now.toUTCString(); +}