CORS and Prototyping with live APIs
Over the last number of weeks I have been working with: Create React App
, Razzle
, After.js
and Next.js
to evaluate them for future projects. (More on this in a future post.) While doing this I wanted to use production APIs that I was familiar with so that I could focus only on the framework.
But there was one problem, APIs in all environments were missing one thing!
Access-Control-Allow-Origin: *
And with that you get:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:3000' is therefore not allowed access.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled
Solution
Now there are many ways around this and I was looking for something super simple. I wanted something that I could share with the team and include as part of the prototype codebase. I found a couple of packages that offered parts of what I wanted. Some were full featured and ready for production! Others difficult to set up and unclear if they would work. In the end I created my own package (local-cors-proxy
) that met my exact use case.
local-cors-proxy
The goal was simple, allow any API to be called without CORS issues and needing anything changed on the backend. This package does that by creating a simple proxy to bypass CORS issues. It is a dev only solution to help you rapidly prototype out your React / Vue / Angular (+ many many more) apps.
Getting started is easy, you can install the package globally or on a project by project basis.
Here is a simple example:
npm install -g local-cors-proxy
Take this as the example API endpoint that we are requesting that has CORS issues:
https://www.yourdomain.ie/movies/list
First we start the proxy:
lcp --proxyUrl https://www.yourdomain.ie
Then we can make a request to the proxy:
Then in your client code, the new API endpoint would look like:
http://localhost:8010/proxy/movies/list
End result will be a request to https://www.yourdomain.ie/movies/list
without the CORS issues!
Alternatively you can install the package locally and add a script to your project:
"scripts": {
"proxy": "lcp --proxyUrl https://www.yourdomain.ie"
}
And run it then via the command yarn proxy
Icon: block by Alina Oleynik from the Noun Project