[{"data":1,"prerenderedAt":412},["ShallowReactive",2],{"blog-prompts/add-auth-middleware":3},{"id":4,"title":5,"body":6,"category":391,"date":392,"dateModified":393,"description":394,"draft":395,"extension":396,"faq":397,"featured":395,"headerVariant":398,"image":397,"keywords":397,"meta":399,"navigation":400,"ogDescription":401,"ogTitle":397,"path":402,"readTime":397,"schemaOrg":403,"schemaType":404,"seo":405,"sitemap":406,"stem":407,"tags":408,"twitterCard":410,"__hash__":411},"blog/blog/prompts/add-auth-middleware.md","Add Auth Middleware with AI Prompts",{"type":7,"value":8,"toc":381},"minimark",[9,16,21,29,108,112,127,187,197,201,208,260,264,271,302,311,327,331,334,355,369],[10,11,12],"tldr",{},[13,14,15],"p",{},"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.",[17,18,20],"h2",{"id":19},"nextjs-middleware","Next.js Middleware",[13,22,23,24,28],{},"Copy this prompt to generate a complete authentication middleware for Next.js App Router. Your AI will create ",[25,26,27],"code",{},"middleware.ts"," with session validation, route protection patterns, and helper functions for server components and API routes.",[30,31,33,36,39,58,61,79,82,94,97],"prompt-box",{"title":32},"Next.js Auth Middleware",[13,34,35],{},"Create authentication middleware for Next.js App Router.",[13,37,38],{},"Requirements:",[40,41,42,46,49,52,55],"ol",{},[43,44,45],"li",{},"Check for valid session cookie",[43,47,48],{},"Validate session on server",[43,50,51],{},"Redirect unauthenticated users to login",[43,53,54],{},"Protect specific routes by pattern",[43,56,57],{},"Allow public routes through",[13,59,60],{},"middleware.ts should:",[62,63,64,67,70,73,76],"ul",{},[43,65,66],{},"Run on matched routes",[43,68,69],{},"Check session cookie exists",[43,71,72],{},"Verify session is valid (not expired)",[43,74,75],{},"Redirect to /login if invalid",[43,77,78],{},"Pass through if valid",[13,80,81],{},"Config matcher:",[62,83,84,91],{},[43,85,86,87],{},"Protect: /dashboard/",[88,89,90],"em",{},", /api/protected/",[43,92,93],{},"Allow: /login, /register, /api/public/*",[13,95,96],{},"Also create:",[62,98,99,102,105],{},[43,100,101],{},"getSession() helper for server components",[43,103,104],{},"requireAuth() wrapper for API routes",[43,106,107],{},"useAuth() hook for client components",[17,109,111],{"id":110},"express-middleware","Express Middleware",[13,113,114,115,118,119,122,123,126],{},"Use this prompt to generate reusable Express middleware functions for authentication. You'll get ",[25,116,117],{},"requireAuth",", ",[25,120,121],{},"optionalAuth",", and ",[25,124,125],{},"requireRole"," middleware with proper error responses for missing, invalid, and expired tokens.",[30,128,130,133,136,153,156,167,170,173],{"title":129},"Express Auth Middleware",[13,131,132],{},"Create reusable auth middleware for Express.",[13,134,135],{},"Middleware function should:",[40,137,138,141,144,147,150],{},[43,139,140],{},"Extract token from Authorization header or cookie",[43,142,143],{},"Validate token (JWT or session lookup)",[43,145,146],{},"Attach user to req.user",[43,148,149],{},"Call next() if valid",[43,151,152],{},"Return 401 if invalid",[13,154,155],{},"Create variations:",[62,157,158,161,164],{},[43,159,160],{},"requireAuth: must be authenticated",[43,162,163],{},"optionalAuth: attach user if present, continue either way",[43,165,166],{},"requireRole(role): must have specific role",[13,168,169],{},"Usage:\napp.get('/protected', requireAuth, handler)\napp.get('/admin', requireAuth, requireRole('admin'), handler)\napp.get('/public', optionalAuth, handler)",[13,171,172],{},"Handle errors:",[62,174,175,178,181,184],{},[43,176,177],{},"Missing token: 401 with { error: 'Authentication required' }",[43,179,180],{},"Invalid token: 401 with { error: 'Invalid token' }",[43,182,183],{},"Expired token: 401 with { error: 'Token expired' }",[43,185,186],{},"Insufficient role: 403 with { error: 'Forbidden' }",[188,189,190],"warning-box",{},[13,191,192,196],{},[193,194,195],"strong",{},"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.",[17,198,200],{"id":199},"api-route-protection","API Route Protection",[13,202,203,204,207],{},"Paste this prompt to create a ",[25,205,206],{},"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.",[30,209,211,214,217,220,234,237,240,243],{"title":210},"Protect API Routes",[13,212,213],{},"Create a wrapper to protect API routes with auth.",[13,215,216],{},"For Next.js API routes / Route Handlers:",[13,218,219],{},"Create withAuth higher-order function:",[62,221,222,225,228,231],{},[43,223,224],{},"Validates session before running handler",[43,226,227],{},"Passes user to handler",[43,229,230],{},"Returns 401 if not authenticated",[43,232,233],{},"Handles errors consistently",[13,235,236],{},"Usage:\nexport const GET = withAuth(async (req, { user }) => {\n// user is guaranteed to exist here\nreturn Response.json({ user })\n})",[13,238,239],{},"For role-based:\nexport const DELETE = withAuth(\nasync (req, { user }) => { ... },\n{ requiredRole: 'admin' }\n)",[13,241,242],{},"The wrapper should:",[62,244,245,248,251,254,257],{},[43,246,247],{},"Parse and validate session/token",[43,249,250],{},"Fetch user from database",[43,252,253],{},"Check role if specified",[43,255,256],{},"Log unauthorized attempts",[43,258,259],{},"Provide typed user object",[17,261,263],{"id":262},"server-action-protection","Server Action Protection",[13,265,266,267,270],{},"Use this prompt to add authentication guards to Next.js Server Actions. Your AI will create a reusable ",[25,268,269],{},"authAction"," wrapper that verifies the session before executing any server-side mutation.",[30,272,274,277,280,283,286,289,299],{"title":273},"Protect Server Actions",[13,275,276],{},"Add auth checks to Next.js Server Actions.",[13,278,279],{},"Server Actions can be called from client - always verify auth!",[13,281,282],{},"Create pattern:\nasync function protectedAction(formData: FormData) {\n'use server'",[13,284,285],{},"const session = await getSession()\nif (!session) {\nthrow new Error('Unauthorized')\n}",[13,287,288],{},"// Now safe to proceed with session.user\n}",[13,290,291,292,295,296,298],{},"Create reusable wrapper:\nconst authAction = (\naction: (user: User, ...args: any",[293,294],"span",{},") => Promise\n) => {\nreturn async (...args: any",[293,297],{},"): Promise => {\nconst session = await getSession()\nif (!session) throw new Error('Unauthorized')\nreturn action(session.user, ...args)\n}\n}",[13,300,301],{},"Usage:\nexport const updateProfile = authAction(async (user, data) => {\n// user is verified\n})",[303,304,305],"tip-box",{},[13,306,307,310],{},[193,308,309],{},"Pro tip:"," Add request logging to your auth middleware. Log successful auths (user, route, time) and failed attempts (IP, route, reason) for security monitoring.",[312,313,314,321],"faq-section",{},[315,316,318],"faq-item",{"question":317},"Should middleware validate the full session or just check existence?",[13,319,320],{},"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.",[315,322,324],{"question":323},"Where should I check permissions - middleware or handler?",[13,325,326],{},"Basic auth in middleware, specific permissions in handler. Middleware handles \"is user logged in?\" Handler handles \"can this user access this specific resource?\"",[17,328,330],{"id":329},"further-reading","Further Reading",[13,332,333],{},"Want to understand the vulnerability before fixing it? These guides explain what's happening and why.",[62,335,336,343,349],{},[43,337,338],{},[339,340,342],"a",{"href":341},"/blog/vulnerabilities/exposed-api-keys","Understanding exposed API keys",[43,344,345],{},[339,346,348],{"href":347},"/blog/how-to/hide-api-keys","How to hide API keys step-by-step",[43,350,351],{},[339,352,354],{"href":353},"/blog/best-practices/secrets","Secret management best practices",[356,357,358,364],"related-articles",{},[359,360],"related-card",{"description":361,"href":362,"title":363},"Find unprotected routes","/blog/prompts/fix-auth-bypass","Fix Auth Bypass",[359,365],{"description":366,"href":367,"title":368},"Role-based access","/blog/prompts/protect-admin-routes","Protect Admin Routes",[370,371,374,378],"cta-box",{"href":372,"label":373},"/","Start Free Scan",[17,375,377],{"id":376},"find-unprotected-routes","Find Unprotected Routes",[13,379,380],{},"Scan your app for routes missing authentication.",{"title":382,"searchDepth":383,"depth":383,"links":384},"",2,[385,386,387,388,389,390],{"id":19,"depth":383,"text":20},{"id":110,"depth":383,"text":111},{"id":199,"depth":383,"text":200},{"id":262,"depth":383,"text":263},{"id":329,"depth":383,"text":330},{"id":376,"depth":383,"text":377},"prompts","2026-02-11","2026-03-06","AI prompts to add authentication middleware. Protect your API routes, server actions, and pages with reusable auth checks.",false,"md",null,"cyan",{},true,"AI prompts to implement reusable authentication middleware.","/blog/prompts/add-auth-middleware","[object Object]","BlogPosting",{"title":5,"description":394},{"loc":402},"blog/prompts/add-auth-middleware",[409],"Authentication","summary_large_image","YkrWM8jP5Zq-iA462kR7EmcFGY-RdvH_-AeiuHSYbms",1775843939093]