Accessing Remote Services Locally and with Netlify

Accessing Remote Services Locally and with Netlify

Avoiding CORS issues in a local development environment

On localhost, this is as simple as utilizing the proxy feature of the Webpack DevServer. See the documentation for details and example configurations.

Using Netlify’s proxy

With Netlify, proxying is part of their redirecting support. It lets you access remote services as if they were part of your app, i.e. without referring to any remote host in the requested URLs.

There are two major benefits to proxying: It doesn’t require CORS to be set up because the URLs are internal. Also, the responses are cached by Netlify’s CDN servers if they include the corresponding headers.

Redirects can be provided as rewrite rules you can include in a file named _redirects. In the Scrivito Example App, this file is located at /public/_redirects.

As an example, a rewrite rule for making remote API calls could look like this:

This causes all requests to /giphy/* to be directed to the specified location, with :splat being replaced by what the * wildcard has picked up. So, a virtually internal request such as

/giphy/v1/gifs/random?tag=cat&api_key=your_api_key

is actually turned into:

http://api.giphy.com/v1/gifs/random?tag=cat&api_key=your_api_key

Just keep in mind that proxying only works for websites that are served via Netlify. Thus, the proxied URLs won’t be accessible during local development.