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

In case of a request for:

it gets redirected to:

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

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


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

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

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

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