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. As part of it, we developed an API which is deployed and running here.

  • 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 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 which doesn't support CORS request. 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,

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 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:

devServer: {
    contentBase: path.join(__dirname, "dist"),
    compress: true,
    port: 8080,
    proxy: {
        '/api': {
            target: 'http://localhost:1337',
            secure: false
        }
    }
  }

and modify the code as,

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

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:

    /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.

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

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

    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:

    "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 Like/Share the post if you found it useful, Cheers 🍻🍻🍻!

Comments (2)

Maneesh Kumar's photo

Great Article ...

Ariana's photo

Mobile App Developer

Thanks, Tapas Adhikary for sharing niche information