-
Notifications
You must be signed in to change notification settings - Fork 4
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
base: main
Are you sure you want to change the base?
Conversation
@bitfalt is attempting to deploy a commit to the MindVault Team on Vercel. A member of the Team first needs to authorize it. |
WalkthroughThe 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 Changes
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
Poem
✨ Finishing Touches
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
✅ Deploy Preview for lucent-florentine-971919 ready!
To edit notification comments on pull requests, go to your Netlify site configuration. |
There was a problem hiding this 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
📒 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/apiLength 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 theapps/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.
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
@evgongora just tried to fix the translations using headers and modifying the middleware. Please deploy the changes on Production to see if it worked :( |
There was a problem hiding this 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
📒 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.
apps/web/src/middleware.ts
Outdated
const addLanguagePrefix = (url: string): string => { | ||
if (urlLanguage || SUPPORTED_LANGUAGES.some(lang => url.startsWith(`/${lang}/`))) { | ||
return url | ||
} | ||
return `/${preferredLanguage}${url.startsWith('/') ? url : `/${url}`}` | ||
} |
There was a problem hiding this comment.
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.
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}`}` | |
} |
function getLanguageFromPath(pathname: string): string | null { | ||
const firstSegment = pathname.split('/')[1] | ||
return SUPPORTED_LANGUAGES.includes(firstSegment) ? firstSegment : null | ||
} |
There was a problem hiding this comment.
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.
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' |
There was a problem hiding this comment.
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.
import { headers } from 'next/headers' |
There was a problem hiding this 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
📒 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.
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