Skip to main content
Next.jsApp Routeradvanced

Next.js Edge Middleware & Session Gatekeeper

Design lightweight edge middleware for route protection, JWT validation, multi-tenant rewrites, and security headers.

Compatibility & Specs

Compatible AI Models
ClaudeChatGPT
Last UpdatedApr 1, 2026
Customizable Variables3 parameters

How to Use This Prompt

Follow this 3-step workflow to extract high-signal responses from any compatible AI model.

01

1. Tailor the Parameters

Use the interactive customizer above to substitute the bracketed placeholders with your exact context, requirements, and constraints.

02

2. Send to AI Model

Copy the prompt and paste it into Claude, ChatGPT, Gemini, or Copilot. These models follow structured multi-step constraints reliably.

03

3. Review and Iterate

Review the output against the verified benchmark below. Follow up in the conversation to stress-test edge cases or refine tone.

Prompt Variables & Parameters

Reference breakdown of every dynamic variable embedded in this prompt template.

PlaceholderParameter NameTypeStatusDescription & Guidance
[routing_requirements]Routing RequirementstextareaRequiredProtected paths, public paths, and dynamic rewritesDefault: 1. Protect `/dashboard/*`, `/workbench/*`, and `/settings/*`; 2. Allow public access to `/`, `/prompts/*`, `/categories/*`, `/api/webhooks/*`; 3. Preserve requested URL in query param `?returnTo=` on redirect.
[auth_mechanism]Authentication MechanismtextRequiredHow session tokens are validatedDefault: HTTP-only secure session cookie containing a signed JWT verified via JOSE and Web Crypto
[security_needs]Security & Multi-Tenant NeedstextOptionalSpecial security headers or subdomain mappingDefault: Strict security headers (HSTS, X-Content-Type-Options, Frame-Options DENY) and rate-limit header passthrough

Example Execution & Benchmark Output

Sample input arguments and the verified AI response demonstrating expected quality and formatting.

Sample VariablesInputs
[routing_requirements]
1. Protect `/dashboard/*`, `/workbench/*`, and `/settings/*`; 2. Allow public access to `/`, `/prompts/*`, `/categories/*`, `/api/webhooks/*`; 3. Preserve requested URL in query param `?returnTo=` on redirect.
[auth_mechanism]
HTTP-only secure session cookie containing a signed JWT verified via JOSE and Web Crypto
[security_needs]
Strict security headers (HSTS, X-Content-Type-Options, Frame-Options DENY) and rate-limit header passthrough
Expected AI ResponseVerified Result
### Production `middleware.ts` Implementation ```typescript import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; import { jwtVerify } from 'jose'; const SECRET_KEY = new TextEncoder().encode(process.env.JWT_SECRET_KEY || 'default-dev-secret'); const PROTECTED_PREFIXES = ['/dashboard', '/workbench', '/settings']; export async function middleware(request: NextRequest) { const { pathname } = request.nextUrl; // 1. Check if path requires authentication const isProtected = PROTECTED_PREFIXES.some((prefix) => pathname.startsWith(prefix)); if (isProtected) { const token = request.cookies.get('session_token')?.value; if (!token) { const loginUrl = new URL('/login', request.url); loginUrl.searchParams.set('returnTo', pathname); return NextResponse.redirect(loginUrl); } try { // Edge-compatible JWT verification using Web Crypto (jose) await jwtVerify(token, SECRET_KEY); } catch (err) { // Expired or invalid signature const loginUrl = new URL('/login', request.url); loginUrl.searchParams.set('returnTo', pathname); const response = NextResponse.redirect(loginUrl); response.cookies.delete('session_token'); return response; } } // 2. Attach Strict Security Headers const response = NextResponse.next(); response.headers.set('X-Frame-Options', 'DENY'); response.headers.set('X-Content-Type-Options', 'nosniff'); response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin'); response.headers.set('Strict-Transport-Security', 'max-age=63072000; includeSubDomains; preload'); return response; } export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico|api/webhooks).*)'], }; ```

Best Use Cases

Scenarios and roles where this prompt produces maximum leverage.

Next.js full-stack teams protecting private dashboard routes with sub-millisecond edge latency
Architects preventing unauthorized access without spinning up heavy Node.js server runtimes
Developers adding mandatory enterprise security headers across all web responses

Tips for Best Results

Techniques to elevate response fidelity

  • •Specify your exact runtime and dependency versions (e.g. Next.js 15, React 19, TypeScript 5.4) to eliminate outdated syntax hallucinations.
  • •Ask the model to enumerate potential runtime failure modes, concurrency issues, or null boundary states before generating code.
  • •Request idiomatic, type-safe solutions with clear unit test skeletons rather than monolithic scripts.

Common Mistakes to Avoid

Frequent failure modes and anti-patterns

  • •Pasting large unformatted code dumps without indicating the specific function or error you want analyzed.
  • •Deploying AI-generated code directly to production without verifying memory safety, edge cases, and security vulnerabilities.
  • •Omitting architectural constraints (such as SSR vs. client component boundaries or database indexing).

Part of Curated Collections

This prompt is sequenced as part of these goal-oriented workflows

View all collections

Related AI Prompts

Complementary workflows in Next.js

View all Next.js prompts
Next.jsintermediate

Next.js App Router Performance & Cache Auditor

Audit Next.js routes for static pre-rendering, cache invalidation, and Core Web Vitals optimization.

claudechatgptperplexity
#nextjs#turbopack#caching
Codingadvanced

OWASP Security Vulnerability & Dependency Auditor

Inspect code modules for injection vulnerabilities, insecure deserialization, broken access controls, and auth flaws.

claudechatgptgemini
#security-audit#owasp#vulnerability-scanning
Next.jsadvanced

Next.js Server vs. Client Component Boundary Decision Matrix

Audit page trees to push 'use client' directives to the leaves, minimize JS bundles, and maximize server streaming.

claudechatgptgemini
#nextjs#server-components#client-components