Skip to content

[question] res.setHeader after status(code).json(body) fails with ERR_HTTP_HEADERS_SENT #62

@FranciscoKloganB

Description

@FranciscoKloganB

Describe the bug

I have recently started using your middleware package on a personal project and I quite enjoyed following through with the docs and implementing what I needed. At some point, I saw the following example.

// request-tracing.pipe.ts`
export async function requestTracingPipe(
  _req: NextApiRequest,
  res: NextApiResponse,
  next: () => Promise<void>
): Promise<void> {
  res.setHeader("X-Timing-Start", new Date().toISOString())

  await next()

  res.setHeader("X-Response-ID", nanoid())
  res.setHeader("X-Timing-End", new Date().toISOString())
}

However, when trying to setHeader after responding to the client on the API Route, I get the following error:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

I have run the debugger multiple times and res is only called once. Also, if I disable request-tracing.pipe.ts the error stops occurring.

Here is a snippet of the code that runs before the middleware.

async function getHandler(req: NextApiRequest, res: NextApiResponse) {
  const { search } = req.query

  // res.status(200).json(data) executes and the next middleware to execute is `request-tracing.pipe.ts`
  if (search) {
    const data = await forwardGeocode(search as string)
    res.status(200).json(data) 👈
  } else {
    throw new AppError(400, `Query string must define "search" key value pair.`)
  }
}

async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === "GET") {
    await getHandler(req, res)
  }
}

export default withMiddleware()(METHODS_GUARD)(handler)

Question

Has this happened before? Are there any Next API changes we are not aware of?

Expected behavior

After performing res.status(code).json(body) I expected the res to still pass through request-tracing.pipe.ts before being returned to the client, so that, timing headers can be set. However, this might not be a bug related to next-api-middleware.

Desktop (please complete the following information):

  • OS: Ubuntu
  • Version: 20.04
  • Next 12.2.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions