Newer
Older
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
58
59
60
61
62
63
64
import { NextResponse } from "next/server";
import { headers } from "next/headers";
import { getToken } from "next-auth/jwt";
import { match } from "@formatjs/intl-localematcher";
import Negotiator from "negotiator";
const locales = ["en", "de"];
function getLocale(request, current) {
/*
* If the user has a locale in its referer, keep it.
*/
if (current) return current;
/*
* Read the accept-language header and match it to a provided locale
*/
const headers = {
"accept-language": request.headers.get("accept-language"),
};
let languages = new Negotiator({ headers }).languages();
let defaultLocale = "en";
let lang = match(languages, locales, defaultLocale);
return lang;
}
export async function middleware(request) {
const token = await getToken({ req: request });
const { pathname, search } = request.nextUrl;
const current = headers().get("next-url");
const callback = decodeURIComponent(request.nextUrl.search).split("=")[1];
const pathnameHasLocale = locales.some(
(locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`,
);
const refererHasLocale = locales.some(
(locale) =>
current &&
(current.startsWith(`/${locale}/`) || current === `/${locale}`),
);
const locale = pathnameHasLocale
? pathname.substr(1, 2)
: refererHasLocale
? getLocale(request, current.substr(1, 2))
: getLocale(request, "");
let forward = pathname;
if (!pathnameHasLocale) {
request.nextUrl.pathname = `/${locale}${pathname}`;
return Response.redirect(request.nextUrl);
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!api|static|.*\\..*|_next|favicon.ico|robots.txt).*)"],
};