Skip to main content

Next.js Middleware Authentication Chain

Build a Next.js middleware auth chain with role-based access, token refresh, session caching, security headers, and audit logging.

Fill in the placeholders

Edit the values, then copy your finished prompt.

Your Prompt
prompt.txt
You are a Next.js security architect. Help me implement a comprehensive middleware authentication chain for a SaaS platform application with NextAuth.js v5 authentication.

Step 1: Design the middleware.ts file at the project root that intercepts all requests. Create a matcher config that applies authentication checks to routes matching /dashboard/:path*, /api/:path*, /settings/:path* while excluding public routes, static assets, and API health checks. Structure the middleware to execute in under 50ms to avoid impacting page load times.

Step 2: Implement JWT token validation within the middleware. Decode the token from the httpOnly cookie and verify its signature, expiration, and issuer claims. If the token is expired but a refresh token exists, trigger a silent refresh flow that updates the cookies before the request proceeds.

Step 3: Build role-based access control by mapping 4 user roles to route permissions. Create a route-permission matrix where each protected route segment requires specific roles. Return a 403 redirect to an access-denied page when a valid user lacks permissions for the requested route.

Step 4: Implement a session validation layer that checks if the user session is still active on the NextAuth.js v5 server. Cache the session status using Next.js edge-compatible caching to avoid hitting the auth server on every request. Set a cache TTL of 5 minutes for session validity.

Step 5: Add security headers in the middleware response including Content-Security-Policy, X-Frame-Options, and Strict-Transport-Security. Implement CSRF protection for state-changing routes and rate limiting headers for API routes.

Step 6: Create comprehensive logging that captures authentication events (login, logout, token refresh, access denied) and sends them to Datadog. Include request metadata (IP, user agent, route) for security audit trails without logging sensitive token data.

What this prompt does

This prompt casts the AI as a Next.js security architect building a middleware authentication chain for a [app_type] app using [auth_provider]. It designs middleware.ts with a matcher that protects [protected_routes] while excluding public assets and health checks, structured to execute under [max_latency]. It then validates the JWT from [token_location], verifying signature, expiry, and issuer, and triggers a silent refresh when the access token is expired but a refresh token exists. Keeping the middleware under a tight latency budget matters more than people expect.

The structure works because edge auth is a sequence of guards. Role-based access maps [role_count] roles to a route-permission matrix returning 403 redirects; a session-validation layer checks the [auth_provider] server and caches status with a [cache_ttl] to avoid hammering it; security headers (CSP, X-Frame-Options, HSTS) plus CSRF and rate-limit headers are added to responses; and authentication events are logged to [logging_service] with request metadata but never raw tokens. The matcher config is what keeps the cost down: it applies auth checks only to [protected_routes] while excluding static assets and health checks, so the middleware does not run where it adds no value. Mapping [role_count] roles to a route-permission matrix turns access control into a single source of truth rather than scattered per-page checks, and returning a clean 403 redirect for a valid user lacking permission is clearer than a silent failure. Capturing IP, user agent, and route gives a usable audit trail without ever writing secrets to logs.

When to use it

  • You want auth enforced at the edge rather than scattered through pages
  • You need silent token refresh when access tokens expire
  • You want role-based access control via a route-permission matrix
  • You need session caching to avoid hitting the auth server on every request
  • You want security headers and CSRF protection added in middleware
  • You need audit logging of auth events without leaking token data

Example output

The AI returns a middleware.ts with a matcher config for [protected_routes], JWT validation reading from [token_location] with signature/expiry/issuer checks and a silent-refresh flow, a role-permission matrix across [role_count] roles returning 403 redirects, a session-validation layer caching status with [cache_ttl] TTL, security-header injection (CSP, X-Frame-Options, HSTS) plus CSRF and rate-limit headers, and logging of auth events to [logging_service] with request metadata but no sensitive token data.

Pro tips

  • Keep the matcher precise so static assets and health checks skip auth and stay under [max_latency]
  • Get the silent-refresh flow right — botching it either logs users out early or stampedes [auth_provider]
  • Cache session status with [cache_ttl] so you are not validating against the auth server on every single request
  • Never log raw tokens; capture IP, user agent, and route for the audit trail but keep secrets out of logs
  • Map every protected segment in the route-permission matrix so a valid user without the role gets a clean 403
  • Treat [max_latency] as a hard budget; middleware runs on every matched request and compounds fast

Frequently Asked Questions

How does the silent token refresh work?
When the access token is expired but a valid refresh token exists in `[token_location]`, the middleware triggers a refresh flow that updates the cookies before the request proceeds. Getting this right is delicate: a flawed flow either logs users out prematurely or overloads `[auth_provider]` with refresh calls.
Why cache session validation instead of checking every request?
Checking the `[auth_provider]` server on every request adds latency and load. The prompt caches session status with a `[cache_ttl]` using edge-compatible caching, so most requests use the cached result and only revalidate after the TTL expires, keeping the middleware under its latency budget.
Does it add security headers and CSRF protection?
Yes. The middleware response includes Content-Security-Policy, X-Frame-Options, and Strict-Transport-Security headers, plus CSRF protection for state-changing routes and rate-limit headers for API routes. These are applied centrally rather than per-page.
Is sensitive token data kept out of the audit logs?
Yes. Logging captures authentication events and request metadata like IP, user agent, and route for security audit trails, but explicitly excludes raw token data. This gives you a usable audit trail without turning your logs into a secret-leakage risk.
Engr Mejba Ahmed

Need this built for real?

Engr Mejba Ahmed

AI Developer · Software Engineer

I'm Mejba — I design and ship production AI systems, automations, and full-stack apps. If you want this turned into a working solution for your team, let's talk.

More in React & Next.js Prompts

Engr Mejba Ahmed

Engr Mejba Ahmed

AI assistant · trained on my work

👋

Hey there!

Quick Actions

WhatsApp Direct line to me

Chat on WhatsApp

+880 1723 741224 · Replies within the hour on working days

Popular Questions

Engr Mejba Ahmed is connected
Engr Mejba Ahmed is typing...
Engr Mejba Ahmed avatar

✉ Want me to follow up? Drop your email

Engr Mejba Ahmed avatar

📞 Connect Directly

Choose how you'd like to reach me

WhatsApp

+880 1723 741224

Email

mejba.13@gmail.com

✓ Details sent! I'll get back to you shortly.

Powered by OpenAI

335+

Blog Posts

25

AI Courses

63

Projects

Services & Expertise

Pricing & Process

Learning & Resources

Connect & Support