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

35 lines
893 B
TypeScript

import "server-only";
import { redirect } from "next/navigation";
import { cacheLife } from "next/cache";
import { getSession } from "./session";
import { findUserById } from "./data";
export type User = {
id: string;
name: string;
};
// Reads the session cookie, so it must run on every request and cannot live in
// a plain `use cache` scope. `use cache: private` lets it read the cookie while
// keeping the result out of the shared, server-stored cache. Cached scopes are
// prefetchable by default; a `stale` of at least 30 seconds keeps it that way.
export async function getCurrentUser(): Promise<User> {
"use cache: private";
cacheLife({ stale: 60 });
const { userId } = await getSession();
if (!userId) {
redirect("/login");
}
const user = await findUserById(userId);
if (!user) {
redirect("/login");
}
return { id: user.id, name: user.name };
}