- What is CORS?
- CORS Examples
- Working with CORS and DataHub
What is CORS?
Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any other origins (domain, scheme, or port) than its own from which a browser should permit loading of resources. CORS also relies on a mechanism by which browsers make a “preflight” request to the server hosting the cross-origin resource, in order to check that the server will permit the actual request. In that preflight, the browser sends headers that indicate the HTTP method and headers that will be used in the actual request.
CORS Errors are common when you’re working with APIs but it’s very important to handle them effectively due to several security reasons. Below is a CORS error example.
by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header
is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch
the resource with CORS disabled.
The CORS mechanism supports secure cross-origin requests and data transfers between browsers and servers. Modern browsers use CORS in APIs such as XMLHttpRequest or Fetch to mitigate the risks of cross-origin HTTP requests. Source - Mozilla MDN Web Docs.
Working with CORS and DataHub
There are two major ways to handle CORS errors effectively so you don’t expose your API keys and credentials on the Client-Side.
Using a Proxy
One solution for making cross-origin requests is to use a CORS proxy. There are many different CORS proxies you could use. You'll find some examples in this Gist by jimmywarting and some templates listed below.
- Cloudflare CORS header proxy
- Cloudflare CORS cors_header_proxy.js
- Cloudflare worker template by Figment
- Cloudflare worker template by Figment (supports Websockets)
- nginx proxy configuration by Figment (supports Websockets)
Using a Serverless Function
Using a serverless function is another more effective way to handle CORS errors and proxy our requests. We build our own functions or micro-infrastructure to call a web service and interact using APIs. Azure, AWS & GCP are some of the more popular platforms for building and running serverless functions. Below are some examples of serverless functions built and shared by our Figment Developers & Figment Community Members 🙌
- Azure Function for CORS proxy by Florian Uhd. GitHub Gist - azure-request.js.
- AWS Lambda Function for CORS proxy by Austin Woetzel. GitHub Gist - aws-proxy.js.
- Standalone nginx template for proxying DataHub requests with CORS headers by Figment. GitHub Gist - datahub-cors-dev-proxy.