docs.nestjs.com icon indicating copy to clipboard operation
docs.nestjs.com copied to clipboard

Serverless Redirects Docs

Open SawyerHopkins opened this issue 3 years ago • 1 comments

Is there an existing issue that is already proposing this?

  • [X] I have searched the existing issues

Is your feature request related to a problem? Please describe it

This is a follow-up to nestjs/swagger#199 and nestjs/swagger#437. These describe an issue in which even though the request url maybe /${mySwaggerUrl}/, a redirect in with an identical location header (/${mySwaggerUrl}/) is sent as the response. This triggers a redirect loop until the browser gives up.

The accepted solution from nestjs/swagger#199 involves a patch for an issue where API gateway is stripping trailing slashes. This appears to no longer be true. This can be confirmed by logging the event to cloudwatch an verifying the trailing slash exists.

Describe the solution you'd like

With some trial and error I was able to determine the issue is with the express request object (have not done any testing with fastify), in which the originalUrl property is missing the trailing slash. The simple solution appears to be adding a middleware before calling setup from SwaggerModule.

  app.use((req: Request, _: any, next: any) => {
    if (req.originalUrl === '/swagger') {
      req.originalUrl = '/swagger/'
    }
    next()
  })

I didn't dig too deep to figure out why this occurs in express, but a couple solutions could be provided to the community.

  • If this the new accepted solution, and is an issue that should be supported directly, the middleware could be added to setupExpress, perhaps behind an option flag.

  • If this isn't desired, adding some documentation around this issue to https://docs.nestjs.com/faq/serverless would be helpful.

Teachability, documentation, adoption, migration strategy

Setup follows the current https://docs.nestjs.com/faq/serverless

Relevant packages

{
    "@nestjs/common": "8.0.5",
    "@nestjs/core": "8.0.5",
    "@nestjs/platform-express": "8.0.5",
    "@nestjs/swagger": "5.2.0",
    "@nestjs/typeorm": "8.0.1",
    "@vendia/serverless-express": "4.3.9",
    "swagger-ui-express":"4.3.0"
}

What is the motivation / use case for changing the behavior?

This took a non-negligible amount of time to debug and I hope sharing saves some other people some headache. If either of the proposed solutions seem reasonable I am happy to open a PR.

SawyerHopkins avatar Feb 26 '22 00:02 SawyerHopkins

Let's start with adding some documentation around this issue to the official docs and then we can investigate if adding such middleware won't introduce any breaking changes. If you can create a PR that would be great!

kamilmysliwiec avatar Feb 28 '22 09:02 kamilmysliwiec