Hi. I'm endeavouring to implement a cookie/session based authentication system, and have run into trouble implementing cookies.
The session stuff and caching works, it's just getting the session cookie to the client I'm having trouble with.
Here is my relevant code:
app/(auth)/signup/actions.ts
"use server";
...
export default async function signup(_: any,
...
const user = await createUser(username, email, password);
const sessionToken = await generateSessionToken();
const session = await createSession(sessionToken, user.id);
const response = await fetch("http://localhost:3000/api/set-session-cookie", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ token: sessionToken, expiresAt: session.expiresAt }),
});
if (!response.ok) {
throw new Error("Failed to set session cookie");
}
return {
message: "Signup successful",
};
}
lib/auth/session.ts
"use server";
...
export async function setSessionTokenCookie(token: string, expiresAt: Date) {
const cookieStore = await cookies();
console.log("Setting cookie with token:", token);
console.log("Cookie expires at:", expiresAt);
cookieStore.set("session", token, {
httpOnly: true,
path: "/",
secure: process.env.NODE_ENV === "production",
sameSite: "strict",
expires: expiresAt,
});
return new NextResponse(
JSON.stringify({ message: "Session cookie set successfully!" }),
{
status: 200,
}
);
}
...```