AceDevHub
Intermediate Node.js Interview QuestionsIntermediateConcept

Node.js · Question 47

What is CORS and how do you handle it in Node.js?

Direct answer

CORS is a browser security policy — servers must send Access-Control-Allow-Origin (and related headers) for cross-origin fetches; use cors middleware in Express or @fastify/cors in Fastify with explicit allowed origins, not * with credentials.

CORS applies to browsers, not server-to-server calls. AceDevHub web (localhost:3000) calling API (localhost:4000) is cross-origin — the API must allow the web origin.

Why interviewers ask

HeaderPurpose
Access-Control-Allow-OriginWhich origins may read the response
Access-Control-Allow-MethodsAllowed verbs for preflight
Access-Control-Allow-HeadersAllowed request headers (Authorization, Content-Type)
Access-Control-Allow-Credentialstrue when cookies/httpOnly JWT cross-origin
  • Preflight OPTIONS — browser sends OPTIONS before non-simple requests; server must respond 204 with CORS headers.
  • Credentials — fetch(..., { credentials: 'include' }) requires specific origin, not *.
  • SameSite cookies — auth design pairs with CORS for Google OAuth session cookies.
cors-express.mjs
import express from "express";
import cors from "cors";

const app = express();

app.use(cors({
  origin: ["http://localhost:3000", "https://acedevhub.com"],
  credentials: true,
  methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
}));

// Fastify: await fastify.register(import('@fastify/cors'), { origin: [...] })