Why
- To keep the website secure.
- Adding CORS is super important if you plan to make your API publicly accessible.
- You don't need it if your front-end and back-end are going to have the same domain.
- CORS is now used by all major browsers.
- Allows a client-side application from another domain to consume the API we are building.
- CORS support is required in order to be useful to modern web applications, but you still see this problem around on older APIs from time to time.
What
- CORS stands for Cross Origin Resource Sharing.
- It is an important factor in making and handling API requests.
- States that a browser can only make requests to an API if they share the same URL domain or if allowed by response headers.
- If they don't share a domain, the client-side domain must be white-listed by CORS in the API in order to have access.
How Do You Know the API Doesn't Support CORS?
- If you are making a normal fetch request to an endpoint the API says it supplies, but are getting an HTTP error similar to:
Reason: Did not find method in CORS header 'Access-Control-Allow-Methods' - Read the documentation of the API.
- Another quick trick is to open Postman or curl and try the exact same request there. Postman/curl are not browsers and do not enforce browser CORS policies, so if your request works from Postman but fails in the browser, your issue is definitely CORS.
What If the API I Want Doesn't Support CORS?
When selecting APIs for your project, look for ones that are CORS enabled. If you must use one that isn't, the standard solution is to avoid making the request directly from the browser frontend. Instead, call a backend route on your own server (e.g. Next.js Route Handler / proxy) which makes the upstream request and forwards the result to your client.
Notes
- We can use CORS as a middleware on a route-by-route basis.