0
0
NextJSframework~5 mins

Server-side session access in NextJS

Choose your learning style9 modes available
Introduction

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.

You want to keep a user logged in across different pages without asking them to sign in again.
You need to store user preferences or shopping cart info securely during their visit.
You want to protect sensitive data by handling it only on the server, not in the browser.
You want to customize page content based on who is visiting, like showing their name.
You want to check if a user is allowed to see a page before sending it.
Syntax
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.

Examples
This example checks if the user is logged in. If not, it redirects them to the login page.
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);
  if (!session) {
    return { redirect: { destination: '/login', permanent: false } };
  }
  return { props: { session } };
}
This example extracts the user's email from the session and sends it as a prop to the page.
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: { userEmail: session?.user?.email ?? null } };
}
Sample Program

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.

NextJS
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 } };
}
OutputSuccess
Important Notes

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.

Summary

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.