Skip to content

fix(#218): allow multiple CORS origins on Next.js server and update dependencies #263

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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

rjoydip
Copy link
Contributor

@rjoydip rjoydip commented May 17, 2025

This Pull Request (PR) introduces a robust solution for handling Cross-Origin Resource Sharing (CORS) on the Next.js server, enabling secure communication with multiple specified frontend origins. Additionally, it updates several key project dependencies to their latest stable versions, ensuring better performance, security, and access to new features.

✨ Changes Introduced

1. CORS Configuration (pages/_middleware.ts)

  • Dynamic Origin Whitelisting: The middleware now dynamically checks the Origin header of incoming requests against a predefined list of allowedOrigins. This ensures that only trusted frontends can interact with the API, enhancing security.
  • Flexible Access-Control-Allow-Origin: If a request's origin is found within the allowedOrigins array, the Access-Control-Allow-Origin header is set to the specific requesting origin. This is crucial for proper CORS behavior and avoids issues with wildcard origins.
  • Official documentation: https://nextjs.org/docs/app/building-your-application/routing/middleware#cors

2. Code Refactoring

I spotted a few potential issues:

  • The CORS headers need to be set differently in Next.js middleware. When using NextResponse.next(), any headers you add with append() modify the request that will be forwarded to your route handlers, not the response that will be sent back to the client.
  • The code doesn't handle preflight requests (OPTIONS) properly, which is crucial for CORS to work properly.

3. Dependency Updates (package.json)

  • @changesets/cli: Updated from 2.29.3 to 2.29.4.

Fixed: #218

Summary by CodeRabbit

  • New Features

    • Improved CORS support to allow multiple origins, with dynamic handling based on a configurable list.
    • Expanded allowed HTTP methods in CORS headers to include PUT and DELETE.
  • Refactor

    • Enhanced middleware logic for more robust and flexible CORS handling.
  • Chores

    • Updated the @changesets/cli development dependency to the latest version.

Copy link

changeset-bot bot commented May 17, 2025

⚠️ No Changeset found

Latest commit: 97fb15d

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented May 17, 2025

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The middleware for the Next.js backend server was refactored to support multiple allowed CORS origins by reading a comma-separated list from an environment variable. The function signature was updated to accept a request parameter, and CORS headers were set dynamically based on the request's origin. Additionally, a development dependency was updated.

Changes

File(s) Change Summary
apps/cli/templates/backend/server/next/src/middleware.ts Refactored middleware to support multiple CORS origins, dynamic header setting, expanded allowed methods, and updated function signature.
package.json Updated @changesets/cli devDependency version from ^2.29.3 to ^2.29.4.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Middleware
    participant NextApp

    Client->>Middleware: Sends HTTP request (with Origin header)
    Middleware->>Middleware: Extracts Origin header
    Middleware->>Middleware: Checks if Origin is in allowed list
    alt OPTIONS preflight
        Middleware-->>Client: Responds with CORS headers (if allowed)
    else Other methods
        Middleware->>NextApp: Forwards request
        NextApp-->>Middleware: Returns response
        Middleware-->>Client: Responds with CORS headers (if allowed)
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
Support multiple origins in CORS middleware using env variable (CORS_ORIGINS) (#218)
Dynamically set Access-Control-Allow-Origin header for allowed origins (#218)
Update middleware function signature to accept request parameter (#218)
Expand allowed HTTP methods in CORS headers (#218)

Poem

A rabbit hops with nimble cheer,
Now CORS is set for every peer!
Origins many, not just one,
All checked before the work is done.
With headers set, requests allowed,
The monorepo bunny feels quite proud!
🐇✨


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
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.

Actionable comments posted: 0

🧹 Nitpick comments (2)
apps/cli/templates/backend/server/next/src/middleware.ts (2)

24-34: Consider adding trim() when processing origins from environment variables.

The origin comparison could be more robust by trimming whitespace from the allowed origins. This would prevent issues when environment variables contain spaces after commas.

- const allowedOrigins = process.env.CORS_ORIGINS?.split(",") ?? [];
+ const allowedOrigins = process.env.CORS_ORIGINS?.split(",").map(origin => origin.trim()) ?? [];

9-12: Consider adding a default origin for local development.

If CORS_ORIGINS is not set in the environment, the allowed origins array will be empty, which might cause issues during local development. Consider adding a default development origin when the environment variable is not set.

- const allowedOrigins = process.env.CORS_ORIGINS?.split(",") ?? [];
+ const allowedOrigins = process.env.CORS_ORIGINS?.split(",") ?? 
+   (process.env.NODE_ENV === 'development' ? ['http://localhost:3000'] : []);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between a8d3daa and 9aab9eb.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (2)
  • apps/cli/templates/backend/server/next/src/middleware.ts (1 hunks)
  • package.json (1 hunks)
🔇 Additional comments (6)
package.json (1)

19-19: Dependency version update looks good.

The update from @changesets/cli@^2.29.3 to @changesets/cli@^2.29.4 is a minor patch version change that likely includes bug fixes and maintenance improvements. This is a low-risk change that aligns with the PR objectives.

apps/cli/templates/backend/server/next/src/middleware.ts (5)

1-1: Import statement updated correctly.

The import statement now properly imports both NextRequest and NextResponse from 'next/server', which is necessary for the updated middleware function signature that accepts a request parameter.


3-7: Good extraction of CORS options into a reusable object.

Extracting CORS headers into a dedicated object improves code readability and maintainability. The CORS configuration includes all necessary headers with appropriate values, and correctly expands the allowed methods to include PUT and DELETE as mentioned in the PR objectives.


9-12: Multiple CORS origins handling implemented correctly.

The middleware function now properly extracts the origin from request headers and checks it against a list of allowed origins from the environment variable. The implementation follows best security practices by only allowing specific origins instead of using wildcards.


14-22: Proper handling of preflight OPTIONS requests.

The code correctly identifies and handles preflight OPTIONS requests by returning an immediate response with appropriate CORS headers. The conditional inclusion of the Access-Control-Allow-Origin header only for allowed origins is a good security practice.


30-32: Efficient header setting with Object.entries.

Using Object.entries to iterate through the CORS options and set headers is a clean and maintainable approach. This ensures all required CORS headers are consistently applied.

@rjoydip rjoydip changed the title fix(issues-218): allow multiple CORS origins on Next.js server and update dependencies fix(#218): allow multiple CORS origins on Next.js server and update dependencies May 19, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add multiple origins setup in middleware when creating monorepo
1 participant