-
-
Notifications
You must be signed in to change notification settings - Fork 32
/
middleware.ts
40 lines (34 loc) · 1.29 KB
/
middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { NextResponse, NextRequest } from 'next/server'
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
// 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
return NextResponse.redirect(
new URL(
pathname.replace(`/${fallbackLng}`, pathname === `/${fallbackLng}` ? '/' : ''),
request.url
)
)
}
const pathnameIsMissingLocale = locales.every(
(locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
)
if (pathnameIsMissingLocale) {
// We are on the default locale
// Rewrite so Next.js understands
// 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))
}
}
export const config = {
// Do not run the middleware on the following paths
// prettier-ignore
matcher:
'/((?!api|static|track|data|css|scripts|.*\\..*|_next).*|sitemap.xml)',
}