Session Management & useSession Hook
Access session data in server and client components and protect pages based on auth status.
Session Management & useSession Hook is a free React Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the React Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Session Types in Auth.js
Auth.js supports two session strategies: JWT (default, stateless token in cookie) and database (session record in DB, invalidatable server-side).
useSession in Client Components
useSession() is a Client Component hook that reads the current session. It returns data (session), status ('loading' | 'authenticated' | 'unauthenticated'), and an update function.
'use client';
import { useSession } from 'next-auth/react';
export function UserAvatar() {
const { data: session, status } = useSession();
if (status === 'loading') return <Spinner />;
if (status === 'unauthenticated') return <Link href="/login">Sign in</Link>;
return <img src={session.user?.image ?? ''} alt={session.user?.name ?? ''} />;
}SessionProvider Setup
Wrap your app (or a Client Component subtree) in SessionProvider so useSession can access the session context.
// app/providers.tsx
'use client';
import { SessionProvider } from 'next-auth/react';
export function Providers({ children }: { children: React.ReactNode }) {
return <SessionProvider>{children}</SessionProvider>;
}
// app/layout.tsx
import { Providers } from './providers';
export default function RootLayout({ children }) {
return <html><body><Providers>{children}</Providers></body></html>;
}auth() in Server Components
For Server Components, use auth() directly — no hook, no provider needed. It reads the session from the server-side cookie.
import { auth } from '@/auth';
export default async function Header() {
const session = await auth();
return (
<nav>
{session ? (
<span>Hello, {session.user?.name}</span>
) : (
<Link href="/login">Sign in</Link>
)}
</nav>
);
}Protecting Client Routes
Use useSession with required: true option to auto-redirect unauthenticated users to the sign-in page.
'use client';
import { useSession } from 'next-auth/react';
export default function ProtectedPage() {
const { data: session } = useSession({ required: true });
// session is never null here — unauthenticated users are redirected
return <div>Welcome, {session?.user?.name}</div>;
}Updating the Session
Call the update() function returned by useSession to refresh the session (e.g., after a profile update) without signing out and back in.
const { data: session, update } = useSession();
async function handleNameChange(newName: string) {
await updateUserName(newName); // API call
await update({ user: { name: newName } }); // refresh session
}JWT Session Callbacks
Use the jwt callback to add custom data to the JWT token on sign-in, and the session callback to expose it in the session object.
callbacks: {
async jwt({ token, user }) {
if (user) token.role = user.role; // add on first sign-in
return token;
},
async session({ session, token }) {
session.user.role = token.role as string;
return session;
},
},Session Expiry
Configure session max age in the Auth.js config. JWT sessions auto-refresh with each request when active.
export const { handlers, auth } = NextAuth({
session: {
strategy: 'jwt',
maxAge: 30 * 24 * 60 * 60, // 30 days
updateAge: 24 * 60 * 60, // refresh if older than 1 day
},
});Invalidating Database Sessions
Database sessions can be revoked server-side (useful for force logout). Delete the session record from the database to immediately invalidate it.
// Server Action to log out all devices:
async function logOutAllDevices() {
'use server';
const session = await auth();
if (session) await db.session.deleteMany({ where: { userId: session.user.id } });
redirect('/login');
}Role-Based Access in Client Components
Read the session role from useSession and conditionally render UI based on it.
const { data: session } = useSession();
const isAdmin = session?.user?.role === 'admin';
return (
<>
{isAdmin && <AdminPanel />}
<UserContent />
</>
);Quick Check
Which provider must wrap your app for useSession() to work in Client Components?
Recap
Use auth() for session access in Server Components and useSession() in Client Components wrapped by SessionProvider. Add custom data via JWT/session callbacks, update sessions client-side with update(), and configure maxAge for session expiry.
Frequently asked questions
Is the “Session Management & useSession Hook” lesson free?
Yes — the full text of “Session Management & useSession Hook” is free to read here on the web, and the React Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the React Academy course, upgrade to CoddyKit PRO.
What will I learn in “Session Management & useSession Hook”?
Access session data in server and client components and protect pages based on auth status. You practise React Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start React Academy?
No prior experience is required. React Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Session Management & useSession Hook” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this React Academy lesson?
Yes. Every React Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Setting Up Auth.js in Next.js App Router
- Session Management & useSession Hook
- Credentials Provider & Custom Login
- Middleware-Based Route Protection