By Mario Liggiu


2018-03-28 10:08:20 8 Comments

I have setup an express application with various routes like:

  • /api/route1
  • /api/route2
  • /api/newroute

I need to redirect a request for route /api/route2 to /api/newroute. Thus I use res.redirect(); to achieve this. It works fine on my local development environment, where the application is hosted on http://localhost/api. A request for http://localhost/api/route2 gets successfully redirected to http://localhost/api/newroute.

We have now deployed the express application in a serverless/lambda container using aws-serverless-express. The application is hosted by AWS on https://xxx.execute-api.us-east-1.amazonaws.com/production/api.

In case of a request for:

https://xxx.execute-api.us-east-1.amazonaws.com/production/api/route2

it gets redirected to:

https://xxx.execute-api.us-east-1.amazonaws.com/api/newroute.

The redirect fails as the correct endpoint should be now /production/api/newroute.

I would like to avoid to hardcode the infix “/production” in res.redirect(); as the it will vary due to environment.

Thus I have checked whether

  • req.originalUrl
  • req.baseUrl
  • req.path

will provide the infix “/production”, however this is not the case.

Also req.get('Host') does not provide “/production” as it returns https://xxx.execute-api.us-east-1.amazonaws.com.

Are there any other options how I could get the full URL where the application is hosted? Or are there any better ideas?

1 comments

@James 2018-10-11 14:19:52

I ran into this same issue. Here's my solution:

const baseUrl = req.url
      .replace(
        event.pathParameters.proxy, // => returns api/your/path
        event.requestContext.path // => returns /production//api/your/path
      )
      .split('//') // fix the double-slashes (//)
      .join('/');

Related Questions

Sponsored Content

1 Answered Questions

3 Answered Questions

[SOLVED] Is AWS Lambda good for real-time API Rest?

1 Answered Questions

0 Answered Questions

Serverless CORS configuration not working

1 Answered Questions

2 Answered Questions

1 Answered Questions

[SOLVED] Get AWS API gateway host name in another independent lambda

1 Answered Questions

[SOLVED] CORS issue with Serverless and PUT command

1 Answered Questions

Sponsored Content