{"success":true,"name":"keep-next-js-middleware-thin-and-edge-safe","description":"Adding logic to middleware.ts in a Next.js project","category":"ai-brimind","path":"ai-brimind/keep-next-js-middleware-thin-and-edge-safe/SKILL.md","file":"SKILL.md","content":"---\nname: keep-next-js-middleware-thin-and-edge-safe\ndescription: \"Adding logic to middleware.ts in a Next.js project\"\n---\n\n# Keep Next.js Middleware Thin and Edge-Safe\n\n## When to use\nProject is Next.js, and you are about to put auth logic, database calls, or heavy code into middleware.ts.\n\n## Example request\nquerying the database in middleware to load the user → middleware runs on every matching request in a limited runtime; it should check a cookie and pass, not open DB connections. — Thin gate, not a backend. | middleware running on images, fonts, and _next assets → the matcher config was never set; scope it to the paths that need it. — Unscoped matcher taxes everything. | importing a Node-only library (fs, some ORMs) in middleware → the Edge runtime does not have Node APIs; it breaks or forces workarounds. — Edge runtime limits. | rewriting locale or redirecting logged-out users by reading a cookie → exactly the cheap, per-request routing decision middleware is for. — Right-sized middleware job.\n\n## Instructions\nAct like a gatekeeper who knows the gate must stay light because everyone passes through it. When touching middleware.ts in Next.js: 1) State what middleware is for: cheap, per-request routing decisions — redirects, rewrites, locale detection, reading a cookie to bounce logged-out users. It runs on the Edge runtime for every matched request, so anything heavy multiplies across all traffic. 2) Check the runtime constraints before importing: no Node core modules (fs, net), and many database drivers and ORMs will not run there. If the logic needs the database or heavy computation, it belongs in the Server Component, Server Action, or route handler — not the gate. 3) Always define the matcher config so middleware runs only where needed, excluding static assets, images, and _next internals; unscoped middleware silently taxes every asset request. 4) Never treat middleware as the ONLY auth layer: it filters early, but pages and handlers must re-verify the session themselves. 5) If you are unsure whether a library is Edge-compatible, check its docs or test in isolation instead of debugging cryptic build errors later. Only add logic to middleware once it passes the test 'cheap, per-request, routing-related', and explain why it must run at the gate rather than in the route — not just that it works in dev.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #502\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}