DEV Community

Deep Fix
Deep Fix

Posted on

Fix CORS Errors in Node.js Fastify – Complete Guide for Developers

Fix CORS Errors in Node.js Fastify – Complete Guide for Developers

Cross‑Origin Resource Sharing (CORS) errors are a common hurdle when building APIs with Node.js and Fastify. This post walks you through why they happen and how to resolve them step‑by‑step.


1. What Triggers a CORS Error?

When a browser requests a resource from a different origin (scheme, host, or port) than the page it originated from, the server must explicitly allow that request via response headers. If the required Access‑control‑Allow‑Origin header is missing or mismatched, the browser blocks the call and logs a CORS error.

2. Install the Fastify CORS Plugin

npm install fastify-cors
Enter fullscreen mode Exit fullscreen mode

3. Basic Configuration

const fastify = require('fastify')();

fastify.register(require('fastify-cors'), {
  // Allow specific origins or use * for all (not recommended for production)
  origin: ['http://localhost:3000', 'https://my‑frontend.com'],
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  credentials: true
});

fastify.get('/api/data', async (request, reply) => {
  return { message: 'CORS is now configured!' };
});

fastify.listen({ port: 4000 }, err => {
  if (err) throw err;
  console.log('Server listening on http://localhost:4000');
});
Enter fullscreen mode Exit fullscreen mode

Why This Works

  • origin tells the browser which domains are permitted.
  • credentials: true adds the Access‑control‑Allow‑Credentials header, needed for cookies or HTTP authentication.

4. Common Pitfalls

Symptom Likely Cause Fix
No 'Access-Control-Allow-Origin' header Origin not listed or using * with credentials Add the exact origin to the origin array or compute it dynamically.
Pre‑flight OPTIONS request fails Missing methods or allowedHeaders Include methods and, if needed, allowedHeaders in the plugin options.
CORS works locally but not in production Different domain or missing HTTPS Mirror the production domain in the origin list and ensure HTTPS is used.

5. Advanced: Dynamic Origin Handling

fastify.register(require('fastify-cors'), {
  origin: (origin, cb) => {
    const whitelist = ['http://localhost:3000', 'https://my‑frontend.com'];
    if (whitelist.includes(origin) || !origin) {
      cb(null, true);
    } else {
      cb(new Error('Not allowed by CORS'));
    }
  }
});
Enter fullscreen mode Exit fullscreen mode

This function checks the incoming request origin against a whitelist, allowing you to keep the list in a config file or environment variable.

6. Verify the Fix

Use curl or the browser dev tools:

curl -i -H "Origin: http://localhost:3000" http://localhost:4000/api/data
Enter fullscreen mode Exit fullscreen mode

You should see:

HTTP/1.1 200 OK
access-control-allow-origin: http://localhost:3000
access-control-allow-credentials: true
Enter fullscreen mode Exit fullscreen mode

If the headers appear, the CORS issue is resolved.


Quick Resources

Feel free to drop a comment if you hit any edge cases, and happy coding!

Top comments (0)