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.

Vul de plaatshouders in

Edit the values, then copy your finished prompt.

Jouw Prompt
prompt.txt

                                

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.

Meer in React & Next.js Prompts

Engr Mejba Ahmed

Engr Mejba Ahmed

Claude Code Expert · Online

👋

Hey there!

Quick Actions

WhatsApp Instant reply

Chat on WhatsApp

+880 1723 741224 · Instant reply

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

[email protected]

✓ 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