Skip to content

Conversation

RomanBobrovskiy
Copy link
Collaborator

@RomanBobrovskiy RomanBobrovskiy commented Feb 20, 2025

Add Next.js Rewrites Support

This PR adds support for Next.js rewrites functionality, allowing the application to internally rewrite URLs without changing the URL in the browser.

Key Changes

1. Build Process Updates (src/build/next.ts)

  • Added getRewritesConfig function to parse Next.js rewrite rules from manifest
  • Renamed getNextCachedRoutesMatchers to getNextCachedRoutesConfig
  • Updated return type to include both cached routes and rewrites configuration
  • Handles both array and object-based rewrite configurations:
    • beforeFiles
    • afterFiles
    • fallback

2. Type Definitions (src/types/index.ts)

  • Added new types for rewrite functionality:
export type NextRewriteEntity = {
source: string
destination: string
regex: string
has?: RouteHas[]
}
export type NextRewrites = NextRewriteEntity[]
  • Imported RouteHas from Next.js for type safety

3. Lambda@Edge Handler Updates (src/lambdas/originRequest.ts)

  • Added new validation functions:
    • validateRouteHasMatch: Validates rewrite conditions
      • Header matching
      • Query parameter validation
      • Cookie checking
    • validateRewriteRoute: Processes rewrite rules against incoming requests
  • Updated handler to process rewrites before request handling

4. Infrastructure Updates

  • Modified OriginRequestLambdaEdge construct:
    • Added rewritesConfig prop
    • Updated environment variables to include rewrites
  • Updated NextCloudfrontStack:
    • Added rewrite configuration propagation
    • Maintained backward compatibility

Implementation Details

Rewrite Rule Processing

  • Supports all Next.js rewrite conditions:
    • Headers
    • Query parameters
    • Cookies
    • Path regex matching
  • Maintains original rewrite order from Next.js config
  • Integrates seamlessly with existing caching mechanism

@RomanBobrovskiy RomanBobrovskiy merged commit 6f63c97 into main Feb 24, 2025
1 check 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