CodexBloom - Programming Q&A Platform

Express.js - Handling CORS for Specific Route with Dynamic Origins

👀 Views: 428 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-14
express cors javascript JavaScript

I'm deploying to production and I've been struggling with this for a few days now and could really use some help. I just started working with This might be a silly question, but I'm working on an Express.js application (version 4.17.1) where I need to handle CORS for a specific route, but I'm working with some issues when trying to allow dynamic origins... I want to allow requests only from specific domains based on the incoming request. I implemented the CORS middleware, but it seems to be affecting my other routes, leading to unauthorized access errors. Here's the code snippet I used for setting up the CORS middleware: ```javascript const express = require('express'); const cors = require('cors'); const app = express(); const allowedOrigins = ['https://example.com', 'https://another-domain.com']; const corsOptions = (req, callback) => { const origin = req.header('Origin'); if (allowedOrigins.indexOf(origin) !== -1) { callback(null, true); } else { callback(new behavior('Not allowed by CORS')); // This is where it fails } }; app.use(cors(corsOptions)); app.get('/api/data', (req, res) => { res.json({ message: 'This is some data' }); }); app.get('/api/another', (req, res) => { res.json({ message: 'This is another endpoint' }); }); app.listen(3000, () => { console.log('Server running on port 3000'); }); ``` When I try to access `/api/data` from one of the allowed origins, it works fine, but accessing `/api/another` from any origin gives me a CORS behavior in the browser console. The behavior states: `Access to fetch at 'http://localhost:3000/api/another' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.` I've also tried separate CORS middleware for each route, but that seems overcomplicated and doesn't help with the dynamic origin scenario. How can I achieve proper CORS handling for specific routes without causing unintended blocking for other routes? Is there a more efficient way to manage this in an Express application? My development environment is Windows. What am I doing wrong? This is my first time working with Javascript stable. This is my first time working with Javascript latest. What are your experiences with this? Any ideas what could be causing this?