i try to build nextjs on Google’s Project IDX, but it seems there is some problem with cookies management. i set my session cookies on login page, then i want to take it values on other page. it is set when i do login, but when i move to other page, there is no cookies anymore.
is it IDX problem or am i did it wrong ?
i set my cookies same as this video: [https://www.youtube.com/watch?v=DJvM2lSPn6w]
import { cookies } from "next/headers";
import { NextRequest, NextResponse } from "next/server";
const secretKey = process.env.SECRET_KEY;
const key = new TextEncoder().encode(secretKey);
export async function encrypt(payload: any) {
return await new SignJWT(payload)
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt()
.setExpirationTime("10 sec from now")
.sign(key);
}
export async function decrypt(input: string): Promise<any> {
const { payload } = await jwtVerify(input, key, {
algorithms: ["HS256"],
});
return payload;
}
export async function login(formData: FormData) {
// Verify credentials && get the user
const user = { username: formData.get("username"), password: formData.get("password") };
// Create the session
const expires = new Date(Date.now() + 10 * 1000);
const session = await encrypt({ user, expires });
// Save the session in a cookie
cookies().set("session", session, { expires, httpOnly: true });
console.log("login success")
console.log(session)
}
export async function logout() {
// Destroy the session
cookies().set("session", "", { expires: new Date(0) });
}
export async function getSession() {
const session = cookies().get("session")?.value;
if (!session) return null;
return await decrypt(session);
}
export async function updateSession(request: NextRequest) {
const session = request.cookies.get("session")?.value;
if (!session) return;
// Refresh the session so it doesn't expire
const parsed = await decrypt(session);
parsed.expires = new Date(Date.now() + 10 * 1000);
const res = NextResponse.next();
res.cookies.set({
name: "session",
value: await encrypt(parsed),
httpOnly: true,
expires: parsed.expires,
});
return res;
}