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

add: weglot header to middleware #159

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

Conversation

bitfalt
Copy link
Member

@bitfalt bitfalt commented Feb 21, 2025

This PR adds the weglot header to the middleware, so that the website can be translated properly.

Note: This is all testing that must be done in the deploy, since weglot uses DNS to translate.

Summary by CodeRabbit

  • New Features
    • Enhanced language support ensures responses reflect users' preferred languages, defaulting to English when no valid preference is provided.
    • Improved consistency in language handling across public routes, authentication flows, and API interactions, contributing to a smoother user experience.
    • Added support for multiple languages: English, French, Spanish, and German.
    • Automatic redirection to language-prefixed URLs for better accessibility.
    • Public paths can now be accessed without requiring a language prefix.

Copy link

vercel bot commented Feb 21, 2025

@bitfalt is attempting to deploy a commit to the MindVault Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Feb 21, 2025

Walkthrough

The changes enhance the middleware to support language preference handling. A constant is renamed and several helper functions are added to extract and validate the primary language from the Accept-Language header, defaulting to English. The middleware updates responses to include a Weglot-Language-Preference header, modifies logic for public paths, and ensures API routes incorporate the preferred language in request headers.

Changes

File(s) Change Summary
apps/web/src/middleware.ts - Renamed publicPaths to PUBLIC_PATHS.
- Added SUPPORTED_LANGUAGES constant.
- Introduced getPrimaryLanguage, addLanguagePrefix, isPublicPath, and getLanguageFromPath helper functions.
- Updated middleware to determine preferred language and include Weglot-Language-Preference header in responses.
- Modified routing logic for public paths and session token handling.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Middleware
    participant LanguageHelper as getPrimaryLanguage

    Client->>Middleware: Send request with Accept-Language header
    Middleware->>LanguageHelper: Parse header for primary language
    LanguageHelper-->>Middleware: Return primary language (default: "en")
    Middleware-->>Client: Respond with Weglot-Language-Preference header set
Loading

Poem

I'm a rabbit with ears so keen,
Hopping through changes on my screen,
With languages set in header flight,
My middleware now feels just right.
Coding carrots make my day bright!
🐰🥕

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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.

Copy link

netlify bot commented Feb 21, 2025

Deploy Preview for lucent-florentine-971919 ready!

Name Link
🔨 Latest commit aab6f66
🔍 Latest deploy log https://app.netlify.com/sites/lucent-florentine-971919/deploys/67b93528a5dfdf0008c6cf3c
😎 Deploy Preview https://deploy-preview-159--lucent-florentine-971919.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

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: 1

🧹 Nitpick comments (2)
apps/web/src/middleware.ts (2)

35-37: Consider using ISO 639-1 language code constants.

While the language codes are correct, consider defining them as named constants to improve maintainability and prevent typos.

-const SUPPORTED_LANGUAGES = ['en', 'fr', 'es', 'de'] // Add all languages you support
+const SUPPORTED_LANGUAGES = {
+  ENGLISH: 'en',
+  FRENCH: 'fr',
+  SPANISH: 'es',
+  GERMAN: 'de'
+} as const;
+
+type SupportedLanguage = typeof SUPPORTED_LANGUAGES[keyof typeof SUPPORTED_LANGUAGES];

81-90: Consider caching language preference.

The language preference is determined for every request. Consider caching it in a cookie to improve performance and maintain consistency across requests.

+  // Check for cached language preference
+  const cachedLanguage = request.cookies.get('preferred_language')?.value;
+  const preferredLanguage = cachedLanguage || getPrimaryLanguage(acceptLanguage);
+
   // Create response object that we'll modify
   let response = NextResponse.next()
 
   // Set Weglot language header
   response.headers.set('Weglot-Language-Preference', preferredLanguage)
+  
+  // Cache the language preference if not already cached
+  if (!cachedLanguage) {
+    response.cookies.set('preferred_language', preferredLanguage, {
+      maxAge: 30 * 24 * 60 * 60, // 30 days
+      path: '/',
+      sameSite: 'lax'
+    });
+  }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0f43d17 and 9d63e21.

📒 Files selected for processing (1)
  • apps/web/src/middleware.ts (4 hunks)
🔇 Additional comments (2)
apps/web/src/middleware.ts (2)

154-156: LGTM: Matcher configuration is correct.

The matcher configuration correctly excludes static assets and images from middleware processing, which is important for performance.


129-134:

❓ Verification inconclusive

Consider adding language validation middleware for API routes.

For API routes, consider validating that the client's requested language matches the supported languages to prevent potential issues with unsupported languages.


🏁 Script executed:

#!/bin/bash
# Check if there are any API endpoints that might need language-specific handling
rg -l "x-preferred-language" ./apps/web/src/app/api

Length of output: 51


Language Validation Middleware for API Routes

The middleware currently sets the "x-preferred-language" header on API requests, but our search in the apps/web/src/app/api directory did not reveal any instance where this header is used for validating the language. Please verify whether the client-requested language is validated elsewhere. If not, consider implementing a validation middleware that checks against the list of supported languages to avoid potential issues with unsupported language inputs.

  • Action: Confirm if any language validation already exists in your API routes.
  • Suggestion: If missing, add middleware that validates the preferredLanguage before processing API requests.

Copy link

vercel bot commented Feb 21, 2025

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

Name Status Preview Comments Updated (UTC)
miniapp-monorepo-web ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 22, 2025 2:56am

@bitfalt
Copy link
Member Author

bitfalt commented Feb 22, 2025

@evgongora just tried to fix the translations using headers and modifying the middleware. Please deploy the changes on Production to see if it worked :(

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: 3

🧹 Nitpick comments (2)
apps/web/src/middleware.ts (2)

35-36: Enhance language configuration maintainability.

Consider using an enum or object for better type safety and maintainability of supported languages.

-const SUPPORTED_LANGUAGES = ['en', 'fr', 'es', 'de']
+enum SupportedLanguage {
+  ENGLISH = 'en',
+  FRENCH = 'fr',
+  SPANISH = 'es',
+  GERMAN = 'de'
+}
+
+const SUPPORTED_LANGUAGES = Object.values(SupportedLanguage)

77-85: Optimize public path checking.

The current implementation rechecks language prefixes for every path comparison. Consider caching the path without language prefix.

 function isPublicPath(path: string): boolean {
   // Remove language prefix if it exists
-  const pathWithoutLang = SUPPORTED_LANGUAGES.some(lang => path.startsWith(`/${lang}/`))
-    ? path.substring(3) // Remove /{lang}/ prefix
-    : path
+  const langPrefix = SUPPORTED_LANGUAGES.find(lang => path.startsWith(`/${lang}/`))
+  const pathWithoutLang = langPrefix ? path.substring(3) : path
 
   return PUBLIC_PATHS.some(publicPath => pathWithoutLang.startsWith(publicPath))
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9d63e21 and 59f1fd6.

📒 Files selected for processing (1)
  • apps/web/src/middleware.ts (4 hunks)
🔇 Additional comments (3)
apps/web/src/middleware.ts (3)

39-47: Enhance language parsing robustness.

The language parsing logic could be more robust to handle edge cases and malformed inputs.


105-106: LGTM! Weglot header implementation.

The Weglot language header is correctly set for translation services.


189-194: LGTM! Matcher configuration.

The matcher configuration correctly handles both language-prefixed and non-prefixed routes.

Comment on lines 109 to 114
const addLanguagePrefix = (url: string): string => {
if (urlLanguage || SUPPORTED_LANGUAGES.some(lang => url.startsWith(`/${lang}/`))) {
return url
}
return `/${preferredLanguage}${url.startsWith('/') ? url : `/${url}`}`
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add URL validation in language prefix function.

The function should validate URLs before manipulation to prevent errors with malformed URLs.

 const addLanguagePrefix = (url: string): string => {
+  if (!url) return `/${preferredLanguage}`
+
   if (urlLanguage || SUPPORTED_LANGUAGES.some(lang => url.startsWith(`/${lang}/`))) {
     return url
   }
   return `/${preferredLanguage}${url.startsWith('/') ? url : `/${url}`}`
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const addLanguagePrefix = (url: string): string => {
if (urlLanguage || SUPPORTED_LANGUAGES.some(lang => url.startsWith(`/${lang}/`))) {
return url
}
return `/${preferredLanguage}${url.startsWith('/') ? url : `/${url}`}`
}
const addLanguagePrefix = (url: string): string => {
if (!url) return `/${preferredLanguage}`
if (urlLanguage || SUPPORTED_LANGUAGES.some(lang => url.startsWith(`/${lang}/`))) {
return url
}
return `/${preferredLanguage}${url.startsWith('/') ? url : `/${url}`}`
}

Comment on lines +88 to +91
function getLanguageFromPath(pathname: string): string | null {
const firstSegment = pathname.split('/')[1]
return SUPPORTED_LANGUAGES.includes(firstSegment) ? firstSegment : null
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add validation for malformed paths.

The function should handle edge cases like empty paths or paths with multiple segments.

 function getLanguageFromPath(pathname: string): string | null {
+  if (!pathname || pathname === '/') return null
+
   const firstSegment = pathname.split('/')[1]
   return SUPPORTED_LANGUAGES.includes(firstSegment) ? firstSegment : null
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function getLanguageFromPath(pathname: string): string | null {
const firstSegment = pathname.split('/')[1]
return SUPPORTED_LANGUAGES.includes(firstSegment) ? firstSegment : null
}
function getLanguageFromPath(pathname: string): string | null {
if (!pathname || pathname === '/') return null
const firstSegment = pathname.split('/')[1]
return SUPPORTED_LANGUAGES.includes(firstSegment) ? firstSegment : null
}

@@ -1,9 +1,10 @@
import { jwtVerify } from "jose";
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { headers } from 'next/headers'
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove unused import.

The headers import from 'next/headers' is not used in the code.

-import { headers } from 'next/headers'
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import { headers } from 'next/headers'

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

35-36: Make SUPPORTED_LANGUAGES more type-safe.

Consider using an enum or const object for better type safety and maintainability.

-const SUPPORTED_LANGUAGES = ['en', 'fr', 'es', 'de']
+enum SupportedLanguage {
+  ENGLISH = 'en',
+  FRENCH = 'fr',
+  SPANISH = 'es',
+  GERMAN = 'de'
+}
+const SUPPORTED_LANGUAGES = Object.values(SupportedLanguage)

96-111: Optimize path checking performance.

The current implementation checks paths twice. Consider using a Set for O(1) lookup and precomputing language-prefixed public paths.

+// Pre-compute language-prefixed public paths
+const PUBLIC_PATHS_SET = new Set([
+  ...PUBLIC_PATHS,
+  ...PUBLIC_PATHS.flatMap(path => 
+    SUPPORTED_LANGUAGES.map(lang => `/${lang}${path}`)
+  )
+]);
+
 function isPublicPath(path: string): boolean {
-  // First check if the path is directly in PUBLIC_PATHS
-  if (PUBLIC_PATHS.some(publicPath => path.startsWith(publicPath))) {
-    return true
-  }
-
-  // Then check if the path without language prefix is in PUBLIC_PATHS
-  for (const lang of SUPPORTED_LANGUAGES) {
-    if (path.startsWith(`/${lang}/`)) {
-      const pathWithoutLang = path.substring(3)
-      return PUBLIC_PATHS.some(publicPath => pathWithoutLang.startsWith(publicPath))
-    }
-  }
-
-  return false
+  return Array.from(PUBLIC_PATHS_SET).some(publicPath => path.startsWith(publicPath));
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 59f1fd6 and aab6f66.

📒 Files selected for processing (1)
  • apps/web/src/middleware.ts (3 hunks)
🔇 Additional comments (4)
apps/web/src/middleware.ts (4)

4-4: Remove unused import.

The headers import from 'next/headers' is not used in the code.

-import { headers } from 'next/headers'

39-47: Enhance language parsing robustness.

The language parsing logic could be more robust to handle edge cases and malformed inputs.


131-132: Well-implemented Weglot integration!

The consistent setting of the Weglot-Language-Preference header across all responses is a good practice for ensuring proper translation functionality.


211-216: Good configuration for language routing!

The matcher configuration correctly handles both language-prefixed and non-prefixed routes while appropriately excluding static assets.

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