-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
middleware.ts
89 lines (79 loc) · 2.38 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import {
defaultLocale,
i18n,
isNotStarted,
isReviewed,
locales,
} from "./i18n/i18n.config";
import { match as matchLocale } from "@formatjs/intl-localematcher";
//@ts-ignore
import Negotiator from "negotiator";
function combinePath(request: NextRequest, path: string): boolean {
return request.nextUrl.pathname.startsWith(`/${getLocale(request)}/${path}`);
}
function formatSpecialValues(value: string) {
return value;
}
function getLocale(request: NextRequest): string {
const negotiatorHeaders: Record<string, string> = {};
request.headers.forEach((value, key) => (negotiatorHeaders[key] = formatSpecialValues(value)));
const locales: string[] = i18n.locales.map((locale) =>
locale?.replaceAll("_", "-"),
);
let languages = new Negotiator({ headers: negotiatorHeaders }).languages(
locales,
);
return matchLocale(languages, locales, i18n.defaultLocale);
}
const excludedPaths = [
"api",
"_next/static",
"_next/image",
"/favicon.ico",
"/manifest.json",
"/_next/webpack-hmr",
"/opengraph-image",
"/twitter-image",
];
export function middleware(request: NextRequest) {
let { pathname } = request.nextUrl;
// NOTE: Check if any of the excluded paths are in the request
if (excludedPaths.some((path) => pathname.includes(path))) {
return;
}
try {
const pathnameHasLocale = locales
.map((locale) => locale.replaceAll("_", "-"))
.some(
(locale) =>
pathname.startsWith(`/${locale}`) || pathname === `/${locale}`,
);
let locale = getLocale(request);
if (pathnameHasLocale) {
const selectedLocale = pathname.split("/")[1];
if (isNotStarted(selectedLocale || "")) {
console.log(
`Locale ${selectedLocale} is not reviewed, redirecting to en`,
);
pathname = pathname.replace(`/${selectedLocale}`, "");
locale = defaultLocale;
} else {
return;
}
}
if (isNotStarted(locale || "")) {
console.log(`Locale ${locale} is not reviewed, redirecting to en`);
pathname = pathname.replace(`/${locale}`, "");
locale = defaultLocale;
}
request.nextUrl.pathname = `/${locale}${pathname}`;
return NextResponse.redirect(request.nextUrl);
} catch (e) {
console.error(e);
}
}
export const config = {
matcher: ["/((?!_next).*)"],
};