Skip to content
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

2.5.0 - Next 13 compatibility #257

Merged
merged 2 commits into from
Jan 9, 2025

Conversation

Yoshify
Copy link
Collaborator

@Yoshify Yoshify commented Jan 9, 2025

Explain your changes

This PR contains some minor fixes for the upcoming 2.5.0 release to improve compatibility with Next 13.

  • The bailout for internal Kinde paths (like login) has been moved to the very top of the middleware. It has also been expanded to include other paths like kinde_callback and register. This was the source of a redirect loop in Next 13.
  • The prefetch check for login, logout and register links has been reworked to use the headers() function instead of directly accessing headers on a NextRequest object. In Next 13, the headers on a NextRequest are an object, but in 14 onwards they're a map. The existing logic treated it like a map and thus caused breakages in Next 13 (TypeError: e.headers.get is not a function). Instead, the prefetch check now expects the result of headers() as it's a stable and consistent API for working with headers in all versions of Next from 13 on.

Checklist

🛟 If you need help, consider asking for advice over in the Kinde community.

prevents certain edge cases (primarily in Next13) that can cause redirect loops
The current logic assumes headers is a map (which is true for Next >14), but in Next 13 the request headers are an object. This causes errors on Next 13 like so: TypeError: e.headers.get is not a function

Given the headers function was added in 13, we should resort to using that instead as it provides a stable and consistent API for accessing headers in all versions greater than Next 13.
Copy link
Contributor

coderabbitai bot commented Jan 9, 2025

Walkthrough

The pull request introduces changes to authentication middleware and request handling across multiple files. The modifications primarily focus on refining route handling, pre-fetch request detection, and authentication flow. Key changes include adding new constants for callback and registration pages in the authentication middleware, updating how pre-fetch checks are performed in login, logout, and register handlers, and simplifying the isPreFetch utility function to work directly with headers.

Changes

File Change Summary
src/authMiddleware/authMiddleware.ts Added new constants callbackPage and registerPage for specific authentication routes
src/handlers/login.ts Updated pre-fetch check to use headers() instead of routerClient.req
src/handlers/logout.ts Modified pre-fetch detection to use headers() from next/headers
src/handlers/register.ts Replaced routerClient.req with await headers() for pre-fetch check
src/utils/isPreFetch.ts Changed function signature from NextRequest to ReadonlyHeaders and simplified header checking
src/utils/isPreFetch.test.ts Refactored tests to use mockHeaders instead of mockNextRequest

Sequence Diagram

sequenceDiagram
    participant Client
    participant AuthMiddleware
    participant Handler
    participant Headers

    Client->>AuthMiddleware: Request
    AuthMiddleware->>AuthMiddleware: Check public paths
    alt Is public path
        AuthMiddleware-->>Client: Allow access
    else Not public path
        AuthMiddleware->>Handler: Validate authentication
        Handler->>Headers: Get headers
        Headers->>Handler: Check pre-fetch
        alt Is pre-fetch
            Handler-->>Client: Return null
        else Not pre-fetch
            Handler->>Client: Process request
        end
    end
Loading

Possibly related PRs

Suggested reviewers

  • DanielRivers
  • coel
  • peterphanouvong

Finishing Touches

  • 📝 Generate Docstrings

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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. (Beta)
  • @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.

@Yoshify Yoshify requested review from DanielRivers and removed request for DaveOrDead and peterphanouvong January 9, 2025 03:12
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 (3)
src/utils/isPreFetch.ts (1)

1-1: Consider using the public Next.js types package

Instead of importing from internal Next.js paths, consider using the public @types/next package for better stability across Next.js versions.

-import { ReadonlyHeaders } from "next/dist/server/web/spec-extension/adapters/headers";
+import { ReadonlyHeaders } from '@types/next';
src/handlers/logout.ts (1)

1-1: Add missing semicolon for consistency

While the implementation correctly mirrors other handlers, there's a minor inconsistency in the return statement.

  if (isPreFetch(heads)) {
-    return null
+    return null;
  }

Also applies to: 11-12

src/authMiddleware/authMiddleware.ts (1)

22-24: LGTM! Early bailout implementation.

The early bailout for internal Kinde paths effectively prevents redirect loops in Next.js 13.

However, consider adding debug logging for consistency with the rest of the middleware:

  if(loginPage == pathname || callbackPage == pathname || registerPage == pathname) {
+   if(config.isDebugMode) {
+     console.log('authMiddleware: internal Kinde path, skipping auth check')
+   }
    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 63601d9 and a58a762.

📒 Files selected for processing (6)
  • src/authMiddleware/authMiddleware.ts (2 hunks)
  • src/handlers/login.ts (2 hunks)
  • src/handlers/logout.ts (2 hunks)
  • src/handlers/register.ts (2 hunks)
  • src/utils/isPreFetch.test.ts (1 hunks)
  • src/utils/isPreFetch.ts (1 hunks)
🔇 Additional comments (7)
src/utils/isPreFetch.ts (1)

3-8: LGTM! Clean and robust prefetch detection

The implementation correctly handles all common prefetch header variations and the type change to ReadonlyHeaders makes the function more precise.

src/handlers/login.ts (1)

1-1: LGTM! Robust header handling for Next.js compatibility

The change to use headers() function instead of accessing headers directly from the request object ensures compatibility with both Next.js 13 and 14.

Also applies to: 10-12

src/handlers/register.ts (1)

1-1: LGTM! Consistent implementation with other handlers

The changes mirror the login handler implementation, maintaining consistency across the codebase.

Also applies to: 10-12

src/utils/isPreFetch.test.ts (2)

8-10: LGTM! Clean helper function implementation.

The mockHeaders helper function correctly creates a ReadonlyHeaders object, which aligns with Next.js 13's header handling.


13-14: LGTM! Comprehensive test coverage.

The test cases thoroughly cover all prefetch scenarios:

  • Purpose header
  • X-Purpose header
  • X-Moz header
  • No prefetch headers
  • Different header values

Also applies to: 18-19, 23-24, 28-29, 33-38

src/authMiddleware/authMiddleware.ts (2)

19-21: LGTM! Clear constant definitions.

The new constants for callback and register pages improve code maintainability.


37-37: Verify the impact of simplified public path check.

The simplified public path check might affect routes that were previously handled differently.

Let's verify if any routes are impacted:

✅ Verification successful

Simplified public path check is safe to use

The change to use startsWith for public paths is appropriate as it only affects completely public resources (like /_next and favicon.ico). Protected routes use separate protection mechanisms through protectPage and protectApi functions that handle authentication and authorization independently.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for route definitions and middleware usage
rg -A 3 'publicPaths.*=' || \
rg -A 3 'withAuth\(' || \
rg -A 3 'NextResponse\.redirect.*loginPage'

Length of output: 796


Script:

#!/bin/bash
# Check git history for the file
git log -L :publicPaths:src/authMiddleware/authMiddleware.ts

# Search for route handlers
fd -e ts -e js -e tsx -e jsx --exec rg -l 'export.*handler|createHandler|route\.ts$|route\.js$|api.*handler'

Length of output: 158


Script:

#!/bin/bash
# Check handler files content
echo "=== src/server/index.js ==="
cat src/server/index.js
echo -e "\n=== src/handlers/protect.js ==="
cat src/handlers/protect.js

# Search for path-related configurations
rg -g '!*.{lock,md}' -A 3 'path.*=.*["\']/'

Length of output: 4684

@DanielRivers DanielRivers merged commit 9bfade8 into kinde-oss:main Jan 9, 2025
2 checks passed
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.

2 participants