Server-side session access lets your Next.js app remember who a user is while keeping data safe on the server. This helps personalize pages and protect private info.
Server-side session access in NextJS
import { getServerSession } from 'next-auth/next'; import { authOptions } from './api/auth/[...nextauth]'; export async function getServerSideProps(context) { const session = await getServerSession(context.req, context.res, authOptions); return { props: { session } }; }
getServerSession fetches the session on the server using the request and response objects.
You need to pass your authOptions which define how authentication works in your app.
import { getServerSession } from 'next-auth/next'; import { authOptions } from './api/auth/[...nextauth]'; export async function getServerSideProps(context) { const session = await getServerSession(context.req, context.res, authOptions); if (!session) { return { redirect: { destination: '/login', permanent: false } }; } return { props: { session } }; }
import { getServerSession } from 'next-auth/next'; import { authOptions } from './api/auth/[...nextauth]'; export async function getServerSideProps(context) { const session = await getServerSession(context.req, context.res, authOptions); return { props: { userEmail: session?.user?.email ?? null } }; }
This Next.js page uses server-side session access to get the logged-in user's info before rendering. If no user is logged in, it shows a message. Otherwise, it welcomes the user by name and shows their email.
import { getServerSession } from 'next-auth/next'; import { authOptions } from './api/auth/[...nextauth]'; export default function ProfilePage({ session }) { if (!session) { return <p>You must be logged in to view this page.</p>; } return ( <main> <h1>Welcome, {session.user.name}!</h1> <p>Your email is {session.user.email}</p> </main> ); } export async function getServerSideProps(context) { const session = await getServerSession(context.req, context.res, authOptions); return { props: { session } }; }
Always handle the case when the session is null to avoid errors.
Server-side session access runs on every page request, so it can slow down your page if overused.
Use secure cookies and HTTPS to keep session data safe.
Server-side session access helps your app remember users safely on the server.
Use getServerSession inside getServerSideProps to get session data.
Check if a session exists to protect pages or customize content.