This guide shows how to protect Server Actions in a Next.js App Router application using protect().
protect() ensures a Server Action only executes for authenticated users and can optionally enforce group-based authorization.
protect()This guide assumes you’ve completed the Next.js App Router quickstart.
You should already have:
.env.localCreate a Server Action and call protect() before running any sensitive logic.
"use server";
import { protect } from "@monocloud/auth-nextjs";
export async function submitName(formData: FormData) {
await protect();
const name = String(formData.get("name") ?? "");
return { ok: true, name };
}
How it works:
protect() is server-only and can safely be used inside any Server Action, regardless of whether it was triggered from a Server or Client Component.
By default, users are returned to the page that triggered the Server Action.
To redirect users to a specific route after signing in, pass a returnUrl option.
"use server";
import { protect } from "@monocloud/auth-nextjs";
export async function submitName(formData: FormData) {
await protect({ returnUrl: "/server-actions" });
const name = String(formData.get("name") ?? "");
return { ok: true, name };
}
After authentication, users are redirected to http://localhost:3000/server-actions
You can restrict a Server Action 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.
"use server";
import { protect } from "@monocloud/auth-nextjs";
export async function submitAdminAction(formData: FormData) {
await protect({ groups: ["admin"] });
const value = String(formData.get("value") ?? "");
return { ok: true, value };
}
With this configuration:
Protect other parts of your application: