Deployment of React App over Netlify

Netlify provides an easy CI/CD capability where you can directly hook up your github repo and on new push to your deployment branch – it builds, tests and deploys.

It has even got a nice blog here which illustrates how you can go about deploying it on Netlify. It even tells you how you can setup re-route, in case you are using react-router or something similar. Typically, in such case you would like to point back to index.html upon any redirects. Well, it’s easy-peezy.

But, HERE’S A CATCH, if you are making an API call that are not netlify functions then you may get this CORS error.

cors_error_netlify

I am assuming you have handled CORS at backend already (this is how it’s done in Nest.js), and still you are getting this error – because it’s an issue from Netlify’s end.

Problem Analysis

Understanding that you have applied the redirection rules following the blog mentioned above. It might be looking like this:

/*    /index.html   200

What it conveys is that – no matter what the request is – redirect it back to index.html. And it was doing same for API calls as well, for which the application was hosted on AWS EC2.

Thus, clearly we need a new redirection rule. We settled for this eventually:

_redirects

Now, the first rule will be transferring the endpoint requests beginning with “/api/” to API application on AWS. (Notice splat in end? Read more about it here)
And for rest of the paths, which don’t begin with “api”, will be redirected to “index.html”.

One more step needs to be completed on backend. We need to append “api” to all our API’s controller path in backend. In Nets.js it can be done by adding a global prefix (refer this).

Also, we will need a header rule to enable CORS header request generating from Netlify. My _header file looks as follows for now:

_headers

With this you should be ready for deployment on netlify.

To read more about _headers and _redirects follow their links. Conventions of these files can be a bit quirky sometimes. Netlify has provided a utility to cross-check the configs of both.

(Note: Remember to put the _headers and _redirects file in the public folder, near index.html)

Lastly, the api url changes that we have made to our react-app may hinder with local development. Here’s a little workaround for same using “environment variables” which comes already integrated with create-react-app.