nestjs / docs.nestjs.com

The official documentation https://docs.nestjs.com 📕
MIT License
1.2k stars 1.74k forks source link

Serverless Redirects Docs #2298

Open SawyerHopkins opened 2 years ago

SawyerHopkins commented 2 years ago

Is there an existing issue that is already proposing this?

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.

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.

kamilmysliwiec commented 2 years ago

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!