Web API  

How to Fix CORS Errors in JavaScript and Node.js API Gateway

Introduction

CORS (Cross-Origin Resource Sharing) errors are one of the most common problems developers face when building websites or APIs. You may have seen messages like “Access-Control-Allow-Origin missing” or “CORS policy blocked the request.” These errors happen because your browser blocks requests that come from a different domain or port for security reasons.

The good news is that CORS errors are easy to fix—once you understand how they work. In this guide, we explain CORS in simple language, show you updated solutions for JavaScript, Node.js, and API Gateway, and provide clear examples so you can apply them immediately.

What Is a CORS Error?

CORS errors appear when a browser blocks a request made from one origin (domain, port, or protocol) to another. This prevents unauthorized websites from accessing your data without permission.

Example Scenario:

Your frontend:

http://localhost:3000

Your backend:

http://localhost:5000

Even though both are on your computer, the browser sees this as a cross-origin request and may block it unless the server allows it.

Why Do Browsers Block Cross-Origin Requests?

Browsers follow a security rule called the Same-Origin Policy, which prevents websites from accessing data from other sites.

This protects users from:

  • Unauthorized data access

  • Malicious websites stealing information

  • Unwanted scripts running without permission

To make cross-origin requests safely, the server must explicitly allow the requesting origin using CORS headers.

Common CORS Error Messages

You may see errors like:

  • "CORS policy: No 'Access-Control-Allow-Origin' header present"

  • "CORS policy: Preflight request failed"

  • "Blocked by CORS policy"

These messages all point to the same issue—your server is not allowing your frontend to access it.

How to Fix CORS Errors in JavaScript (Frontend)

On the frontend, you cannot bypass CORS because it is enforced by the browser. However, you can control how you make requests.

1. Use the Correct Mode in Fetch

fetch("https://example.com/api", {
  method: "GET",
  mode: "cors"
})

This tells the browser that you expect a cross-origin request.

2. Avoid Using Proxy Hacks in Production

Development proxies like Vite or React can temporarily solve the issue, but the real fix must happen on the backend.

3. Do Not Disable Browser Security

This is unsafe and should never be used in real applications.

How to Fix CORS Errors in Node.js (Backend)

Fixing CORS on the server is the correct solution. Node.js makes this easy.

Option 1: Enable CORS Using the CORS Package

import express from "express";
import cors from "cors";

const app = express();
app.use(cors());

app.get("/data", (req, res) => {
  res.json({ message: "CORS Enabled" });
});

app.listen(5000, () => console.log("Server running on port 5000"));

This allows all origins. For security, you can limit it to specific domains.

Option 2: Allow Only Specific Origins

const allowedOrigins = ["http://localhost:3000", "https://yourdomain.com"];

app.use(
  cors({
    origin: (origin, callback) => {
      if (!origin || allowedOrigins.includes(origin)) {
        callback(null, true);
      } else {
        callback(new Error("Not allowed by CORS"));
      }
    }
  })
);

This ensures only trusted websites can access your API.Option 3: Manually Set CORS Headers

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
  res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
  next();
});

Use "*" only for public APIs. Private APIs should restrict origins.

How to Fix CORS Errors in AWS API Gateway

API Gateway requires CORS to be enabled both in the API settings and the Lambda response.

1. Enable CORS in API Gateway Settings

  • Open API Gateway

  • Select your route

  • Click Enable CORS

  • Deploy the API

2. Add CORS Headers in Lambda Response

return {
  statusCode: 200,
  headers: {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Headers": "Content-Type",
    "Access-Control-Allow-Methods": "GET,POST,OPTIONS"
  },
  body: JSON.stringify({ message: "Success" })
};

Without this, API Gateway will still block the request.

Understanding Preflight Requests (OPTIONS)

Before sending certain types of requests, the browser sends an OPTIONS request to check if the server allows it.

Your server must respond with:

Access-Control-Allow-Origin
Access-Control-Allow-Methods
Access-Control-Allow-Headers

If any of these are missing, the browser will block the main request.

Best Practices for Handling CORS Safely

1. Avoid Using * for Private Data

Instead, specify allowed domains.

2. Always Allow OPTIONS Requests

PREVENTS preflight failures.

3. Keep Client and Server on the Same Domain (if possible)

This reduces the need for CORS.

4. Use HTTPS for All Requests

Mixed content can cause additional errors.

5. Test APIs Using Tools Like Postman

Postman does not enforce CORS, so it helps isolate server problems.

Common Mistakes to Avoid

  • Adding CORS headers only on successful responses

  • Forgetting to handle OPTIONS method

  • Enabling CORS on backend but not on API Gateway

  • Using client-side hacks instead of server-side solutions

Conclusion

CORS errors can be frustrating, but once you understand how browsers enforce cross-origin rules, fixing them becomes easy. The key is to allow trusted origins on the server side and respond correctly to preflight (OPTIONS) requests. Whether you're building with JavaScript, Node.js, or API Gateway, the updated methods in this guide will help you solve CORS issues cleanly and safely.