-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.js
57 lines (47 loc) · 2 KB
/
middleware.js
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
50
51
52
53
54
55
56
57
import { NextResponse } from "next/server"
import getAvailableLocales, { getFallbackLocale } from "./app/i18n/settings"
import { match } from "@formatjs/intl-localematcher"
import Negotiator from "negotiator"
async function getLocale(request, locales) {
const fallbackLng = await getFallbackLocale()
const headers = new Headers(request.headers)
const acceptLanguage = headers.get("accept-language")
if (acceptLanguage) {
headers.set("accept-language", acceptLanguage.replaceAll("_", "-"))
}
const headersObject = Object.fromEntries(headers.entries())
const languages = new Negotiator({ headers: headersObject }).languages()
return match(languages, locales, fallbackLng)
}
export async function middleware(request) {
// Check if there is any supported locale in the pathname
const pathname = request.nextUrl.pathname
const locales = await getAvailableLocales()
const pathnameIsMissingLocale = locales.every(
locale => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
)
//go to home in browser language if pathname & locale is missing
if (pathname === "/") {
const locale = await getLocale(request, locales)
return NextResponse.redirect(new URL(`/${locale}/home`, request.url))
}
//go to the specific locale home if there is no pathname but the locale is set
if (
pathname.split("/").length === 2 &&
locales.includes(pathname.split("/")[1])
) {
return NextResponse.redirect(
new URL(`/${pathname.split("/")[1]}/home`, request.url)
)
}
//go to pathname in browser language if locale is missing but pathname is set
if (pathnameIsMissingLocale) {
const locale = await getLocale(request, locales)
// e.g. incoming request is /products
// The new URL is now /en/products
// return NextResponse.redirect(new URL(`/${locale}/${pathname}`, request.url))
}
}
export const config = {
matcher: ["/((?!.*\\.|_next|api\\/).*)"]
}