From 716519b40ac049eb2fc5bfd54372e8701431223f Mon Sep 17 00:00:00 2001 From: Joshua Permito Date: Tue, 14 Nov 2023 11:25:05 +0800 Subject: [PATCH] feat: support multiple origins for CORS --- README.md | 5 +++-- example.env | 2 +- src/app.js | 12 ++++-------- 3 files changed, 8 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 0fc7a83..b100179 100644 --- a/README.md +++ b/README.md @@ -18,9 +18,10 @@ The MongoDB URI to use for the application, defaults to `mongodb://localhost:270 ### `JWT_SECRET` The secret to use for JWT. This is required for the application to run. If not set, the application will throw an error. -### `FRONTEND_URL` -The URL of the frontend application, defaults to `http://localhost:5173`. +### `FRONTEND_URLS` +The comma-separated list of URLs of the frontend application. This is used for CORS. +If no value is set, the application will allow all origins. ## Private Files Put any private files in the `private` directory. diff --git a/example.env b/example.env index 221342d..8b810af 100644 --- a/example.env +++ b/example.env @@ -1,4 +1,4 @@ MONGODB_URI= JWT_SECRET= -FRONTEND_URL= +FRONTEND_URLS= PORT= \ No newline at end of file diff --git a/src/app.js b/src/app.js index dcd4036..e05d910 100644 --- a/src/app.js +++ b/src/app.js @@ -1,7 +1,3 @@ -// Default FRONTEND_URL - -const DEFAULT_FRONTEND_URL = 'http://localhost:5173' - // Packages import createError from 'http-errors' import express from 'express' @@ -30,12 +26,12 @@ import settingsRouter from './routes/settings.js' const app = express() // Configure CORS -if (!process.env.FRONTEND_URL) - console.warn(`FRONTEND_URL not set, using default: ${DEFAULT_FRONTEND_URL}`) - +const whitelist = [] +if (!process.env.FRONTEND_URL) console.warn('FRONTEND_URLS not set, allowing all origins') +else whitelist.push(...process.env.FRONTEND_URL.split(',')) app.use( cors({ - origin: process.env.FRONTEND_URL || DEFAULT_FRONTEND_URL, + origin: (origin) => whitelist.length === 0 || whitelist.includes(origin), optionsSuccessStatus: 200 }) )