CodingNic

Authentication & Sessions

Create Secure Sessions

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:

text
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.

ts
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:

ts
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:

ts
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:

  1. inspect the browser cookie
  2. confirm it is HTTP-only
  3. confirm the database contains a session record
  4. 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.