Add Auth Middleware with AI Prompts

TL;DR

Auth middleware lets you protect routes consistently without repeating code. Create a reusable function that validates sessions/tokens and attach user info to the request. These prompts help you build middleware for different frameworks.

Next.js Middleware

Copy this prompt to generate a complete authentication middleware for Next.js App Router. Your AI will create middleware.ts with session validation, route protection patterns, and helper functions for server components and API routes.

AI Prompt

Next.js Auth Middleware

Create authentication middleware for Next.js App Router.

Requirements:

  1. Check for valid session cookie
  2. Validate session on server
  3. Redirect unauthenticated users to login
  4. Protect specific routes by pattern
  5. Allow public routes through

middleware.ts should:

  • Run on matched routes
  • Check session cookie exists
  • Verify session is valid (not expired)
  • Redirect to /login if invalid
  • Pass through if valid

Config matcher:

  • Protect: /dashboard/, /api/protected/
  • Allow: /login, /register, /api/public/*

Also create:

  • getSession() helper for server components
  • requireAuth() wrapper for API routes
  • useAuth() hook for client components

Express Middleware

Use this prompt to generate reusable Express middleware functions for authentication. You'll get requireAuth, optionalAuth, and requireRole middleware with proper error responses for missing, invalid, and expired tokens.

AI Prompt

Express Auth Middleware

Create reusable auth middleware for Express.

Middleware function should:

  1. Extract token from Authorization header or cookie
  2. Validate token (JWT or session lookup)
  3. Attach user to req.user
  4. Call next() if valid
  5. Return 401 if invalid

Create variations:

  • requireAuth: must be authenticated
  • optionalAuth: attach user if present, continue either way
  • requireRole(role): must have specific role

Usage: app.get('/protected', requireAuth, handler) app.get('/admin', requireAuth, requireRole('admin'), handler) app.get('/public', optionalAuth, handler)

Handle errors:

  • Missing token: 401 with { error: 'Authentication required' }
  • Invalid token: 401 with { error: 'Invalid token' }
  • Expired token: 401 with { error: 'Token expired' }
  • Insufficient role: 403 with { error: 'Forbidden' }

Default deny: Your middleware should require authentication by default. Explicitly allow public routes rather than explicitly protecting private ones. Missing a protection is worse than over-protecting.

API Route Protection

Paste this prompt to create a withAuth higher-order function that wraps API route handlers. Your AI will generate a typed wrapper that validates sessions, fetches the user, checks roles, and logs unauthorized attempts.

AI Prompt

Protect API Routes

Create a wrapper to protect API routes with auth.

For Next.js API routes / Route Handlers:

Create withAuth higher-order function:

  • Validates session before running handler
  • Passes user to handler
  • Returns 401 if not authenticated
  • Handles errors consistently

Usage: export const GET = withAuth(async (req, { user }) => { // user is guaranteed to exist here return Response.json({ user }) })

For role-based: export const DELETE = withAuth( async (req, { user }) => { ... }, { requiredRole: 'admin' } )

The wrapper should:

  • Parse and validate session/token
  • Fetch user from database
  • Check role if specified
  • Log unauthorized attempts
  • Provide typed user object

Server Action Protection

Use this prompt to add authentication guards to Next.js Server Actions. Your AI will create a reusable authAction wrapper that verifies the session before executing any server-side mutation.

AI Prompt

Protect Server Actions

Add auth checks to Next.js Server Actions.

Server Actions can be called from client - always verify auth!

Create pattern: async function protectedAction(formData: FormData) { 'use server'

const session = await getSession() if (!session) { throw new Error('Unauthorized') }

// Now safe to proceed with session.user }

Create reusable wrapper: const authAction = ( action: (user: User, ...args: any) => Promise ) => { return async (...args: any): Promise => { const session = await getSession() if (!session) throw new Error('Unauthorized') return action(session.user, ...args) } }

Usage: export const updateProfile = authAction(async (user, data) => { // user is verified })

Pro tip: Add request logging to your auth middleware. Log successful auths (user, route, time) and failed attempts (IP, route, reason) for security monitoring.

Should middleware validate the full session or just check existence?

At minimum, verify the session exists and hasn't expired. For high-security apps, also verify the user still exists and isn't disabled. Balance security with performance.

Where should I check permissions - middleware or handler?

Basic auth in middleware, specific permissions in handler. Middleware handles "is user logged in?" Handler handles "can this user access this specific resource?"

Further Reading

Want to understand the vulnerability before fixing it? These guides explain what's happening and why.

Find Unprotected Routes

Scan your app for routes missing authentication.

AI Fix Prompts

Add Auth Middleware with AI Prompts