Authentication & Sessions
18 min read
Create Secure Sessions
Create Secure Sessions
Task
Create server-managed sessions using the existing Session model and an HTTP-only cookie.
File
Create:
lib/session.ts
Session Shape
Generate an unpredictable token, store only a hash of it in the database, and place the raw token in an HTTP-only cookie.
import crypto from "node:crypto";
export function createSessionToken() {
return crypto.randomBytes(32).toString("base64url");
}
export function hashSessionToken(token: string) {
return crypto.createHash("sha256").update(token).digest("hex");
}
When creating a session:
const token = createSessionToken();
const tokenHash = hashSessionToken(token);
await prisma.session.create({
data: {
userId: user.id,
tokenHash,
expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24 * 30),
},
});
Set the cookie with:
response.cookies.set("readly_session", token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
maxAge: 60 * 60 * 24 * 30,
});
Keep SESSION_SECRET available in the environment configuration for the application’s server-side session configuration.
Test
After registration or login:
- inspect the browser cookie
- confirm it is HTTP-only
- confirm the database contains a session record
- confirm the stored token is not the raw cookie value
Checkpoint
Readly can establish a persistent authenticated session without exposing the session token to browser JavaScript.