This guide shows how to protect Client Components in a Next.js App Router application using protectClientPage() from the MonoCloud SDK.
Protected components require authentication and provide client-side access control, including group-based authorization, redirects, and custom error handling.
protectClientPage()This guide assumes you’ve completed the Next.js App Router quickstart.
You should already have:
.env.localCreate a Client Component and wrap it with protectClientPage().
"use client";
import { MonoCloudUser } from "@monocloud/auth-nextjs";
import { protectClientPage } from "@monocloud/auth-nextjs/client";
type Props = {
user: MonoCloudUser;
};
const Home = ({ user }: Props) => {
return (
<div>Hi {user.email}</div>
);
};
export default protectClientPage(Home);
How it works:
user object is injected as a propprotectClientPage() runs entirely in the browser.
This means:
For protecting sensitive data or enforcing authorization on the server, use protectPage() or protectApi() instead.
By 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 protectClientPage(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 protectClientPage(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 protectClientPage(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 protectClientPage(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.protectClientPage() supports an onError callback to render fallback UI when authentication fails (for example, due to network issues).
export default protectClientPage(Home, {
onError: (error: Error) => (
<div>
Error: {error.message}
</div>
),
});
With this configuration:
You can customize this to show retry actions, support messaging, or integrate with observability tools.
Protect other parts of your application: