How do you protect pages using getServerSideProps?

In the Pages Router, check the session inside getServerSideProps and return { redirect: { destination: "/login", permanent: false } } when the user is not signed in (or { notFound: true } when they lack access). Because it runs on the server before rendering, protected data never reaches unauthenticated users.

Steps

  1. Read the session from context.req (cookies) with your auth library: getServerSession(req, res, authOptions) in next-auth v4, or your own readSession(req.cookies.session).
  2. If missing, return a redirect, preserving the destination in a query param.
  3. If present, check permissions for this page.
  4. Fetch data for that user and return it as props.

Details

  • Use permanent: false so browsers do not cache the redirect.
  • Add Cache-Control: private, no-store for per-user pages so no CDN caches them.
  • Protect the data, not only the page. API routes the page calls must check the session too.
  • Pages using getStaticProps are public HTML; protect them with client-side checks plus protected API calls, or switch to getServerSideProps.

App Router equivalent

Call verifySession() in the page or layout (a Server Component) and redirect("/login") if it fails. Layout checks alone are not enough, because layouts do not re-render on every navigation; check in pages and data functions.

Code example

tsx
1// pages/billing.tsx
2import type { GetServerSideProps } from "next";
3import { readSession } from "@/lib/session-pages";
4import { db } from "@/lib/db";
5
6type Props = { invoices: { id: string; total: number }[] };
7
8export const getServerSideProps: GetServerSideProps<Props> = async ({ req, res, resolvedUrl }) => {
9 const session = await readSession(req.cookies.session);
10
11 if (!session) {
12 return {
13 redirect: { destination: `/login?next=${encodeURIComponent(resolvedUrl)}`, permanent: false },
14 };
15 }
16 if (session.role !== "owner") return { notFound: true }; // hide existence of the page
17
18 res.setHeader("Cache-Control", "private, no-store");
19 const invoices = await db.invoice.findMany({ where: { orgId: session.orgId }, select: { id: true, total: true } });
20 return { props: { invoices } };
21};
22
23export default function Billing({ invoices }: Props) {
24 return <ul>{invoices.map((i) => <li key={i.id}>${i.total}</li>)}</ul>;
25}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app