Skip to content

chore: update dependencies and improve middleware logic#163

Closed
carhartlewis wants to merge 6 commits into
mainfrom
lewis/middleware-fix
Closed

chore: update dependencies and improve middleware logic#163
carhartlewis wants to merge 6 commits into
mainfrom
lewis/middleware-fix

Conversation

@carhartlewis
Copy link
Copy Markdown
Contributor

@carhartlewis carhartlewis commented Mar 20, 2025

  • Updated various package dependencies including @aws-sdk/client-securityhub, @ai-sdk/openai, @ai-sdk/provider, @ai-sdk/react, @tanstack/react-query, and others to their latest versions.
  • Enhanced middleware logic to streamline authentication checks and improve session handling.
  • Refactored Google sign-in component for better readability and maintainability.
  • Adjusted layout component to remove unnecessary authentication checks.

Summary by CodeRabbit

  • Chores

    • Upgraded various libraries and development tools to boost stability, performance, and compatibility.
  • Refactor

    • Streamlined authentication and routing flows for a smoother sign-in experience, including an updated post-sign-in redirect.
    • Improved backend connectivity by transitioning to a more reliable database adapter.
    • Enhanced middleware for clearer internationalization handling, removing authentication logic.
    • Adjusted rendering structure in the Providers component for better encapsulation of children elements.

- Updated various package dependencies including `@aws-sdk/client-securityhub`, `@ai-sdk/openai`, `@ai-sdk/provider`, `@ai-sdk/react`, `@tanstack/react-query`, and others to their latest versions.
- Enhanced middleware logic to streamline authentication checks and improve session handling.
- Refactored Google sign-in component for better readability and maintainability.
- Adjusted layout component to remove unnecessary authentication checks.
@vercel
Copy link
Copy Markdown

vercel Bot commented Mar 20, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
app ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 20, 2025 1:53pm
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
comp-portal ⬜️ Skipped (Inspect) Mar 20, 2025 1:53pm

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 20, 2025

Walkthrough

The pull request updates multiple dependencies across various package configuration files, adjusts authentication flow and redirection logic in several components, and refactors the database adapter integration. The changes remove redundant authentication checks in the layout, reformat and modify redirect behavior in the Google sign-in component, and update the middleware function for clearer session validation and redirection. Additionally, the Neon adapter has been replaced with a PostgreSQL solution in the database package.

Changes

File(s) Change Summary
apps/app/package.json, apps/portal/package.json, package.json, packages/db/package.json, packages/analytics/package.json Updated several dependency and devDependency versions, added a new Next.js dependency, and upgraded packages (e.g., @ai-sdk series, Next.js, AWS SDK, better-auth, @prisma/extension-accelerate, posthog-js).
apps/app/src/.../layout.tsx Removed authentication-related imports and session validation logic from the layout component.
apps/app/src/components/google-sign-in.tsx Reformatted indentation for consistency; adjusted redirect path from "/" to "/setup" when no invite code is provided.
apps/app/src/middleware.ts Refactored the middleware function with an updated function signature, restructured authentication and redirection logic, and added a consistent pathname header.
packages/db/src/index.js Eliminated Neon database adapter logic and integrated the PostgreSQL adapter for the Prisma client, with corresponding code restructuring.
apps/portal/src/app/[locale]/providers.tsx Wrapped children prop in a React fragment when hasAnalyticsKeys is false, without altering logical flow.
apps/app/src/app/page.tsx Updated session validation logic to check for session.user instead of session, with adjusted indentation.
apps/app/src/components/magic-link.tsx Modified redirectTo property in the signIn function to redirect to "/setup" if no inviteCode is provided.

Possibly related PRs

Poem

I hopped through code with joyful cheer,
Dependencies updated, crisp and clear.
No more auth checks in the layout’s space,
Middleware now leads with a friendly pace.
I nibble bugs with a twitch of delight,
A rabbit’s rhyme for a codebase bright!
Hooray for changes under moonlight!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 444a377 and 0efc2e2.

📒 Files selected for processing (5)
  • apps/app/src/app/layout.tsx (1 hunks)
  • apps/app/src/app/page.tsx (1 hunks)
  • apps/app/src/components/google-sign-in.tsx (1 hunks)
  • apps/app/src/components/magic-link.tsx (1 hunks)
  • apps/app/src/middleware.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/app/src/app/layout.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/app/src/components/google-sign-in.tsx
🔇 Additional comments (7)
apps/app/src/components/magic-link.tsx (1)

46-48: Authentication flow change: Redirect path updated to "/setup"

The redirect path has been changed from "/" to "/setup" when no invite code is provided. This change aligns with the broader authentication flow improvements mentioned in the PR objectives, directing users to a setup page after authentication instead of directly to the root page.

Make sure the "/setup" route is properly configured to handle this flow and that this change is consistent with the user journey you want to create.

apps/app/src/app/page.tsx (2)

5-9: Improved session validation with explicit user check

The session validation has been enhanced to specifically check for session?.user instead of just session. This is a more precise check that ensures a user is properly authenticated.

This change aligns with the PR objectives of streamlining authentication checks and provides better security by ensuring the existence of a valid user object before proceeding.


11-15: Properly structured authentication flow

The authentication flow is now properly structured to:

  1. First check if the user exists
  2. Then check if they have an organization
  3. Finally redirect to setup if neither of the above conditions are met

This logical flow ensures users are properly guided through the authentication and setup process, which aligns with the redirect change in the magic-link component.

apps/app/src/middleware.ts (4)

10-22: Improved middleware with focused responsibility

The middleware has been significantly refactored to focus solely on internationalization, removing authentication logic that was previously present. This creates a cleaner separation of concerns and aligns with the PR objectives of improving middleware logic.

The addition of the "x-pathname" header is a good touch as it makes the current path available to other parts of the application that might need this information.


4-8: Well-configured internationalization settings

The internationalization middleware is configured with multiple languages (en, es, fr, no, pt) with English as the default. Using the "rewrite" URL mapping strategy is appropriate for most Next.js applications as it handles locale-specific routes while maintaining a clean URL structure.


15-18: Clean pathname extraction logic

The logic to extract the pathname without the locale prefix is clean and handles the case where no locale is present. This will be useful for any routing logic that needs to operate independently of the current locale.


24-28: Appropriate route matching configuration

The middleware configuration correctly excludes static assets, API routes, and monitoring endpoints from being processed. This is important for performance as it ensures the middleware only runs for user-facing routes that need internationalization.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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

- Upgraded `next` to version `15.3.0-canary.14` for improved features and performance.
- Updated `@types/react` to `19.0.10` and `posthog-js` to `1.232.0` for better type definitions and analytics support.
- Adjusted `@types/react-dom` to `19.0.4` for consistency across type definitions.
- Enhanced `providers.tsx` to use fragment syntax for rendering children.
- Simplified middleware by removing unnecessary comments and restructuring the authentication checks.
- Updated the middleware to use destructured request properties for cleaner code.
- Ensured consistent handling of session and URL redirection logic.
- Maintained the integration of the I18n middleware for internationalization support.
@vercel vercel Bot temporarily deployed to Preview – comp-portal March 20, 2025 13:06 Inactive
Copy link
Copy Markdown

@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/app/src/middleware.ts (2)

18-50: Consider adding request logging for better observability.

While the error handling is solid, adding request logging would improve observability and debugging capabilities. This could help track authentication flows and identify potential issues.

export default auth((req) => {
	try {
+		// Log incoming request for debugging
+		console.log(`Middleware processing: ${req.nextUrl.pathname}`);
		const { auth: session, nextUrl } = req;

		// Rest of the code...
	} catch (error) {
		console.error("Middleware error:", error);
		return new NextResponse("Internal Server Error", { status: 500 });
	}
});

20-39: Consider adding type assertion for better type safety.

The current implementation relies on type inference. Adding explicit type assertions would improve code readability and catch potential type-related issues earlier.

export default auth((req) => {
	try {
-		const { auth: session, nextUrl } = req;
+		const { auth: session, nextUrl } = req as { auth: { user?: { id: string } } | null, nextUrl: URL };

		// Rest of the code...
	}
});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f2b4039 and 1a08fa5.

📒 Files selected for processing (1)
  • apps/app/src/middleware.ts (1 hunks)
🔇 Additional comments (8)
apps/app/src/middleware.ts (8)

6-9: Good enhancement to the matcher pattern.

The updated matcher configuration properly excludes system paths and adds runtime specification. This ensures middleware only runs on relevant routes, improving performance.


13-15: Expanded internationalization support.

The locales array has been expanded to include "no" and "pt" languages, improving the application's accessibility to Norwegian and Portuguese users.


18-20: Refactored middleware implementation for cleaner integration with auth.

The previous mainMiddleware function has been replaced with a more direct approach using the auth wrapper function. This makes the authentication flow more explicit and removes the need for a separate middleware function.


22-24: Improved authentication redirect logic.

The redirect logic now correctly checks for both the session state and the current path, ensuring unauthenticated users are properly directed to the auth page except when they're already there.


26-28: Proper handling of authenticated users on auth page.

Redirecting authenticated users away from the auth page prevents unnecessary authentication flows and improves user experience.


30-39: Well-structured root path handling with performance consideration.

The root path handling is well-implemented with clear comments explaining the rationale. The comment about avoiding Prisma in middleware is particularly important for performance.


41-44: Consistent header management.

Setting the x-pathname header provides valuable context to downstream handlers. This is a good practice for debugging and tracking request flow.


45-49: Comprehensive error handling.

The try/catch block with specific error logging and appropriate error response ensures the middleware remains robust even when unexpected errors occur.

- Integrated NextAuth for improved authentication handling within the middleware.
- Updated the middleware to utilize TypeScript types for request and response.
- Streamlined session retrieval and URL redirection logic for better clarity and performance.
- Maintained compatibility with the existing I18n middleware for internationalization support.
@vercel vercel Bot temporarily deployed to Preview – comp-portal March 20, 2025 13:15 Inactive
Copy link
Copy Markdown

@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 (1)
apps/app/src/middleware.ts (1)

35-43: Consider consolidating redundant redirect logic.

There's some potential redundancy between the root path redirect logic and the earlier general redirect logic. The check at lines 26-28 already handles redirecting unauthenticated users, which overlaps with the root path handling at lines 35-38.

// Only handle root path redirects
if (nextUrl.pathname === "/") {
-  if (!session?.user) {
-    return NextResponse.redirect(new URL("/auth", nextUrl.origin));
-  }

  // If authenticated, let the page handle the redirection
  // This way we avoid Prisma in middleware
  return NextResponse.next();
}

Since you're already checking for unauthenticated users earlier in the middleware, this could be simplified to just handle the authenticated case for the root path.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1a08fa5 and 29ed517.

📒 Files selected for processing (1)
  • apps/app/src/middleware.ts (1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
apps/app/src/middleware.ts (2)
apps/app/src/auth/config.ts (1) (1)
  • authConfig (27-76)
apps/app/src/auth/index.ts (1) (1)
  • auth (6-6)
🔇 Additional comments (4)
apps/app/src/middleware.ts (4)

19-19: Clean NextAuth initialization.

Good approach to destructure the auth function from the NextAuth initialization. This makes the code more readable and follows the recommended pattern for NextAuth v5.


21-54: Improved authentication flow with cleaner redirection logic.

The refactored middleware effectively handles authentication state and redirection in a more streamlined way. Using await auth() to check sessions is a clean approach that leverages NextAuth v5's functionality.

A few observations:

  1. Good error handling with appropriate logging and 500 response
  2. Clear separation of redirection logic for different authentication states
  3. Helpful comments explaining the root path handling

7-11: Good matcher configuration.

The matcher is correctly set up to exclude system paths and static assets. The runtime: "nodejs" setting is appropriate for middleware that needs to access environment variables and make external API calls.


45-48: Consistently setting x-pathname header.

Good practice to consistently set the x-pathname header on the response, which will make client-side navigation tracking more reliable.

…d I18n integration

- Refactored middleware to utilize the `auth` middleware for session management.
- Simplified URL redirection logic for unauthenticated users and improved handling for authenticated users.
- Maintained the integration of the I18n middleware for consistent internationalization support.
- Improved code clarity and performance by restructuring the middleware flow.
Copy link
Copy Markdown

@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 (3)
apps/app/src/middleware.ts (3)

6-8: Locale definitions are straightforward.
Defining multiple locales and the default locale is clear. If you anticipate more locales, consider externalizing the config for easier maintenance.


11-16: Potential edge runtime opportunity.
This config is valid; however, you might consider using "edge" as the runtime for potentially lower latency and higher scalability if suitable for your use case.


30-38: Redundant authentication check.
Lines 22–24 already handle unauthenticated users visiting “/”. The nested if (!session?.user) block here duplicates that logic. Consider removing it to reduce complexity.

Example refactor:

-if (!session?.user && nextUrl.pathname !== "/auth") {
-  return NextResponse.redirect(...);
-}
...
-if (nextUrl.pathname === "/") {
-  if (!session?.user) {
-    return NextResponse.redirect(...);
-  }
-  return NextResponse.next();
-}
+if (nextUrl.pathname === "/") {
+  if (!session?.user) {
+    return NextResponse.redirect(...);
+  }
+  return NextResponse.next();
+}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 29ed517 and 444a377.

📒 Files selected for processing (1)
  • apps/app/src/middleware.ts (1 hunks)
🔇 Additional comments (5)
apps/app/src/middleware.ts (5)

1-3: Imports look well-defined.
All imports are relevant for authentication and middleware functionality. No issues identified.


22-24: Conditional check for unauthenticated access.
If a user is not authenticated and not on “/auth,” they get redirected correctly. No issues.


26-28: Redirecting authenticated users away from “/auth.”
Ensures users aren’t stuck on the sign-in page if already logged in. No concerns here.


40-44: i18n response handling is valid.
Appending the x-pathname header is useful for debugging or logging. No issues noted.


18-20:

Details

❓ Verification inconclusive

Confirm the usage of authMiddleware().
Currently, authMiddleware() is invoked without passing the request object. Ensure the function doesn’t require the request directly or any associated headers/cookies.


🏁 Script executed:

#!/bin/bash
# Checking the implementation of `authMiddleware` in the codebase to see if it expects request input.
fd 'auth.ts' --type f --exec cat {} | rg 'function authMiddleware\(' -A 5

Length of output: 75


I've attempted to locate the definition of authMiddleware by searching in auth.ts, but no matching implementation was found. This suggests that the function definition might be in a different file or follow a different structure. Before approving the usage, please verify that authMiddleware() was deliberately implemented to not require any parameters (such as the request object, headers, or cookies).

To assist further, please run the following shell script to search for the definition of authMiddleware across the entire repository:

Once you confirm its signature and usage, you can update the invocation in apps/app/src/middleware.ts accordingly if needed.

Please verify the implementation of authMiddleware() to ensure it doesn't need the request (or associated data).


🏁 Script executed:

#!/bin/bash
# Search for the definition of authMiddleware in the repository
rg -n "function authMiddleware\(" .

Length of output: 159


Action: Verify the signature of authMiddleware()

Our automated searches did not yield a definitive implementation of authMiddleware(). It’s possible that the function is defined as an arrow function or in another non-standard form. Please manually confirm that authMiddleware() is intentionally designed to be invoked without any parameters (like the request object, headers, or cookies). If the implementation expects any input, update the call in apps/app/src/middleware.ts accordingly.

To aid your verification, try running this command to search for all instances of authMiddleware using multiple patterns:

Review Location

  • File: apps/app/src/middleware.ts, Lines: 18-20

🏁 Script executed:

#!/bin/bash
echo "Searching for function declaration..."
rg -n "function authMiddleware\(" .
echo "Searching for arrow function declaration..."
rg -n "const authMiddleware\s*=" .

Length of output: 378


Action Required: Verify authMiddleware() Signature

Our automated searches couldn’t locate an explicit definition for authMiddleware, whether defined as a traditional function or an arrow function. This lack of evidence necessitates a manual verification to confirm that the function is intentionally implemented without requiring the request object (or headers/cookies).

Next Steps:

  • Manual Confirmation:
    Please inspect the actual implementation of authMiddleware() to ensure it does not expect any parameters. If it should accept the request (or related metadata), adjust its invocation in apps/app/src/middleware.ts accordingly.

  • Review Location:

    • File: apps/app/src/middleware.ts
    • Lines: 18-20

Once you have confirmed the intended design, update the code if necessary.

…arity

- Updated middleware to enhance I18n integration and simplified session handling.
- Refactored layout component for consistent formatting.
- Adjusted RootPage redirection logic to ensure proper user flow.
- Modified Google and Magic Link sign-in components to redirect to "/setup" after authentication.
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.

1 participant