CORS and micro-services with now.sh

On March 7th 2017 the folks at zeit introduced a new way to compose and coordinate micro-services. In this post I will show you how you can use that to get rid of the CORS header configuration, by using the new aliasing feature. This is made possible because deployments can be configured to be accessible under the same domain.

What is our setup?

  • a rest api - comp-test-api.now.sh github
  • a frontend - comp-test-frontend.now.sh github

What should the result be?

  • the rest api reachable on - comp-test.now.sh/api
  • the frontend reachable on - comp-test.now.sh

When accessing our api it simply returns a list of strings.

curl https://comp-test-api.now.sh/
=> Response ["cat","dog","deer"]

When we open the webapp at https://comp-test-frontend.now.sh we get a CORS error. The browser prevents us from requesting data on a different domain than ours. Instead of configuring the headers now, we will use a different solution.

Cors error

What do we have to do?

  • you need an now.sh account
  • point the frontend api calls to https://comp-test.now.sh/api/
  • creating a rules.json file in which we define the paths
{
  "rules": [
    { "pathname": "/api/*", "dest": "comp-test-api.now.sh" },
    { "pathname": "/**", "dest": "comp-test-frontend.now.sh" },
    { "dest": "www.comp-test.now.sh" }
  ]
}
  • run now alias comp-test.now.sh -r rules.json

This means that we can access comp-test-api.now.sh by using comp-test.now.sh/api and comp-test-frontend.now.sh by using comp-test.now.sh

That`s it. We now have the api as well as the frontend reachable under the same domain (comp-test.now.sh), which means that the CORS configuration is not necessary. The cool thing about this is, it can be used for whatever service you want. It is not restricted to now.sh deployments.

If you want to read more about that feature go to https://zeit.co/blog/path-alias