NextResponse throws error when http request status code is 204

Hi there,

I am having trouble when returning 204 http status code from Next.js (latest today) from a api route (METHOD: DELETE)

To Reproduce

  1. Inside API route do a DELETE handler
  2. Return status (HTTP Status Code) 204

export async function DELETE(request: NextRequest, { params }: ResponseUtils['PARAMS']) {
  const service = serviceImpl();
  const { id } = params;

  try {
    IdSchema.parse({ id });
  } catch (error) {
    return defaultServerErrorHandler(error);
  }

  try {
    // The request is completed successfully, and the response is a 204 No Content status code.
    const {  status } = await service.delete.byId(id);
    // The response body is empty and the status code is 204.
    // But when trying to return the response, it throws the following error:
    // {"message":"Response constructor: Invalid response status code 204"}

    // I tried all the following options, but none of them worked:
    return NextResponse.json({}, { status });
    // return NextResponse.json(null, { status });
    // return NextResponse.json('', { status });
    // return NextResponse.json(undefined, { status }); // This is actually invalid (Value is not JSON serializable)
  } catch (error) {
    return defaultServerErrorHandler(error);
  }
}


Do you know some workaround about this issue or it is just me?

Hey @lucarampi. This sounds like this issue where people were running into the same error because the response body was not actually empty: Static GET App route throws TypeError when returning cached 204 · Issue #49005 · vercel/next.js · GitHub

Try something like NextResponse(null, { status }); instead of NextResponse.json({}, { status }) and let us know whether or not that solves it for you.

You can find more info about the error here: Invalid API Route Status/Body Response | Next.js

Hey, thanks for the links, but I’ve already looked into them.

Regarding the other approaches you mentioned, if you take a closer look at the comments inside the code posted above, you’ll see all the options I’ve already tried.

Thanks for your time, and I hope we can figure this out!

I missed the list of things you tried. Thanks for including that!

Can you try return new Response( null, { status: 204 } ) instead of NextResponse as suggested here: Static GET App route throws TypeError when returning cached 204 · Issue #49005 · vercel/next.js · GitHub

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.