DEV Community

Cover image for Node proxy to add CORS headers to API response!
das.jishu25@gmail.com
das.jishu25@gmail.com

Posted on

Node proxy to add CORS headers to API response!

With the introduction of CORS (Cross Origin Resource Sharing) policy, frontend code won't have access to a response if correct CORS headers are not embedded in it. If you own the backend code, then it becomes easy to handle since you can just add the headers before sending the response. If it's not owned by you, then you have no way to add headers directly before the response reaches your frontend code.

Error message due to response being blocked by CORS policy

Manually inserting them using GUI can be tiresome. The easiest way to get past this is to use a proxy server.

Check out this repo: add-cors

It includes a public proxy server which can be used to fetch data by adding CORS headers so that it's not blocked by CORS policy. A better way is to create your own proxy and use it without relying on a public server. The repo contains instructions on how to go about creating a proxy and host it on Heroku.

   git clone https://github.com/das-jishu/add-cors.git
   cd add-cors/
   npm install
   heroku create cors-everywhere //cors-everywhere is an example. Use a unique name for heroku to create.
   git push heroku master
Enter fullscreen mode Exit fullscreen mode

The code is fairly simple which enables someone to write it from scratch instead of cloning the code and add more features and utility as needed.

Oldest comments (0)