This guide shows how to protect Server Components in a Next.js App Router application using protectPage().
Protected server components require authentication and can optionally enforce group-based authorization and customize redirects.
protectPage()This guide assumes you’ve completed the Next.js App Router quickstart.
You should already have:
.env.localCreate a Server Component and wrap it with protectPage().
import { MonoCloudUser, protectPage } from "@monocloud/auth-nextjs";
type HomePageProps = {
user: MonoCloudUser;
};
function Home({ user }: HomePageProps) {
return <div>Hi {user.email}</div>;
}
export default protectPage(Home);
How it works:
user object is injected as a propBy default, users are returned to the page they attempted to access.
To redirect users to a specific route after authentication, pass a returnUrl.
export default protectPage(Home, {
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 default protectPage(Home, {
groups: ["admin"],
});
With this configuration, only authenticated users in the admin group can access the page.
Use onAccessDenied to render custom UI when the user is not authenticated.
export default protectPage(Home, {
onAccessDenied: () => (
<div>
<h1>Access Denied</h1>
<p>Please sign in to continue.</p>
</div>
)
});
How it works:
onAccessDenied is not provided, the user is automatically redirected to the sign-in flow.Use onGroupAccessDenied to render custom UI when the user is authenticated but does not belong to the required group. This callback receives the authenticated user.
export default protectPage(Home, {
groups: ['admin'],
onGroupAccessDenied: ({ user }) => (
<div>
<h1>Unauthorized</h1>
<p>User {user.email}, does not have access to this page.</p>
</div>
),
});
How it works:
onGroupAccessDenied is not provided, a default Access Denied message is rendered.Protect other parts of your application: