feat(api): add cookie handling for random participant postfix in connection details (#385)

This commit is contained in:
Jonas Schell 2025-01-14 14:36:03 +01:00 committed by GitHub
parent 686b749282
commit 10a0ac4a35
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -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();
}