Skip to content

correct origin cors middleware #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 15, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,24 @@ const port = process.env.PORT || 3000;

app.use(express.json());
app.use(cookieParser());
const allowlist = [
"http://localhost:3000",
"https://posts-seven-red.vercel.app",
];

app.use(
cors({
origin: "http://localhost:5173", // Autoriser uniquement votre frontend
origin: (origin, callback) => {
if (
Copy link

Choose a reason for hiding this comment

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

suggestion: Clarify ternary operator precedence

Consider adding parentheses around the production check or extracting the condition into a named variable to improve readability and prevent misinterpretation.

!origin || process.env.NODE_ENV === "production"
Copy link

Choose a reason for hiding this comment

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

🚨 question (security): Reconsider allowing requests with no Origin header

Requests without an Origin header are currently permitted, which could allow non-browser clients to bypass CORS. Confirm if this behavior is intended.

? allowlist.includes(origin)
: origin === "http://localhost:5173"
) {
callback(null, true);
} else {
callback(new Error("Not allowed by CORS"));
}
Comment on lines +31 to +33
Copy link

Choose a reason for hiding this comment

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

suggestion (bug_risk): Use callback(null, false) instead of throwing an error

Calling the callback with an error causes a 500 response. Use callback(null, false) to reject the request without triggering an internal server error.

Suggested change
} else {
callback(new Error("Not allowed by CORS"));
}
} else {
callback(null, false);
}

},
credentials: true,
allowedHeaders: ["Content-Type", "Authorization", "X-Requested-With"],
exposedHeaders: ["Content-Length", "X-Total-Count"],
Expand Down