This guide shows how to protect server-rendered pages in a Next.js Pages Router application using protectPage().
Protected pages require authentication and can optionally enforce group-based authorization, customize redirects, and render custom access denied UI.
protectPage()This guide assumes you’ve completed the Next.js Pages Router quickstart.
You should already have:
pages/ directory).env.localCreate a Pages Router page and wrap getServerSideProps with protectPage().
import { MonoCloudUser, protectPage } from "@monocloud/auth-nextjs";
type Props = {
user: MonoCloudUser;
};
export default function ServerPage({ user }: Props) {
return <div>Hi {user.email}</div>;
}
export const getServerSideProps = protectPage<Props>();
How it works:
protectPage() runs on every requestuser object is injected into page propsBy default, users are returned to the page they attempted to access.
To redirect users to a specific route after authentication, pass a returnUrl.
export const getServerSideProps = protectPage<Props>({
returnUrl: "/dashboard",
});
After authentication, users are redirected to http://localhost:3000/dashboard
You can restrict access to users belonging to specific groups.
groups to the application scopes.env.local:MONOCLOUD_AUTH_SCOPES=openid profile email groups
After updating scopes, users must sign out and sign back in for the new claims to be included in their session.
export const getServerSideProps = protectPage<Props>({
groups: ["admin"],
});
With this configuration, only authenticated users in the admin group can access the page.
Use onAccessDenied to override the default redirect when a user is not authenticated.
export const getServerSideProps = protectPage<Props>({
onAccessDenied: (ctx) => ({
redirect: {
destination: "/custom-signin",
permanent: false,
},
}),
});
How it works:
onAccessDenied is not provided, the user is automatically redirected to the sign-in flow.Use onGroupAccessDenied to customize the behavior when a user is authenticated but does not belong to the required group.
export const getServerSideProps = protectPage<Props>({
groups: ["admin"],
onGroupAccessDenied: (ctx) => {
console.warn(`Unauthorized access attempt by ${ctx.user.email}`);
return {
redirect: {
destination: "/403",
permanent: false,
},
};
},
});
How it works:
getServerSideProps context extended with the authenticated user.If onGroupAccessDenied is not provided, protectPage() injects a groupAccessDenied: true prop into the page so you can render an alternate UI.
export default function ServerPage({ user, groupAccessDenied }: Props) {
if (groupAccessDenied) {
return <div>Access Denied</div>;
}
return <div>Hi {user.email}</div>;
}
Protect other parts of your application: