Skip to content

Commit c921a25

Browse files
committed
configure CORS in websocket
1 parent 78c0290 commit c921a25

File tree

3 files changed

+15
-4
lines changed

3 files changed

+15
-4
lines changed

server/src/index.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,12 @@ export const corsOptions = {
3131
credentials: true,
3232
};
3333

34+
if (corsOptions.origins.length > 1 && process.env.NODE_ENV === "production") {
35+
console.warn(
36+
"WARNING: socket.io only supports one cors origin, therefore only first origin will be registered.",
37+
);
38+
}
39+
3440
app.use(cors(corsOptions));
3541
app.use(csrf(corsOptions));
3642

server/src/lib/cross-origin/share.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
type Config = {
1+
export type Config = {
22
origins: string[]; // allowed origins
33
methods?: string[]; // Access-Control-Allow-Methods
44
credentials?: boolean; // Access-Control-Allow-Credentials
@@ -47,4 +47,4 @@ function assertValidConfig(config: Config) {
4747
}
4848
}
4949

50-
export { validateConfig, type Config };
50+
export { validateConfig };

server/src/lib/socket/socket.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,17 @@ import type { Message, UserID } from "common/types";
33
import type { CorsOptions } from "cors";
44
import { type Socket, Server as SocketIOServer } from "socket.io";
55
import { getUserIdFromToken } from "../../firebase/auth/db";
6+
import type { Config as CorsConfig } from "../cross-origin/share";
67

78
const users = new Map<UserID, Socket>();
89

9-
export function initializeSocket(server: Server, corsOptions: CorsOptions) {
10+
export function initializeSocket(server: Server, corsOptions: CorsConfig) {
11+
const cors: CorsOptions = {
12+
origin: corsOptions.origins[0],
13+
...corsOptions,
14+
};
1015
const io = new SocketIOServer(server, {
11-
cors: corsOptions,
16+
cors,
1217
connectionStateRecovery: {},
1318
});
1419

0 commit comments

Comments
 (0)