Skip to content

fix: ensure middleware matchers evaluate default locale #2548

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

Closed
wants to merge 20 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
6bd9781
fix: ensure 2nd level middleware match respects locales
orinokai Jul 16, 2024
49fe9ad
fix: ensure adding locale is case sensitive
orinokai Jul 18, 2024
61ff711
test: update expect message
orinokai Jul 18, 2024
1160801
chore: destructure localizedPath
orinokai Jul 18, 2024
b010192
feat: allow for locale fallbacks when adding locale prefix
orinokai Jul 19, 2024
74e2502
fix: pass NextConfig in NextRequest (needed even though it's not in t…
orinokai Jul 22, 2024
71ed888
fix: headers need to be Node.js style plain object (even though Next …
orinokai Jul 23, 2024
935e621
test: assert that paths don't match with an invalid prefix
orinokai Jul 23, 2024
8d3972c
Merge branch 'main' into rs/frp-761-imiddleware-locale
orinokai Jul 23, 2024
878f022
test: remove only
orinokai Jul 23, 2024
dccecf9
chore: refactor for clarity
orinokai Jul 23, 2024
bfd3f54
chore: revert red herring
orinokai Jul 23, 2024
e1330fd
Merge branch 'rs/frp-761-imiddleware-locale' of github.com:netlify/ne…
orinokai Jul 23, 2024
1a5886e
test: fix incorrect locale test
orinokai Jul 23, 2024
8e691dc
chore: refactor NetlifyNextRequest type for clarity
orinokai Jul 23, 2024
a7620fd
test: fix faulty i18n test logic
orinokai Jul 23, 2024
da8215f
chore: refactor to remove normalizeLocalizedTarget
orinokai Jul 24, 2024
fb8d9ea
test: update failure messages for clarity
orinokai Jul 25, 2024
af173a6
chore: update e2e test command docs
orinokai Jul 25, 2024
2bd7c8f
Merge branch 'main' into rs/frp-761-imiddleware-locale
pieh Jul 26, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 2 additions & 54 deletions edge-runtime/lib/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,7 @@ import { updateModifiedHeaders } from './headers.ts'
import type { StructuredLogger } from './logging.ts'
import { addMiddlewareHeaders, isMiddlewareRequest, isMiddlewareResponse } from './middleware.ts'
import { NetlifyNextRequest } from './next-request.ts'
import {
addBasePath,
normalizeDataUrl,
normalizeLocalePath,
normalizeTrailingSlash,
relativizeURL,
} from './util.ts'
import { normalizeDataUrl, normalizeTrailingSlash, relativizeURL } from './util.ts'

export interface FetchEventResult {
response: Response
Expand Down Expand Up @@ -187,26 +181,12 @@ export const buildResponse = async ({
// respect trailing slash rules to prevent 308s
rewriteUrl.pathname = normalizeTrailingSlash(rewriteUrl.pathname, nextConfig?.trailingSlash)

const target = normalizeLocalizedTarget({ target: rewriteUrl.toString(), request, nextConfig })
if (target === request.url) {
logger.withFields({ rewrite_url: rewrite }).debug('Rewrite url is same as original url')
return
}
const target = rewriteUrl.toString()
res.headers.set('x-middleware-rewrite', relativeUrl)
request.headers.set('x-middleware-rewrite', target)
return addMiddlewareHeaders(context.rewrite(target), res)
}

// If we are redirecting a request that had a locale in the URL, we need to add it back in
if (redirect && locale) {
redirect = normalizeLocalizedTarget({ target: redirect, request, nextConfig })
if (redirect === request.url) {
logger.withFields({ rewrite_url: rewrite }).debug('Rewrite url is same as original url')
return
}
res.headers.set('location', redirect)
}

// Data requests shouldn't automatically redirect in the browser (they might be HTML pages): they're handled by the router
if (redirect && isDataReq) {
res.headers.delete('location')
Expand All @@ -226,35 +206,3 @@ export const buildResponse = async ({

return res
}

/**
* Normalizes the locale in a URL.
*/
function normalizeLocalizedTarget({
target,
request,
nextConfig,
locale,
}: {
target: string
request: Request
nextConfig?: NetlifyNextRequest['nextConfig']
locale?: string
}) {
const targetUrl = new URL(target, request.url)
const normalizedTarget = normalizeLocalePath(targetUrl.pathname, nextConfig?.i18n?.locales)
const targetPathname = normalizedTarget.pathname
const targetLocale = normalizedTarget.detectedLocale ?? locale

if (
targetLocale &&
!targetPathname.startsWith(`/api/`) &&
!targetPathname.startsWith(`/_next/static/`)
) {
targetUrl.pathname =
addBasePath(`/${targetLocale}${targetPathname}`, nextConfig?.basePath) || `/`
} else {
targetUrl.pathname = addBasePath(targetPathname, nextConfig?.basePath) || `/`
}
return targetUrl.toString()
}
3 changes: 2 additions & 1 deletion edge-runtime/lib/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ export const addLocale = (path: string, locale?: string) => {
locale &&
path.toLowerCase() !== `/${locale.toLowerCase()}` &&
!path.toLowerCase().startsWith(`/${locale.toLowerCase()}/`) &&
!path.toLowerCase().startsWith(`/${locale.toLowerCase()}-`)
!path.startsWith(`/api/`) &&
!path.startsWith(`/_next/static/`)
) {
return `/${locale}${path}`
}
Expand Down
Loading