Performance: Server-side session access
This affects the time to first byte (TTFB) and overall server response time, impacting how quickly the page starts rendering.
Jump into concepts and practice - no test required
import { unstable_getServerSession } from 'next-auth/next'; export async function getServerSideProps(context) { const session = await unstable_getServerSession(context.req, context.res, authOptions); return { props: { user: session?.user ?? null } }; }
export async function getServerSideProps(context) { const session = await getSession({ req: context.req }); // heavy synchronous session parsing or multiple session reads return { props: { user: session.user } }; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy synchronous session parsing | N/A (server-side) | N/A | N/A | [X] Bad |
| Optimized async session retrieval with caching | N/A (server-side) | N/A | N/A | [OK] Good |
getServerSession in Next.js?getServerSessiongetServerSession runs on the clientgetServerSession in a Next.js page?getServerSession from 'next-auth/next'.getServerSideProps in Next.js, what will be logged if the user is not logged in?export async function getServerSideProps(context) {
const session = await getServerSession(context.req, context.res, authOptions);
console.log(session);
return { props: { user: session?.user || null } };
}getServerSession returns null, not undefined or error.session directly, so it logs null. The props user is set to null safely.export async function getServerSideProps(context) {
const session = getServerSession(context.req, context.res, authOptions);
if (!session) {
return { redirect: { destination: '/login', permanent: false } };
}
return { props: { user: session.user } };
}getServerSession returns a Promise, so it must be awaited to get the session object.session is a Promise, so the if check fails and code behaves incorrectly.getServerSession inside getServerSideProps to redirect unauthenticated users to '/login' and pass user data to the page?getServerSession to get the session object.!session, which means no logged-in user, correctly protecting the page.