Skip to content

Commit

Permalink
feat(api): add cookie handling for random participant postfix in conn…
Browse files Browse the repository at this point in the history
…ection details (#385)
  • Loading branch information
Ocupe authored Jan 14, 2025
1 parent 686b749 commit 10a0ac4
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions app/api/connection-details/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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');
}
Expand All @@ -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,
},
Expand All @@ -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 });
Expand Down Expand Up @@ -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();
}

0 comments on commit 10a0ac4

Please sign in to comment.