-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
54 lines (46 loc) · 1.66 KB
/
middleware.ts
File metadata and controls
54 lines (46 loc) · 1.66 KB
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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { stripLocaleFromPath, toInternalPath } from "./lib/i18nRoutes";
const PUBLIC_FILE = /\.(.*)$/;
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
const { locale, pathWithoutLocale, hadLocalePrefix } =
stripLocaleFromPath(pathname);
// Next.js internals + public assets should never be locale-prefixed.
// If a locale prefix sneaks in (e.g. via a <base> tag or relative URL),
// rewrite to the non-prefixed path so assets/HMR/etc keep working.
if (
hadLocalePrefix &&
(pathWithoutLocale.startsWith("/_next") ||
pathWithoutLocale.startsWith("/api") ||
PUBLIC_FILE.test(pathWithoutLocale))
) {
const url = request.nextUrl.clone();
url.pathname = pathWithoutLocale;
return NextResponse.redirect(url);
}
if (
pathname.startsWith("/_next") ||
pathname.startsWith("/api") ||
PUBLIC_FILE.test(pathname)
) {
return NextResponse.next();
}
if (!hadLocalePrefix) {
return NextResponse.next();
}
const internalPath = toInternalPath(pathWithoutLocale, locale);
const url = request.nextUrl.clone();
url.pathname = internalPath;
const requestHeaders = new Headers(request.headers);
requestHeaders.set("x-locale", locale);
return NextResponse.rewrite(url, { request: { headers: requestHeaders } });
}
export const config = {
matcher: [
// Always handle locale-prefixed paths (including accidental /{locale}/_next/*).
"/:locale(en|me|ru)/:path*",
// For non-locale paths, skip Next internals, API routes, and public files.
"/((?!_next|api|.*\\..*).*)",
],
};