Skip to content

Commit f73eb25

Browse files
committed
feat: Add cors
1 parent bb97b64 commit f73eb25

2 files changed

Lines changed: 23 additions & 1 deletion

File tree

config/env/.env.template

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@ API_VERSION=v1
44
# Server Configuration
55
PORT=8080
66

7+
# frontend website (for handling cors), acccepts comma-separated-values
8+
FRONTEND_WEBSITE_URLS=http://localhost:3000,http://localhost:8080
9+
710
# RAG Query API Key (this doesn't offer protection, just identifies the client)
811
RAG_QUERY_API_KEY="RAG_QUERY_API_KEY"
912

src/index.ts

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,26 @@ const app = express();
1414

1515
const API_PREFIX = `/api/${process.env.API_VERSION || 'v1'}`;
1616
app.use(bodyParser.json());
17-
app.use(cors());
17+
const allowedOrigins = process.env.FRONTEND_WEBSITE_URLS?.split(',').map((origin) => origin.trim()) || [];
18+
// handle cors with a dynamic origin function
19+
app.use(
20+
cors({
21+
origin: (origin, callback) => {
22+
// allow requests with no origin (like mobile apps, curl requests)
23+
if (!origin) return callback(null, true);
24+
25+
if (allowedOrigins?.indexOf(origin) !== -1) {
26+
// if the origin is found in the allowedOrigins array, allow it
27+
return callback(null, true);
28+
} else {
29+
// if the origin is not found in the allowedOrigins array, block it
30+
console.info(`Allowed origins: ${allowedOrigins}`);
31+
return callback(new Error(`Not allowed by CORS: ${origin}`));
32+
}
33+
},
34+
credentials: true,
35+
})
36+
);
1837
app.use(`${API_PREFIX}/rag/manage`, ragManagementRouter);
1938
app.use(`${API_PREFIX}/`, geminiRouter);
2039

0 commit comments

Comments
 (0)