Setup CORS with domain

1 min read
This is my current setup for all of my backend services, this CORS is based on my domain.
(this one is generated by AI, I haven’t fully tested it)
// Enable CORS
app.enableCors({
origin: (origin, callback) => {
// Allow requests with no origin (mobile apps, Postman, etc.)
if (!origin) return callback(null, true);
// List of allowed origins
const allowedOrigins = ['http://localhost:9000'];
// Check if origin is in the allowed list
if (allowedOrigins.includes(origin)) {
return callback(null, true);
}
// Check if origin matches thebrownbox.dev domain pattern
// This allows: thebrownbox.dev, www.thebrownbox.dev, api.thebrownbox.dev, etc.
const thebrownboxPattern =
/^https?:\/\/([a-zA-Z0-9-]+\.)*thebrownbox\.dev(:[0-9]+)?$/;
if (thebrownboxPattern.test(origin)) {
return callback(null, true);
}
// Reject all other origins
callback(new Error('Not allowed by CORS'), false);
},
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
allowedHeaders: [
'Origin',
'X-Requested-With',
'Content-Type',
'Accept',
'Authorization',
'X-Access-Token',
],
});
0
Subscribe to my newsletter
Read articles from The Brown Box directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
