How to Use CORS in REST API: Simple Guide
To use
CORS in a REST API, you enable it on the server to allow requests from different origins by setting appropriate HTTP headers like Access-Control-Allow-Origin. This can be done manually or by using middleware libraries that handle CORS automatically.Syntax
To enable CORS, the server must send specific HTTP headers in its response. The most important header is Access-Control-Allow-Origin, which tells the browser which origins are allowed to access the resource.
Access-Control-Allow-Origin: Specifies allowed domains (e.g.,*for all or a specific URL).Access-Control-Allow-Methods: Lists allowed HTTP methods (GET, POST, etc.).Access-Control-Allow-Headers: Lists allowed custom headers.Access-Control-Allow-Credentials: Indicates if cookies or credentials are allowed.
These headers can be set manually or by using middleware in your REST API framework.
http
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: trueExample
This example shows how to enable CORS in a simple Node.js REST API using the cors middleware package. It allows all origins to access the API.
javascript
import express from 'express'; import cors from 'cors'; const app = express(); // Enable CORS for all origins app.use(cors()); app.get('/data', (req, res) => { res.json({ message: 'CORS is enabled!' }); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Output
Server running on http://localhost:3000
Common Pitfalls
Common mistakes when using CORS include:
- Setting
Access-Control-Allow-Originto*but also trying to send credentials (cookies), which is not allowed. - Not handling preflight OPTIONS requests, which browsers send before some requests.
- Forgetting to allow required HTTP methods or headers, causing requests to fail.
- Setting CORS headers only on some routes but not all.
Always test your API with browsers to ensure CORS works as expected.
javascript
/* Wrong: Using wildcard with credentials */ res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Credentials', 'true'); /* Right: Specify exact origin when using credentials */ res.setHeader('Access-Control-Allow-Origin', 'https://example.com'); res.setHeader('Access-Control-Allow-Credentials', 'true');
Quick Reference
Remember these key points when using CORS in REST APIs:
- Allow specific origins instead of
*when credentials are involved. - Handle OPTIONS preflight requests properly.
- Use middleware in your framework to simplify CORS setup.
- Test with browsers to verify CORS behavior.
Key Takeaways
Enable CORS by setting appropriate HTTP headers on your REST API server.
Use middleware libraries to simplify CORS configuration and avoid errors.
Avoid using wildcard origins with credentials; specify exact allowed origins instead.
Handle OPTIONS preflight requests to support complex browser requests.
Test your API in browsers to ensure CORS works as intended.