Next.jsMedium

How do you access the session in Server Components?

Call your auth library's server function directly in the Server Component, for example await auth() (Auth.js v5), auth.api.getSession({ headers: await headers() }) (Better Auth), await currentUser() (Clerk), or your own verifySession() that reads and verifies the cookie. No hook or provider is needed.

Pattern

  1. A server-only helper reads the session cookie with cookies().
  2. It verifies the token or looks up the session, wrapped in React.cache so multiple components share one check per request.
  3. Server Components call it and branch: render, redirect("/login"), notFound() or (experimental) unauthorized().

With Cache Components

  • Reading cookies is request-time work. Place components that read the session inside <Suspense> so the rest of the page stays in the static shell.
  • You cannot read cookies inside "use cache". Read the session outside and pass the user ID as an argument to cached functions, so each user gets their own cache entry.
  • Do not put await auth() at the top of the root layout; it makes the entire app request-time. Read it in the components that need it.

Passing to the client

Pass the minimal fields (name, avatar, role) as props or into a context provider. Never pass the raw token.

Security

Checking the session in a layout is not enough, since layouts do not re-render on every navigation. Check in the page or, better, in the data functions it calls.

Code example

tsx
1// lib/dal.ts
2import "server-only";
3import { cache } from "react";
4import { cookies } from "next/headers";
5import { redirect } from "next/navigation";
6import { decrypt } from "@/lib/session-token";
7
8export const verifySession = cache(async () => {
9 const session = await decrypt((await cookies()).get("session")?.value);
10 if (!session?.userId) redirect("/login");
11 return { userId: session.userId as string, role: session.role as string };
12});
13
14// app/dashboard/page.tsx
15import { Suspense } from "react";
16
17async function Welcome() {
18 const { userId } = await verifySession(); // request-time: inside Suspense
19 const user = await getUserProfile(userId); // can be "use cache" keyed by userId
20 return <h1>Welcome back, {user.name}</h1>;
21}
22
23export default function Dashboard() {
24 return (
25 <Suspense fallback={<h1>Welcome back</h1>}>
26 <Welcome />
27 </Suspense>
28 );
29}
30
31declare function getUserProfile(id: string): Promise<{ name: string }>;

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app