Skip to content
This repository has been archived by the owner on Sep 15, 2024. It is now read-only.

Commit

Permalink
feat: support multiple origins for CORS
Browse files Browse the repository at this point in the history
  • Loading branch information
Dwigoric committed Nov 14, 2023
1 parent c201381 commit 716519b
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 11 deletions.
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion example.env
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
MONGODB_URI=
JWT_SECRET=
FRONTEND_URL=
FRONTEND_URLS=
PORT=
12 changes: 4 additions & 8 deletions src/app.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
// Default FRONTEND_URL

const DEFAULT_FRONTEND_URL = 'http://localhost:5173'

// Packages
import createError from 'http-errors'
import express from 'express'
Expand Down Expand Up @@ -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
})
)
Expand Down

0 comments on commit 716519b

Please sign in to comment.