-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
63 lines (50 loc) · 1.53 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
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { i18n } from "./i18n-config";
import { baseUrlByLocale } from "./i18n-server";
function geRequestHost(request: NextRequest) {
return request.headers.get("x-forwarded-host") || request.headers.get("host");
}
const localeByHost = Object.fromEntries(
Object.entries(baseUrlByLocale).map(([locale, baseUrl]) => [
new URL(baseUrl).host,
locale,
]),
);
export function middleware(request: NextRequest) {
const newUrl = new URL(request.url);
if (
["/browserconfig.xml", "/manifest.json", "/robots.txt"].includes(
request.nextUrl.pathname,
)
) {
return NextResponse.next();
}
if (
i18n.locales.some((locale) => newUrl.pathname.startsWith(`/${locale}/`))
) {
newUrl.pathname.slice(3);
return NextResponse.redirect(newUrl);
}
const locale =
localeByHost[geRequestHost(request) ?? ""] ?? i18n.defaultLocale;
// @todo Remove when catch-all ‘not found’ pages are implemented
const existingPathnamePatterns = [
/^\/$/,
/^\/photos$/,
/^\/update-profiles\//,
];
if (
!existingPathnamePatterns.some((pathnamePattern) =>
pathnamePattern.test(newUrl.pathname),
)
) {
newUrl.pathname = `/${locale}/404`;
return NextResponse.rewrite(newUrl, { status: 404 });
}
newUrl.pathname = `/${locale}${newUrl.pathname}`;
return NextResponse.rewrite(newUrl);
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico|favicon/|images/).*)"],
};