nextjs api-routes ai_generated true

Error: write after end in API route

ID: nextjs/err-next-api-write-after-end

Also available as: JSON · Markdown
95%Fix Rate
96%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
14 active

Root Cause

API route sends response twice — usually a missing return after res.json().

generic

Workarounds

  1. 96% success Add return after res.json()/res.send(): return res.json({ ok: true })
    return prevents execution of code below that would send another response
  2. 90% success Use response.json() instead of manual write in App Router
    // App Router (app/api/route.ts):
    export async function POST(request: Request) {
      const body = await request.json();
      return Response.json({ success: true, data: body });
    }
    // Avoid res.write() / res.end() — use the Response API instead

    Sources: https://nextjs.org/docs/app/building-your-application/routing/route-handlers

  3. 88% success Ensure the response body is not written to after the response has ended
    // Pages Router — add return after each response:
    export default function handler(req, res) {
      if (!req.body.name) {
        return res.status(400).json({ error: 'Name required' });
        // return prevents further writes
      }
      return res.status(200).json({ ok: true });
    }

    Sources: https://nextjs.org/docs/pages/building-your-application/routing/api-routes

Dead Ends

Common approaches that don't work:

  1. Adding res.headersSent check before every response 60% fail

    Band-aid; masks the control flow bug

  2. Wrapping everything in try/catch 75% fail

    The second write is intentional code, not an exception

Error Chain

Frequently confused with: