-
Notifications
You must be signed in to change notification settings - Fork 0
/
no-middleware.tsx
38 lines (28 loc) · 960 Bytes
/
no-middleware.tsx
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
import { NextRequest, NextResponse } from "next/server"
import { LANGS } from "./lib/locales"
const parser = require("accept-language-parser")
const defaultLocale = "fr"
export default function middleware(request: NextRequest) {
const pathname = request.nextUrl.pathname
const pathnameIsMissingLocale = LANGS.every(
(locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
)
if (pathnameIsMissingLocale) {
const locale =
parser.pick(LANGS, request.headers.get("Accept-Language"), {
loose: true,
}) || defaultLocale
const searchParams = request.nextUrl.searchParams.toString()
const url = new URL(
`/${locale}/${pathname}${searchParams ? `?${searchParams}` : ""}`,
request.url
)
return NextResponse.redirect(url)
}
}
export const config = {
matcher: [
// Skip all internal paths (_next), api and assets
"/((?!(?:_next|api|assets|favicon.ico)).*)",
],
}