Skip to content

Commit

Permalink
fix not found handling
Browse files Browse the repository at this point in the history
  • Loading branch information
PxlSyl authored and PxlSyl committed Jun 18, 2024
1 parent b4cbdab commit ad2114c
Showing 1 changed file with 25 additions and 18 deletions.
43 changes: 25 additions & 18 deletions middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,19 @@ import { locales } from 'app/[locale]/i18n/settings'
import { fallbackLng } from 'app/[locale]/i18n/locales'

export function middleware(request: NextRequest) {
// Check if there is any supported locale in the pathname
const pathname = request.nextUrl.pathname
const pathnameIsMissingLocale = locales.every(
(locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
)

if (pathnameIsMissingLocale) {
return NextResponse.rewrite(new URL(`/${fallbackLng}${pathname}`, request.url))
}

// Check if there is any supported locale in the pathname
const isDefaultLocalePath = pathname.startsWith(`/${fallbackLng}/`) || pathname === `/${fallbackLng}`

// Check if the default locale is in the pathname
if (pathname.startsWith(`/${fallbackLng}/`) || pathname === `/${fallbackLng}`) {
// e.g. incoming request is /en/about
// The new URL is now /about
if (isDefaultLocalePath) {
return NextResponse.redirect(
new URL(
pathname.replace(`/${fallbackLng}`, pathname === `/${fallbackLng}` ? '/' : ''),
Expand All @@ -18,23 +24,24 @@ export function middleware(request: NextRequest) {
)
}

const pathnameIsMissingLocale = locales.every(
(locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
)
// Ensure the root paths for locales (e.g., /fr, /en) are valid and do not return not found
const isLocaleRootPath = locales.some(locale => pathname === `/${locale}`)

if (pathnameIsMissingLocale) {
// We are on the default locale
// Rewrite so Next.js understands
if (isLocaleRootPath) {
return NextResponse.next()
}

// e.g. incoming request is /about
// Tell Next.js it should pretend it's /en/about
return NextResponse.rewrite(new URL(`/${fallbackLng}${pathname}`, request.url))
// Check if the path is unmatched (i.e., not found)
const isUnmatchedPath = !locales.some(locale => pathname.startsWith(`/${locale}/`))

if (isUnmatchedPath) {
// Rewrite to the custom not found page
return NextResponse.rewrite(new URL(`/${fallbackLng}/not-found`, request.url))
}

return NextResponse.next()
}

export const config = {
// Do not run the middleware on the following paths
// prettier-ignore
matcher:
'/((?!api|static|track|data|css|scripts|.*\\..*|_next).*|sitemap.xml)',
matcher: '/((?!api|static|track|data|css|scripts|.*\\..*|_next).*|sitemap.xml)',
}

0 comments on commit ad2114c

Please sign in to comment.