Next.jsEasy
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
- Read the session from
context.req(cookies) with your auth library:getServerSession(req, res, authOptions)in next-auth v4, or your ownreadSession(req.cookies.session). - If missing, return a redirect, preserving the destination in a query param.
- If present, check permissions for this page.
- Fetch data for that user and return it as props.
Details
- Use
permanent: falseso browsers do not cache the redirect. - Add
Cache-Control: private, no-storefor 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
getStaticPropsare public HTML; protect them with client-side checks plus protected API calls, or switch togetServerSideProps.
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.tsx2import type { GetServerSideProps } from "next";3import { readSession } from "@/lib/session-pages";4import { db } from "@/lib/db";56type Props = { invoices: { id: string; total: number }[] };78export const getServerSideProps: GetServerSideProps<Props> = async ({ req, res, resolvedUrl }) => {9 const session = await readSession(req.cookies.session);1011 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 page1718 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};2223export 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.