-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
68 lines (45 loc) · 1.91 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { match } from "@formatjs/intl-localematcher";
import Negotiator from "negotiator";
export const runtime = 'experimental-edge' // 'nodejs' (default) | 'edge'
const i18n = { locales : ['en', 'hr'], defaultLocale : 'hr' }
function getLocale(request: NextRequest, i18n : {locales : string[], defaultLocale : string}): string {
const { locales, defaultLocale } = i18n;
const negotiatorHeaders: Record<string, string> = {};
request.headers.forEach((value, key) => (negotiatorHeaders[key] = value));
const languages = new Negotiator({ headers: negotiatorHeaders }).languages(
locales
);
console.log("languages are " + languages)
return match(languages, locales, defaultLocale);
}
export function middleware(request: NextRequest) {
let response;
let nextLocale;
const { locales, defaultLocale } = i18n;
const pathname = request.nextUrl.pathname;
const pathLocale = locales.find(
(locale : string) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
);
if (pathLocale) {
nextLocale = pathLocale;
} else {
const isFirstVisit = !request.cookies.has("NEXT_LOCALE");
const locale = isFirstVisit ? getLocale(request, i18n) : request.cookies.get("NEXT_LOCALE")?.value || defaultLocale;
let newPath = `${locale}${pathname}`;
if (request.nextUrl.search) newPath += request.nextUrl.search;
response =
locale === defaultLocale
? NextResponse.rewrite(new URL(newPath, request.url))
: NextResponse.redirect(new URL(newPath, request.url));
nextLocale = locale;
}
if (!response) response = NextResponse.next();
if (nextLocale) response.cookies.set("NEXT_LOCALE", nextLocale);
response.headers.set("x-url", request.url);
return response;
}
export const config = {
matcher: "/((?!api|_next/static|_next/image|images|img/|favicon.ico).*)",
};