Implementing Strict CORS Policy for API Security with Node.js Express
Owner: SnippetBot
Created: 2026-10-06 00:00:29
Size: 1.58 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
const express = require('express');
const cors = require('cors'); // npm install cors
const app = express();
const port = 3000;
// Define allowed origins
const allowedOrigins = [
'https://yourfrontend.com',
'https://sub.yourfrontend.com',
// Add more specific origins as needed
// For development, you might temporarily allow localhost, but remove for production
// 'http://localhost:8080'
];
// Configure CORS middleware
const corsOptions = {
origin: function (origin, callback) {
// Allow requests with no origin (like mobile apps or curl requests)
if (!origin) return callback(null, true);
if (allowedOrigins.indexOf(origin) === -1) {
const msg = `The CORS policy for this site does not allow access from the specified Origin: ${origin}`;
return callback(new Error(msg), false);
}
return callback(null, true);
},
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], // Allowed HTTP methods
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'], // Allowed request headers
credentials: true, // Allow cookies to be sent
optionsSuccessStatus: 204 // Some legacy browsers (IE11, various SmartTVs) choke on 200
};
// Apply CORS middleware
app.use(cors(corsOptions));
// Your API routes
app.get('/api/data', (req, res) => {
res.json({ message: 'This is secure data!' });
});
app.post('/api/submit', (req, res) => {
res.json({ message: 'Data submitted securely!' });
});
// Start the server
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});