-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
49 lines (42 loc) · 1.35 KB
/
middleware.ts
File metadata and controls
49 lines (42 loc) · 1.35 KB
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
41
42
43
44
45
46
47
48
49
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
import { i18n } from './i18n-config'
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(`/${i18n.defaultLocale}/`) ||
pathname === `/${i18n.defaultLocale}`
) {
// e.g. incoming request is /en/about
// The new URL is now /about
return NextResponse.redirect(
new URL(
pathname.replace(
`/${i18n.defaultLocale}`,
pathname === `/${i18n.defaultLocale}` ? '/' : ''
),
request.url
)
)
}
const pathnameIsMissingLocale = i18n.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(`/${i18n.defaultLocale}${pathname}`, request.url)
)
}
}
export const config = {
// Matcher ignoring `/_next/` and `/api/`
matcher: [
'/((?!api|_next/static|_next/image|favicon.ico|admin|logo.svg|bricks-preview-images|preview).*)',
],
}