DEV Community

Deep Fix
Deep Fix

Posted on

Fix CORS Errors in Node.js Fast: Step‑by‑Step Guide for Developers

Introduction

Cross‑Origin Resource Sharing (CORS) errors are a common hurdle when building APIs with Node.js. This guide walks you through diagnosing and fixing CORS issues quickly so your frontend can talk to your backend without headaches.


Why CORS Fails

  • The browser blocks requests that don't include the correct Access-Control-Allow-Origin header.
  • Mis‑configured middleware, missing headers, or wrong HTTP methods can trigger the error.

Step‑by‑Step Fix

1. Install and Use cors Middleware

npm install cors --save
Enter fullscreen mode Exit fullscreen mode
// app.js
const express = require('express');
const cors = require('cors');
const app = express();

// Basic configuration – allow all origins (use with caution in production)
app.use(cors());

app.get('/api/data', (req, res) => {
  res.json({ message: 'CORS works!' });
});

app.listen(3000, () => console.log('Server running on http://localhost:3000'));
Enter fullscreen mode Exit fullscreen mode

2. Fine‑Tune the Options

const corsOptions = {
  origin: ['https://example.com', 'https://app.example.com'], // whitelist
  methods: ['GET','POST','PUT','DELETE'],
  credentials: true, // enable cookies
  allowedHeaders: ['Content-Type', 'Authorization']
};

app.use(cors(corsOptions));
Enter fullscreen mode Exit fullscreen mode

3. Handle Pre‑flight Requests

app.options('*', cors(corsOptions)); // enable pre‑flight for all routes
Enter fullscreen mode Exit fullscreen mode

4. Verify with Curl or Browser DevTools

curl -i -X OPTIONS http://localhost:3000/api/data -H "Origin: https://example.com" -H "Access-Control-Request-Method: GET"
Enter fullscreen mode Exit fullscreen mode

You should see Access-Control-Allow-Origin and other CORS headers in the response.


Common Pitfalls

Symptom Likely Cause Fix
No 'Access-Control-Allow-Origin' header Middleware not added before routes Move app.use(cors()) to the top
CORS preflight response 404 Missing app.options handler Add app.options('*', cors())
Credentials blocked Access-Control-Allow-Origin is * Specify explicit origin and set credentials: true

Debugging Checklist

  1. Middleware order – ensure cors() runs before your routes.
  2. Origin matching – use exact strings or regex; wildcards are not allowed when credentials are true.
  3. Headers list – include any custom headers you send (X‑My‑Header).
  4. Server logs – print req.headers.origin to confirm what the browser sends.

Automate the Fix

If you need to apply the same configuration across multiple services, download a ready‑made script:

These resources bundle the CORS setup and can be integrated into CI pipelines.


Conclusion

Fixing CORS in a Node.js application is usually a matter of adding the right middleware, configuring it for your environment, and testing the pre‑flight flow. Follow the checklist above, and you’ll eliminate those frustrating browser errors in minutes.

Happy coding!

Top comments (0)