---
name: "nextjs-middleware-edge-auth"
description: "Protect routes, verify JWT sessions, and rewrite regional traffic at the edge before hitting origins."
metadata:
  author: "Vercel"
  version: "1.0.0"
  runtime_compatibility:
    - "codex"
    - "claude-code"
    - "cursor"
    - "windsurf"
triggers:
  - "write nextjs middleware.ts"
  - "edge auth jwt nextjs"
  - "protect admin routes nextjs"
permissions:
  fs_read: true
  fs_write: "workspace"
  shell_exec: false
  net_access: false
---

# Next.js Edge Middleware Session & RBAC Route Protection

Authors Next.js middleware.ts: inspecting cookies and Authorization headers, decoding edge-compatible JWTs (jose), enforcing Role-Based Access Control (RBAC), conditional redirects, and header forwarding.

## When to Invoke
Invoke this skill whenever you need to:
- write nextjs middleware.ts
- edge auth jwt nextjs
- protect admin routes nextjs

## Execution SOP & Rules
1. Export config.matcher excluding static assets, images, and favicon (_next/static, favicon.ico).
2. Use edge-compatible crypto libraries like jose; avoid Node.js native crypto or fs modules in middleware.
3. Pass verified user ID down to Server Components via request headers: requestHeaders.set('x-user-id', id).
4. Return NextResponse.redirect(new URL('/login', request.url)) on missing or invalid tokens.

## Verification Checklist
- Run local linting, syntax validation, and type-checks before reporting completion.
- Ensure all created or modified files adhere to workspace boundaries and avoid uncommitted secrets.
- Verify tests or build commands exit cleanly with return code 0.
