Skip to content

Commit 6c6aecb

Browse files
committed
use CORS_ALLOW_ORIGINS instead of SERVER_ORIGIN, WEB_ORIGIN, WEB_ORIGIN_BUILD, and MOBILE_ORIGIN
1 parent 021ea3e commit 6c6aecb

File tree

3 files changed

+25
-11
lines changed

3 files changed

+25
-11
lines changed

server/.env.sample

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,8 @@
33
# below can be used for docker db created via `make dev-db`
44
DATABASE_URL=postgres://user:password@localhost:5432/database
55

6-
# Application origins
7-
SERVER_ORIGIN=http://localhost:3000
8-
WEB_ORIGIN=http://localhost:5173
9-
MOBILE_ORIGIN=http://localhost:8081
6+
# CORS allow origins, separated by "," | no space is allowed before/after ","
7+
CORS_ALLOW_ORIGINS=http://localhost:3000,http://localhost:3001
108

119
# Firebase
1210
FIREBASE_PROJECT_ID=project-id

server/src/index.ts

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import express from "express";
33
import csrf from "./lib/cross-origin/block-unknown-origin";
44
import cors from "./lib/cross-origin/multi-origin-cors";
55
import { initializeSocket } from "./lib/socket/socket";
6+
import { allUrlMustBeValid, panic } from "./lib/utils";
67
import chatRoutes from "./router/chat";
78
import coursesRoutes from "./router/courses";
89
import matchesRoutes from "./router/matches";
@@ -17,14 +18,15 @@ const app = express();
1718
app.set("query parser", "simple");
1819

1920
const port = 3000;
20-
const allowedOrigins = [
21-
process.env.SERVER_ORIGIN ?? "http://localhost:3000", // delete this fallback when you think everyone has updated their .env
22-
process.env.WEB_ORIGIN,
23-
process.env.MOBILE_ORIGIN,
24-
process.env.WEB_ORIGIN_BUILD,
25-
];
21+
const allowedOrigins = (
22+
process.env.CORS_ALLOW_ORIGINS || panic("env CORS_ALLOW_ORIGINS is missing")
23+
)
24+
.split(",")
25+
.filter((s) => s); // ignore empty string (trailing comma?)
26+
allUrlMustBeValid(allowedOrigins);
27+
2628
export const corsOptions = {
27-
origins: allowedOrigins.filter((s) => s != null).filter((s) => s), // ignore empty string too
29+
origins: allowedOrigins,
2830
methods: ["GET", "HEAD", "POST", "PUT", "DELETE"],
2931
credentials: true,
3032
};

server/src/lib/utils.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
export function panic(reason: string): never {
2+
throw new Error(`function panic() called for reason: "${reason}"`);
3+
}
4+
5+
export function allUrlMustBeValid(urls: string[]) {
6+
for (const url of urls) {
7+
try {
8+
new URL(url);
9+
} catch (err) {
10+
console.error(err);
11+
throw err;
12+
}
13+
}
14+
}

0 commit comments

Comments
 (0)