Verified SOP & TutorialAudited Score 98/100

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.

Target Runtimes:codexclaude-codecursorwindsurf
5 min read • Updated for 2026

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

Codex Desktop, Claude Code CLI, Cursor, or Windsurf installed with workspace permissions
Node.js 20.x or higher and pnpm/npm installed in the workspace sandbox
Next.js 14+ or 15+ App Router project initialized with TypeScript
Edge-compatible JWT library 'jose' installed (`pnpm add jose`)

Verified Search Intents & Long-Tail Queries Solved

SEO Audit Score: 98/100

This operational tutorial is engineered to provide deterministic solutions for these developer search queries:

#install nextjs-middleware-edge-auth in cursor ide#claude code nextjs-middleware-edge-auth rules#codex desktop nextjs-middleware-edge-auth setup tutorial#how to fix nextjs-middleware-edge-auth agent execution error#nextjs edge middleware jwt verification jose#nextjs edge rbac route protection middleware ts#deterministic fullstack agent SOP nextjs middleware#nextjs-middleware-edge-auth sandbox permissions and security score

Step-by-Step Execution Playbook

1

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.

Terminal Command
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.md
middleware.ts
import { 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)$).*)',
  ],
};
Production Pro-Tip

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.

Sandbox Gotcha

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.

2

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.

Terminal Command
pnpm add jose && echo 'JWT_SECRET="ultra-secure-edge-compatible-secret-key-min-32-chars"' >> .env.local
Production Pro-Tip

Always 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.

Sandbox Gotcha

Never commit `.env.local` to source control. Ensure `.env.local` is listed in `.gitignore` before invoking coding agents.

3

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.

Production Pro-Tip

Use concise prompts specifying public vs. protected route patterns to avoid over-restrictive route locking.

Sandbox Gotcha

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.

4

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.

Terminal Command
pnpm next build --no-lint && pnpm eslint middleware.ts
Production Pro-Tip

Check `.next/server/middleware-manifest.json` after running build to confirm that route matchers and edge chunks compiled within size constraints.

Sandbox Gotcha

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

Tested Trigger Prompt (Feed directly into Codex, Claude, or Cursor):

“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.”

Deterministic Agent Verification Pipeline:
Imports { NextResponse } from 'next/server' and jwtVerify from 'jose' without using Node crypto.
Configures config.matcher to exclude static resources, favicon, and Next.js asset bundles.
Extracts JWT from cookies or Authorization Bearer header and executes jwtVerify with TextEncoder encoded secret.
Applies RBAC check: redirects authenticated non-admin users visiting /admin to /unauthorized.
Mutates requestHeaders to set 'x-user-id' and 'x-user-role', passing them into NextResponse.next({ request: { headers } }).
Runs local TypeScript checks and verifies that build executes without Edge Runtime syntax violations.

Runtime Troubleshooting & Failure Modes

Error: Error: A Node.js API is used (process.version) which is not supported in the Edge Runtime. The problematic import was in ./middleware.ts

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.

Resolution Command / Fix:
Replace 'jsonwebtoken' with 'jose' for JWT operations, and use Web Crypto API (crypto.subtle) instead of Node crypto.
Error: TypeError: Key must be one of type CryptoKey, KeyObject, or Uint8Array. Received an instance of String

Root Cause: The JWT verification function in 'jose' was passed a plain string for the secret key instead of a binary Uint8Array representation.

Resolution Command / Fix:
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.

Get 1-Click Install Spec