Instruction file imported from JuanPablo876/CondoControl (
.github/instructions/middleware.instructions.md). Copyright stays with the author.
Middleware (Next.js)
Runtime
- Next.js middleware runs on the Edge Runtime by default
- No Node.js APIs: no
fs, noBuffer, nochild_process, no Prisma - Only import from
next/serverand edge-compatible packages crypto.subtleis available,crypto(Node) is not
Matcher
- Use
config.matcherwith negative lookahead to exclude static assets:
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico|icons|sw.js|manifest.json).*)'],
};
Behavior
- Keep middleware lightweight — it runs on every matched request
- Return
NextResponse.next(),.redirect(), or.rewrite()— never throw - Use
Setfor O(1) path lookups, not arrays - Auth checks belong in route handlers, not middleware (unless explicitly setting up middleware-level auth)
- Do not fetch from the database in middleware — defer to API routes or server components
Common Patterns
- Reserved paths: Use a
Setof known static paths to prevent dynamic catch-all routes from swallowing them - Redirects: Prefer
next.config.jsredirects over middleware for static redirects - Headers: Set security headers (CSP, HSTS) in middleware if not handled by
next.config.js