-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
47 lines (40 loc) · 1.31 KB
/
middleware.ts
File metadata and controls
47 lines (40 loc) · 1.31 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
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
const SUPPORTED = ["tr", "en"] as const;
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
if (pathname.startsWith("/_next") || pathname.startsWith("/api")) {
return NextResponse.next();
}
const match = pathname.match(/^\/(tr|en)(\/.*)?$/);
if (match) {
const lang = match[1];
const rest = match[2] ?? "/";
const url = request.nextUrl.clone();
url.pathname = rest === "" ? "/" : rest;
url.searchParams.set("lang", lang);
const response = NextResponse.rewrite(url);
response.cookies.set("lang", lang, {
path: "/",
maxAge: 60 * 60 * 24 * 365,
sameSite: "lax",
});
return response;
}
const langCookie = request.cookies.get("lang")?.value;
if (!langCookie || !SUPPORTED.includes(langCookie as typeof SUPPORTED[number])) {
const response = NextResponse.next();
response.cookies.set("lang", "en", {
path: "/",
maxAge: 60 * 60 * 24 * 365,
sameSite: "lax",
});
return response;
}
return NextResponse.next();
}
export const config = {
matcher: [
"/((?!_next|api|favicon.ico|robots.txt|sitemap.xml|site.webmanifest|icon-192.png|icon-512.png|apple-icon.png|icon.png|og.png|og.svg).*)",
],
};