File size: 807 Bytes
101ebaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import crypto from "crypto";
import type { NextRequest } from "next/server";

export const USER_COOKIE_NAME = "teich_uid";

const USER_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 365;

export function getOrCreateUserId(request: NextRequest): {
    userId: string;
    shouldSetCookie: boolean;
} {
    const existing = request.cookies.get(USER_COOKIE_NAME)?.value;
    if (existing) {
        return { userId: existing, shouldSetCookie: false };
    }

    const userId = crypto.randomUUID();
    return { userId, shouldSetCookie: true };
}

export function userCookieOptions() {
    return {
        name: USER_COOKIE_NAME,
        httpOnly: true,
        sameSite: "lax" as const,
        secure: process.env.NODE_ENV === "production",
        path: "/",
        maxAge: USER_COOKIE_MAX_AGE_SECONDS,
    };
}