Search code examples
nestjs

NESTJS - Using HEAD Http Request Type and GET for the Same Route


Per Design, in our RESTful api's, we use HEAD to check for the existence of an entity. I recently came across an issue with using NestJS and using the Http Request Type of HEAD and GET with the Same Route. For some reason when the client makes an http HEAD request to the API for say HEAD - /api/test, it would route to the GET portion controller of the code. After some troubleshooting, it appears to be related to the position of the method in the controller. If you place the HEAD portion of the controller code after the GET, the request will intercept to the GET request. If you place it after, it will work as expected. Not sure why but it is good to know

Code snippet:

// HEAD must be before GET for NestJS controller with the same route
@Head(':id')  // check for the existence of an entity
  async hasOne(@Res() response, @Param('id') id): Promise<any> {

   // do something
  }

  @Get(':id') // Get a single entity
  getOne(@Param('id') id): Promise<any> {

   // do something
  }

We are using NestJS 10.4.4


Solution

  • This is an Express issue, introduced in version 4.* and never fixed as it "break things". https://github.com/expressjs/express/issues/2116

    Express uses the rule "first come, first served" when defining API routes, so your code does exactly what you observed: the get route handles the head request (https://github.com/expressjs/expressjs.com/issues/748) unless a specific head route is defined before the get one.