Session management helps keep track of who a user is while they use your website. It lets the site remember the user between pages or visits.
0
0
Session management in NextJS
Introduction
When you want users to stay logged in as they move through your site.
When you need to save user preferences or shopping cart items temporarily.
When you want to protect pages so only logged-in users can see them.
When you want to track user activity during a visit without asking them to log in again.
Syntax
NextJS
import { getServerSession } from 'next-auth/next'; import { authOptions } from './api/auth/[...nextauth]'; export default async function handler(req, res) { const session = await getServerSession(req, res, authOptions); if (session) { res.status(200).json({ message: `Hello, ${session.user.name}` }); } else { res.status(401).json({ message: 'Not authenticated' }); } }
Use getServerSession to get the current user's session on the server side.
authOptions contains your authentication settings and must be imported from your NextAuth config.
Examples
Check if a user session exists and respond with the user's email or a message if not logged in.
NextJS
import { getServerSession } from 'next-auth/next'; import { authOptions } from './api/auth/[...nextauth]'; export default async function handler(req, res) { const session = await getServerSession(req, res, authOptions); if (session) { res.end(`User email: ${session.user.email}`); } else { res.end('No session found'); } }
Use the
useSession hook on the client side to show user info or ask them to log in.NextJS
import { useSession } from 'next-auth/react'; export default function Profile() { const { data: session } = useSession(); if (!session) return <p>Please log in to see your profile.</p>; return <p>Welcome, {session.user.name}!</p>; }
Sample Program
This API route checks if a user session exists. If yes, it greets the user by name. If not, it returns a 401 error saying the user is not authenticated.
NextJS
import { getServerSession } from 'next-auth/next'; import { authOptions } from './api/auth/[...nextauth]'; export default async function handler(req, res) { const session = await getServerSession(req, res, authOptions); if (session) { res.status(200).json({ message: `Hello, ${session.user.name}` }); } else { res.status(401).json({ message: 'Not authenticated' }); } }
OutputSuccess
Important Notes
Sessions are usually stored in cookies to keep users logged in across pages.
Always protect sensitive routes by checking the session on the server side.
Use HTTPS to keep session cookies secure.
Summary
Session management remembers users between pages or visits.
Use getServerSession on the server and useSession on the client.
Always check sessions to protect private data and pages.