Fixing CORS Errors — How to Build a Proxy Server to Handle Cross-Origin Requests
Problem — CORS Errors
As you begin building and working with APIs, chances are you’ll come across the following error:
For security reasons, browsers will only permit scripts from one source to access data from another source if the two sources share the same origin. Cross-Origin Resource Sharing (CORS) can allow for cross domain requests, but only if the requested source specifically allows requests from the initial sender. In the above error, we’re attempting to request information from http://some-url.com/path
, but requests from http://another-url.com/path
have not been explicitly allowed by the destination. When we do this, the browser prevents the request from being made and throws an error. What we need to do is configure the requested server to accept requests from our (or any) source. But what if we don’t have access to that server? What if the server is closed-source? We could reach out to the owners of the API, or we could take matter into our own hands.
It’s important to understand that the reason checkpoint that throws this error stems not from the requested server but from the browser itself, stopping this request in its tracks so as to prevent any unexpected transfer of potentially sensitive information. The Same Origin Policy does not, however, apply between servers. Knowing this, we can spin up our own server, send a request your our personal server then from there, make a request to the API in question.
In visual terms, instead of this:
… we’ll have something like this:
Solution — Building a Proxy Server
Let’s build a proxy server, a personal server that will accept requests from our application, make requests to the API on our behalf, then return data back to our application. If your application is currently operating purely on the frontend, have no fear, this is a pretty painless backend process.
Note: We’re building and deploying this server to handle CORS errors, but most APIs will direct you to build and deploy a server of your own even if cross origin requests are allowed. The reason for this is that most APIs require access keys that are not meant to be visible to the public, and it’s impossible to fully conceal these keys if they’re located in your frontend code. Storing these keys as environment variables only to be used on a backend server will keep them hidden from public access.
Initialize Project
npm init -y // create a new node environment with defaults
Install Dependencies
We’ll be using express and request. Request has been deprecated, but is still functional at the time of writing. In case this changes, find alternatives here.
npm install --save express request
Build the Server
Use the following code to build a server, replacing the request URL with the address of the API you’d like to request. Make sure to change the port if needed in order to prevent collisions with the development server of your frontend.
When a request is made to this server, express will add the necessary header to let the browser know that cross origin requests are to be permitted. The server will then run send a GET request to the server containing the desired data, parse the data, and return it as one JSON blob.
Deploy Server
There are a plethora of options for this step. I’m personally a fan of Heroku for cost and ease of use. The linked directions provide instruction how to use command line inputs to deploy your app, but it’s also fairly straightforward to create an account, head to your dashboard
, link your GitHub account, hit New
, Create new app
, then follow instructions to point Heroku towards an existing GitHub repository.
Use the Server
Last step is to point your front end to your new proxy server. Wherever you’re making the request from in the frontend will need to be redirected towards the new URL where your server is hosted.
Now this:
getData() {
return fetch(`http://some-url.com/path`)
.then((res) => return res.json())
}
Becomes this:
getData() {
return fetch(`https://your-proxy-name.herokuapp.com/api`)
.then((res) => return res.json())
}
That’s all!
Conclusion
Working around CORS errors can be tricky, especially if the requested resource is not our own or if the resource is deprecated. Luckily, building and deploying our own proxy server can be done in a short amount of time!