Files
Joseph 8ff8f1b82e docs: add authentication with Cache Components guide and iron-session example (#95802)
- new guide, Auth w/ Cache Components
- iron-session example w/ Cache Components

TODO:

- [x] opt-out from the instant requirements
- [x] e2e for the example, using instant helper

---------

Co-authored-by: Aurora Scharff <66901228+aurorascharff@users.noreply.github.com>
Co-authored-by: Aurora Scharff <aurora.sofie@gmail.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-07 09:49:57 +00:00

44 lines
1.1 KiB
TypeScript

import "server-only";
import { cookies } from "next/headers";
import { sealData, unsealData } from "iron-session";
export type SessionData = {
userId?: string;
};
const COOKIE_NAME = "app_session";
const password = process.env.SESSION_PASSWORD!;
const cookieOptions = {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax" as const,
path: "/",
};
export async function getSession(): Promise<SessionData> {
const cookie = (await cookies()).get(COOKIE_NAME)?.value;
if (!cookie) {
return {};
}
try {
return await unsealData<SessionData>(cookie, { password });
} catch {
// An expired, tampered, or otherwise unsealable cookie (for example after
// SESSION_PASSWORD is rotated) is treated the same as no session, so
// callers redirect to /login instead of hitting the error boundary.
return {};
}
}
export async function saveSession(data: SessionData) {
const sealed = await sealData(data, { password });
(await cookies()).set(COOKIE_NAME, sealed, cookieOptions);
}
export async function destroySession() {
(await cookies()).delete(COOKIE_NAME);
}