Skip to content

fix(server): restrict CORS to allowed origin from env variable#450

Merged
mehul-m-prajapati merged 1 commit into
GitMetricsLab:mainfrom
adityack477:fix/cors-restrict-origin
May 23, 2026
Merged

fix(server): restrict CORS to allowed origin from env variable#450
mehul-m-prajapati merged 1 commit into
GitMetricsLab:mainfrom
adityack477:fix/cors-restrict-origin

Conversation

@adityack477
Copy link
Copy Markdown
Contributor

@adityack477 adityack477 commented May 23, 2026

Related Issue


Description

The server used cors() with no origin restriction, allowing any
domain to make credentialed API requests - a security risk.

Replaced with an explicit origin config that reads CLIENT_URL
from environment variables, falling back to localhost:5173 for
local dev. Added credentials: true so session cookies continue
working cross-origin.

  • backend/server.js : updated CORS configuration
  • backend/.env.example : added CLIENT_URL variable

How Has This Been Tested?

  • Verified login and API calls work normally from the frontend
  • Confirmed requests from unlisted origins are blocked

Screenshots (if applicable)


Type of Change

  • Bug fix
  • New feature
  • Code style update
  • Breaking change
  • Documentation update

Summary by CodeRabbit

  • Chores
    • Added environment configuration template for server setup and initialization.
    • Updated cross-origin request policy to allow only authorized client domains, enhancing server security.

Review Change Stack

@netlify
Copy link
Copy Markdown

netlify Bot commented May 23, 2026

Deploy Preview for github-spy ready!

Name Link
🔨 Latest commit 64c1064
🔍 Latest deploy log https://app.netlify.com/projects/github-spy/deploys/6a11961ab7f02d0008df7abd
😎 Deploy Preview https://deploy-preview-450--github-spy.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 23, 2026

📝 Walkthrough

Walkthrough

The PR hardens CORS security by replacing wildcard origin configuration with a restricted policy that permits only the frontend client URL and enables credentials support. Environment variable requirements are documented in an example configuration file.

Changes

CORS Security Hardening

Layer / File(s) Summary
Environment configuration template
backend/.env.example
Example environment file documents required variables: SESSION_SECRET, MONGO_URI, PORT, and CLIENT_URL.
CORS origin restriction
backend/server.js
CORS middleware restricted from wildcard (cors('*')) to accept only process.env.CLIENT_URL (defaulting to http://localhost:5173) with credentials enabled.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

A rabbit hops through CORS gates so tight,
No more wildcards—just the client site!
With credentials safe and origins true,
The backend's secure, through and through! 🐰🔒

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: restricting CORS to an allowed origin from environment variables.
Description check ✅ Passed The description follows the template and provides all essential sections: related issue, detailed explanation of changes, testing approach, and type of change.
Linked Issues check ✅ Passed The PR fully addresses issue #367 by replacing cors('*') with origin-restricted configuration using environment variables and enabling credentials support as required.
Out of Scope Changes check ✅ Passed All changes directly support the security objective of restricting CORS: backend/.env.example provides the CLIENT_URL template and backend/server.js implements the restricted CORS configuration.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

Review ran into problems

🔥 Problems

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
backend/server.js (1)

17-20: ⚡ Quick win

Consider logging when CLIENT_URL is not explicitly set.

The fallback to localhost:5173 is appropriate for local development, but if CLIENT_URL is accidentally omitted in production, the server will start successfully while CORS silently blocks all legitimate requests. Unlike other environment variables in this file (SESSION_SECRET, MONGO_URI, PORT), CLIENT_URL has a fallback that could mask configuration issues.

📋 Suggested enhancement for production safety

Add a startup log to make the CORS origin explicit:

 // CORS configuration
+const clientURL = process.env.CLIENT_URL || 'http://localhost:5173';
+if (!process.env.CLIENT_URL) {
+  logger.warn('CLIENT_URL not set, falling back to localhost:5173');
+}
 app.use(cors({
-  origin: process.env.CLIENT_URL || 'http://localhost:5173',
+  origin: clientURL,
   credentials: true,
 }));
+logger.info(`CORS enabled for origin: ${clientURL}`);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/server.js` around lines 17 - 20, Add a startup log that explicitly
reports which CORS origin is being used so missing CLIENT_URL doesn't silently
mask misconfiguration: check process.env.CLIENT_URL when configuring
app.use(cors(...)) (or immediately before app.listen) and log a warning if it's
undefined while also logging the effective origin value (the
process.env.CLIENT_URL or the fallback 'http://localhost:5173') so operators can
see whether the environment variable was provided; reference the existing
app.use(cors(...)) block and process.env.CLIENT_URL when adding the log.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@backend/server.js`:
- Around line 17-20: Add a startup log that explicitly reports which CORS origin
is being used so missing CLIENT_URL doesn't silently mask misconfiguration:
check process.env.CLIENT_URL when configuring app.use(cors(...)) (or immediately
before app.listen) and log a warning if it's undefined while also logging the
effective origin value (the process.env.CLIENT_URL or the fallback
'http://localhost:5173') so operators can see whether the environment variable
was provided; reference the existing app.use(cors(...)) block and
process.env.CLIENT_URL when adding the log.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a3134437-b045-46b1-85d8-01fbfb581c2c

📥 Commits

Reviewing files that changed from the base of the PR and between 3744344 and 64c1064.

📒 Files selected for processing (2)
  • backend/.env.example
  • backend/server.js

@mehul-m-prajapati mehul-m-prajapati merged commit 45a5923 into GitMetricsLab:main May 23, 2026
7 checks passed
@github-actions
Copy link
Copy Markdown

🎉🎉 Thank you for your contribution! Your PR #450 has been merged! 🎉🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Security: Fix overly permissive CORS

2 participants