The Complete Production SOP: How to Deploy and Run Next.js Edge Middleware Session & RBAC Route Protection in Autonomous AI Agents
Production SOP to install and run nextjs-middleware-edge-auth in Codex, Claude Code, Cursor, and Windsurf. Includes edge-safe JWT verification and RBAC steps.
Technical Overview & Architectural Context
Autonomous coding agents frequently stumble when generating Next.js middleware because of runtime context mismatches. LLMs often import Node.js standard modules like 'crypto', 'jsonwebtoken', or 'fs' directly into `middleware.ts`, which breaks immediately upon compilation because Next.js Edge Middleware executes inside the V8 Edge Runtime rather than the Node.js standard environment. Additionally, agents routinely omit strict matcher filters, leading to redundant middleware execution over static assets, SVG icons, and Next.js internal chunks. The 'nextjs-middleware-edge-auth' skill establishes strict guardrails and deterministic SOP boundaries. It restricts the agent to edge-compliant Web Crypto primitives and lightweight libraries like 'jose', mandates exclusion patterns for `_next/static` assets, and enforces secure session header forwarding (`x-user-id`, `x-user-role`) straight into Server Components and Route Handlers without origin-bound re-authentications.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Environment Setup & SKILL.md Mounting
Create the local skill manifest directory and inject verified procedural rules into agent runtime path.
Agent runtimes such as Claude Code, Codex, and Cursor read custom skill directives from `.agents/skills` or `.claude/skills`. Installing this SKILL.md provides explicit frontmatter triggers and AST-level generation constraints that prevent runtime crashes caused by Node-specific modules.
mkdir -p .agents/skills/nextjs-middleware-edge-auth && curl -fsSL https://askills.dev/api/skills/nextjs-middleware-edge-auth/raw -o .agents/skills/nextjs-middleware-edge-auth/SKILL.mdimport { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { jwtVerify } from 'jose';
const PUBLIC_ROUTES = ['/login', '/register', '/api/public'];
const ADMIN_ROUTES = ['/admin'];
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
if (PUBLIC_ROUTES.some((route) => pathname.startsWith(route))) {
return NextResponse.next();
}
const token = request.cookies.get('session_token')?.value ||
request.headers.get('authorization')?.replace('Bearer ', '');
if (!token) {
return NextResponse.redirect(new URL('/login', request.url));
}
try {
const secret = new TextEncoder().encode(process.env.JWT_SECRET);
const { payload } = await jwtVerify(token, secret);
const role = (payload.role as string) || 'user';
if (ADMIN_ROUTES.some((route) => pathname.startsWith(route)) && role !== 'admin') {
return NextResponse.redirect(new URL('/unauthorized', request.url));
}
const requestHeaders = new Headers(request.headers);
requestHeaders.set('x-user-id', String(payload.sub));
requestHeaders.set('x-user-role', role);
return NextResponse.next({
request: { headers: requestHeaders },
});
} catch {
return NextResponse.redirect(new URL('/login', request.url));
}
}
export const config = {
matcher: [
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
],
};Ensure the matcher regex rigorously eliminates static files; running JWT edge verification on favicon.ico or bundled CSS degrades page load speeds and wastes CPU cycles.
Never import 'jsonwebtoken' or 'crypto'; they will immediately trigger a 'Dynamic Code Evaluation (e.g. eval, Function) not allowed in Edge Runtime' error during the build.
Environment Secrets & Dependency Validation
Configure required Edge JWT signing keys and verify Jose dependency installation.
Next.js Edge Middleware loads environment variables defined in `.env.local` or host configurations (like Vercel Edge Config). Validate that `jose` is installed in `package.json` and that secret keys are encoded as a Uint8Array using Web Crypto APIs.
pnpm add jose && echo 'JWT_SECRET="ultra-secure-edge-compatible-secret-key-min-32-chars"' >> .env.localAlways encode string secrets via `new TextEncoder().encode(process.env.JWT_SECRET)` before passing to Jose; passing raw strings to Edge JWT functions throws a TypeError.
Never commit `.env.local` to source control. Ensure `.env.local` is listed in `.gitignore` before invoking coding agents.
Intent Matching & Trigger Invocation
Activate the skill using declarative natural language triggers matching the SKILL.md definition.
When prompted with registered triggers like 'write nextjs middleware.ts' or 'protect admin routes nextjs', the autonomous agent parses the SOP rules: it sets up custom request headers for Server Components, handles fallback redirection, and configures route guards for designated RBAC roles.
Use concise prompts specifying public vs. protected route patterns to avoid over-restrictive route locking.
Make sure your root middleware is located in the root directory or inside `src/` depending on your Next.js directory layout; having middleware in both locations triggers build collisions.
Verification, Linting & Output Quality Gate
Run Next.js build verification to validate Edge Runtime compatibility and lint compliance.
Before accepting any autonomous agent output, run type checking and standard Next.js build checks. The compiler checks whether Edge Middleware imports unsupported Node primitives or uses invalid matchers.
pnpm next build --no-lint && pnpm eslint middleware.tsCheck `.next/server/middleware-manifest.json` after running build to confirm that route matchers and edge chunks compiled within size constraints.
Middleware bundle size cannot exceed 1MB (or 4MB on specialized Edge plans); avoid bundling large client utilities into middleware logic.
Real-World Scenario: Enforce Role-Based Access Control and Edge Session Forwarding in Next.js 15 App Router
“write nextjs middleware.ts to edge auth jwt nextjs. Protect /admin routes for 'admin' role only, allow /api/health and /login publicly, and forward x-user-id and x-user-role headers to server components.”
Runtime Troubleshooting & Failure Modes
Root Cause: The agent imported a module reliant on Node.js runtime APIs (e.g., 'jsonwebtoken', 'crypto', 'path') instead of universal Edge/Web standard APIs.
Replace 'jsonwebtoken' with 'jose' for JWT operations, and use Web Crypto API (crypto.subtle) instead of Node crypto.Root Cause: The JWT verification function in 'jose' was passed a plain string for the secret key instead of a binary Uint8Array representation.
Wrap the environment variable string: new TextEncoder().encode(process.env.JWT_SECRET)Frequently Asked Questions (Next.js Edge Middleware Session & RBAC Route Protection SOP)
Q:Can I use Next.js Edge Middleware Session & RBAC Route Protection across Codex, Claude Code, and Cursor simultaneously?
Yes. This skill adheres to the universal SKILL.md specification. All compatible runtimes (Codex, Claude Code, Cursor, Windsurf) parse the YAML frontmatter, execution rules, and security boundaries seamlessly without vendor lock-in.
Q:How does Next.js Edge Middleware Session & RBAC Route Protection prevent context window overflow during long agent sessions?
Instead of re-explaining Next.js Edge limitations and rewriting edge authentication boilerplate across prompts, the mounted SKILL.md injects a precise SOP directly into the agent's deterministic instruction loop, minimizing conversational token overhead.
Q:Does this skill require escalated root or container permissions?
No. The skill is audited with a security score of 98/100, requires no root or shell execution permissions (`shell_exec: false`), has zero network access (`net_access: false`), and limits write access strictly to workspace files.
Ready to equip your autonomous agent with Next.js Edge Middleware Session & RBAC Route Protection?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.