# Netlify Quick Tip: How to Redirect to an API that doesn’t support CORS request

In my last post, I explained [How to deploy your Sailsjs app on Heroku](https://blog.greenroots.info/how-to-deploy-your-sailsjs-app-on-heroku-and-live-longer-cjzv8igb2001m6vs1qhg5pdnt). As part of it, we developed an API which is  [deployed and running here](https://frozen-shore-18427.herokuapp.com/api/users). 
- How about creating a single page app(using whatever technologies you feel like) and use this API for a purpose? 
- How about we setup a workflow using  [Netlify](https://www.netlify.com/)  to automate build, deploy and publish of this single page web app? 

Well, we have a small problem here! The API is hosted on  [Heroku](https://www.heroku.com/) which doesn't support  [CORS request](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). In plain english, you will not be able to access the API hosted on Heroku from the Single-Page-Web-App hosted on Netlify.

# Problems
Let us assume, the single page app has a way to make an API call as,

```javascript
const [data, loading] = useFetch(
        "https://frozen-shore-18427.herokuapp.com/api/users"
 );
```
I am using React Hook here but, it can be in any other ways as well. You simply can not do that because of the CORS restrictions. You will get an error like below,

![CROS.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1567587982565/vZcCQPmAn.png)
*Error in both development and production(published on Netlify)*

### Let us fix the Development Mode first
If you are using webpack, you can have a configuration like:
```javascript
devServer: {
    contentBase: path.join(__dirname, "dist"),
    compress: true,
    port: 8080,
    proxy: {
        '/api': {
            target: 'http://localhost:1337',
            secure: false
        }
    }
  }
```
and modify the code as,
```javascript
const [data, loading] = useFetch(
        "/api/users"
 );
```
With this, we will be able to access the web app on `localhost:8080` which will proxy all the calls starts with `/api` to local sails service running on `localhost:1337`. All good here!

# How about on Netlify? Redirect to Rescue!
If we deploy and push the above code on Netlify, it will not run correctly. We will get error with code 404 like below,

![404Error.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1567588429325/mXn1jCLQN.png)

We just need to do some basic configuration. Here are the steps:
- Create a file called `_redirects` at the root of our project.
- Have following content in that file:
 ```bash
  /api/*  https://frozen-shore-18427.herokuapp.com/api/:splat  200
 ```
 All we are doing here is to redirect all our calls starts with `/api` to a hosted url(in this case it is on Heroku). Cool, isn't it? 

 Now all requests to /api/… will be proxied through to `https://awesome-rest-green-roots.herokuapp.com/api/` straight from Netlify's CDN servers without an additional connection from the browser. Read more about Redirects  [here](https://www.netlify.com/docs/redirects/).

# Bonus: Bundling _redirects file
Here is a bonus section to explain how to bundle the `_redirects` file so that, Netlify can recognize it correctly. This problem can be solved in several different ways. Here is how I have tackled it:

My Netlify project configuration goes like,

![netlify_settings.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1567588952756/SxgavV5FR.png)

Also I have not pushed the build output folder `dist` to git repository. To make sure, the `_redirects` file is available to Netlify, I have done following changes:

- A simple code(`copy-to-dist.js`) to copy the `_redirects` file inside dist folder

 ```javascript
 const fs = require('fs');

 // _redirects will be created or overwritten by default.
 fs.copyFile('_redirects', './dist/_redirects', (err) => {
   if (err) throw err;
   console.log('_redirects was copied to dist folder!');
 });
 ```
- In `package.json` changed the `prod` script as:

 ```javascript
  "prod": "npm run build && node ./config/copy-to-dist.js",
 ```
Whenever I trigger a build on Netlify for this project, it will run `npm run prod` command as per the configuration setting mentioned above. This will result into a `dist` folder with `_redirects` which will serve the redirect purpose for us.

# See it in action and Code
- Please find the code here:  [Git Hub Repo](https://github.com/atapas/test-sngle-page-netlify) 
- The working code is  [Running here on Netlify](https://netlify-redirect-green-roots.netlify.com/)

 ![success.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1567590263271/y8xHIXdiA.png)

Please Like/Share the post if you found it useful, Cheers 🍻🍻🍻!
