Add fine-grained authorization to a Next.js app
Build Next.js API routes for a blogging platform that register users in Permit.io and allow only users with the Author role through a protected route. This tutorial is for Next.js developers who want to enforce Permit.io policies from App Router route handlers and middleware.
When you finish, your Next.js app has two API routes:
| Route | What it does |
|---|---|
POST /api/register | Syncs a user to Permit.io and assigns the user the Reader role in the default tenant |
GET /api/protected/posts | Runs middleware that calls permit.check() and returns 403 unless the user in the user header has permission to create a Post |
Prerequisites
- A Permit.io account. See Create a Permit.io account.
- Node.js and npm, to run the app and install the Permit CLI.
- A Next.js 15.5 or later project that uses the App Router and a
srcdirectory, with the@/import alias pointing tosrc/. The middleware in this tutorial runs in the Node.js runtime, which Next.js middleware supports from 15.5. - Docker, to run the policy decision point (PDP) container.
1. Configure the policy in Permit
Create the blogging platform policy with the Permit CLI. If your environment already has a policy with a Post resource and an Author role that can create posts, skip to 2. Get your API key.
Install the Permit CLI
The Permit CLI creates policies and runs the PDP from your terminal. Install the CLI with npm:
npm install -g @permitio/cli
Run permit to confirm that the CLI is installed.
Sign in with the Permit CLI
Authenticate the CLI with your Permit.io account:
permit login
The command opens a browser window where you sign in. After you sign in, the CLI uses your default environment. To use a different environment, run permit env select and choose the environment.
Apply the blogging platform template
Permit CLI templates create a policy with predefined resources, roles, and rules. To see the available templates, run permit env template list. The template source files are in the Permit CLI repository.

Apply the blogging-platform template to your environment:
permit env template apply --template blogging-platform
The CLI prints a success message when the template is applied.
Review the policy in the Policy Editor
In the Permit dashboard, select your project and open the Policy screen.

The blogging-platform template creates:
| Policy element | What the template defines |
|---|---|
| Resources | Post (with a premium boolean attribute) and Comment, each with create, read, update, and delete actions |
| Roles | Admin (all actions), Author (create and read posts, read comments), Reader (create and read comments), and Premium Reader (read posts and comments) |
| Relationship | A Post is the parent of its Comment instances. An Author of a post instance becomes a Moderator of the comments on that post. This rule is relationship-based access control (ReBAC). |
| Resource set | Free Post contains posts where premium is false. Readers can read free posts. This rule is attribute-based access control (ABAC). |
This tutorial uses one rule from the policy: the Author role can create a Post, and the Reader role cannot. To change which role can perform an action, check or clear the box in the Policy Editor.
2. Get your API key
Your Next.js app and the PDP authenticate with Permit.io with your environment API key. Copy the API key of the environment where you applied the template. See Get your API key.
Anyone with the environment API key can change that environment's policy through the Permit API. Load the key from an environment variable, and don't commit it.
3. Run the PDP
The PDP evaluates each permission check against your policy. Start a PDP container with the Permit CLI:
permit pdp run
The command starts the PDP in Docker and prints the container ID and name. The PDP listens on port 7766, so your app connects to it at http://localhost:7766.

The Free Post resource set is an ABAC rule, and the Cloud PDP doesn't evaluate ABAC rules, so run the container PDP for this policy. To run the container with docker run instead, or to check that the PDP is healthy, see Run the PDP.
4. Build the Next.js app
Install the Node.js SDK
In your Next.js project directory, install the Permit Node.js SDK:
npm install permitio
For all SDK options, see Check permissions with the Node.js SDK.
Create a shared Permit client
Create src/lib/permit.ts with the following code:
// src/lib/permit.ts
import { Permit } from "permitio";
export const permit = new Permit({
token: process.env.PERMIT_API_KEY!,
pdp: process.env.PDP_URL!,
});
The file exports one Permit client that route handlers import with @/lib/permit. The client reads two environment variables:
| Variable | Value |
|---|---|
PERMIT_API_KEY | Your environment API key from 2. Get your API key |
PDP_URL | The PDP address from 3. Run the PDP: http://localhost:7766 |
Add the /api/register route
Create src/app/api/register/route.ts with the following code. The POST handler syncs the user to Permit.io with permit.api.users.sync(), then assigns the user the Reader role in the default tenant.
// src/app/api/register/route.ts
import { permit } from '@/lib/permit';
import { NextRequest } from 'next/server';
export async function POST(req: NextRequest) {
const { email, first_name, last_name } = await req.json();
if (!email || !first_name || !last_name) {
return new Response(JSON.stringify({ error: 'Missing required fields' }), { status: 400 });
}
try {
// Sync user with Permit
const user = await permit.api.users.sync({
key: email,
email,
first_name,
last_name,
});
// Assign role as part of registration
const assignedRole = {
user: email,
role: 'Reader',
tenant: 'default'
};
const response = await permit.api.users.assignRole(assignedRole);
// Continue with your app's registration logic
return new Response(JSON.stringify({ message: 'User registered and role assigned', user, response }), { status: 201 });
} catch (err) {
return new Response(JSON.stringify({ error: 'Failed to sync user' }), { status: 500 });
}
}
The user's email address is the user key in Permit.io. The middleware passes the same key to permit.check().
Check permissions in middleware
Next.js runs middleware from a middleware.ts file in the project root, or in src/ when the project uses a src directory. Create src/middleware.ts with the following code:
// src/middleware.ts
import { NextRequest, NextResponse } from 'next/server';
import { permit } from '@/lib/permit';
export async function middleware(req: NextRequest) {
// Only run for /api/protected/* routes
if (!req.nextUrl.pathname.startsWith('/api/protected/')) {
return NextResponse.next();
}
const user = req.headers.get('user');
const action = "create"
const resource = "Post"
if (!user) {
return new NextResponse(JSON.stringify({ message: 'missing the required headers' }), { status: 403 });
}
try {
const permitted = await permit.check(user, action, resource);
if (!permitted) {
return new NextResponse(JSON.stringify({ message: 'You are not authorized to access this resource' }), { status: 403 });
}
return NextResponse.next();
} catch (err) {
return new NextResponse(JSON.stringify({ error: 'Permission check failed' }), { status: 500 });
}
}
export const config = {
runtime: 'nodejs',
matcher: ['/api/protected/:path*'],
};
runtime: 'nodejs' is required. The Permit.io Node.js SDK depends on Node.js modules such as pino, which needs module, os, and path, so the SDK cannot run in the Edge runtime that Next.js 15 middleware uses by default. Without that line, Next.js 15 builds this middleware for the Edge runtime and the permission check fails. Node.js middleware is stable from Next.js 15.5. On Next.js 16 and later, middleware is renamed to proxy, a proxy.ts file runs in the Node.js runtime already, and setting runtime in its config throws an error. See the Next.js proxy reference.
The middleware runs for every request that matches /api/protected/:path*. It reads the user key from the user header and asks the PDP whether that user can create a Post:
| Condition | Response |
|---|---|
The user header is missing | 403 with "missing the required headers" |
| The PDP call fails | 500 with "Permission check failed" |
| The PDP denies the request | 403 with "You are not authorized to access this resource" |
| The PDP allows the request | Next.js passes the request to the route handler |
To protect other routes, such as commenting or editing, change the action and resource values and the matcher.
In a production app, take the user key from your authenticated session. This example reads the user key from a request header so that you can test the route with curl.
Add the protected /api/protected/posts route
In the App Router, a route handler lives in a route.ts file inside a folder named after the URL segment. Create src/app/api/protected/posts/route.ts with the following code:
// src/app/api/protected/posts/route.ts
import { NextRequest } from 'next/server';
export async function GET(req: NextRequest) {
return new Response(
JSON.stringify({ message: "You have passed the auth check" }),
{ headers: { "Content-Type": "application/json" } }
);
}
The GET handler returns "You have passed the auth check". The handler runs only when the middleware allows the request.
Start the Next.js app
Create a .env.local file in the project root, replacing <YOUR_API_KEY> with your API key:
PERMIT_API_KEY=<YOUR_API_KEY>
PDP_URL=http://localhost:7766
Start the development server:
npm run dev
The app listens on http://localhost:3000.
5. Test the permission check
Register two users, give one of them the Author role, and confirm that the PDP allows only that user through the protected route.
Register two users
In a second terminal, register John and Emma:
curl -X POST http://localhost:3000/api/register \
-H "Content-Type: application/json" \
-d '{"email": "john@example.com", "first_name": "John", "last_name": "Doe"}'
curl -X POST http://localhost:3000/api/register \
-H "Content-Type: application/json" \
-d '{"email": "emma@example.com", "first_name": "Emma", "last_name": "Den"}'
Each request returns HTTP 201 with "message": "User registered and role assigned", the synced user under user, and the role assignment under response, with "role": "Reader" and "tenant": "default".

Assign John the Author role
Both users have the Reader role, which can't create posts. Give John the Author role in the Permit dashboard:
- Open the Directory screen and select
john@example.comto open the Edit User panel. - Under Permissions Per Tenant, select the Default Tenant.
- In Top Level Access, add the Author role.
- Click Save.

For other ways to assign roles, including the API and SDK, see Sync users.
Check that John can access the route and Emma can't
Send a request to the protected route as John:
curl http://localhost:3000/api/protected/posts \
-H "user: john@example.com"
The PDP allows the request because John has the Author role. The route returns {"message":"You have passed the auth check"}.
Send the same request as Emma:
curl http://localhost:3000/api/protected/posts \
-H "user: emma@example.com"
The PDP denies the request because Emma has only the Reader role. The middleware returns HTTP 403 with {"message":"You are not authorized to access this resource"}.

Each check also appears in the Audit Log screen of the Permit dashboard, with the user, action, resource, and decision.
Next steps
- Check permissions with the Node.js SDK: SDK installation, configuration, and more
permit.check()examples. - Check permissions with permit.check(): check against tenants, resource instances, and attributes.
- Embed user management with Permit Elements: let your users manage roles from your app.
- Enforce permissions in the frontend with CASL: show or hide React components based on Permit.io permissions.