Performance: Session management
Session management affects page load speed and interaction responsiveness by controlling how user data is stored and accessed during navigation.
Jump into concepts and practice - no test required
import { getServerSession } from 'next-auth/next'; import { authOptions } from './authOptions'; export default async function handler(req, res) { const session = await getServerSession(req, res, authOptions); if (!session) { res.status(401).json({ error: 'Unauthorized' }); return; } // minimal async processing res.status(200).json({ user: session.user }); }
import { getSession } from 'next-auth/react'; export default async function handler(req, res) { const session = await getSession({ req }); if (!session) { res.status(401).json({ error: 'Unauthorized' }); return; } // heavy synchronous processing here res.status(200).json({ user: session.user }); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous session fetch with heavy processing | Minimal | Multiple due to blocking | High due to delayed paint | [X] Bad |
| Async session fetch with minimal processing | Minimal | Single or none | Low, smooth paint | [OK] Good |
| Immediate localStorage writes on session change | None | Multiple reflows | Medium due to blocking | [X] Bad |
| Deferred localStorage writes using requestIdleCallback | None | Single or none | Low, non-blocking | [OK] Good |
getServerSession() is used on the server to get the current session.useSession(), which is client-side only. Options B and D are not valid Next.js functions.import { useSession } from 'next-auth/react';
export default function Profile() {
const { data: session } = useSession();
if (!session) return <p>Please log in</p>;
return <p>Welcome, {session.user.name}</p>;
}session is falsy (not logged in), then returns <p>Please log in</p> immediately.session is null or undefined, so the component returns <p>Please log in</p>.import { getServerSession } from 'next-auth/next';
export async function getServerSideProps(context) {
const session = await getServerSession(context);
if (!session) {
return { redirect: { destination: '/login', permanent: false } };
}
return { props: { user: session.user } };
}getServerSession requires the request context to access cookies and headers, so it needs context.req and context.res or the full context passed.getServerSession() without arguments, which causes it to fail to read session data.getServerSession in getServerSideProps allows redirecting users before the page loads if they are not logged in.useSession in the component helps show loading states or user info once the page is loaded.