Protect a Server-Rendered Page
Use getServerSession(req, res, authOptions) in getServerSideProps. Redirect to sign-in if no session exists. Do not rely only on a client-side redirect because it is not a security boundary.
File: `pages/dashboard.js`
import { getServerSession } from "next-auth/next";
import { authOptions } from "./api/auth/[...nextauth]";
export default function Dashboard({ email }) {
return <main><h1>Dashboard</h1><p>Signed in as {email}</p></main>;
}
export async function getServerSideProps(context) {
const session = await getServerSession(context.req, context.res, authOptions);
if (!session) return { redirect: { destination: "/auth/signin", permanent: false } };
return { props: { email: session.user?.email ?? "" } };
}Do not put secrets or sensitive records in returned props because they are serialized to the browser.