-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
72 lines (55 loc) · 2.39 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
import { type NextRequest, NextResponse } from "next/server";
import { fetchAnimeTitleById } from "./app/_lib/graphql/fetchers/animeFetcherById";
import { generateSlug } from "./app/_lib/helpers/slugGenerator";
export async function middleware(request: NextRequest) {
const response = NextResponse.next();
const theme = request.cookies.get("theme")?.value || "light";
console.log("middleware: theme", request.cookies.get("theme")?.value);
response.cookies.set("theme", theme, { path: "/" });
//redirect on the anime preview page based on the preferred title language
if (request.nextUrl.pathname.startsWith("/anime/")) {
const url = request.nextUrl.clone();
const pathname = url.pathname;
// Check if the URL matches the anime page pattern
const animeRegex = /^\/anime\/\d+(\/.+)?$/;
if (!animeRegex.test(pathname)) {
return NextResponse.next(); // Allow other routes to pass through
}
// Simulate fetching user's language preference (e.g., from cookies)
const userLanguage =
request.cookies.get("user-language")?.value || "english"; // Default to English
console.log("user language", userLanguage);
// Parse the ID and slug from the URL
const segments = pathname.split("/");
console.log("segments", segments);
const id = segments[2];
const slug = segments[3];
console.log("middleware: current title slug", slug);
// Generate the appropriate slug for the language
const titles = await fetchAnimeTitleById({ mediaId: +id });
let preferredTitle: string | undefined;
switch (userLanguage) {
case "english":
preferredTitle = titles?.english || titles?.romaji;
break;
case "native":
case "romaji":
preferredTitle = titles?.romaji;
break;
case "userPreferred":
preferredTitle = titles?.userPreferred;
break;
default: // Handle unsupported languages or fallback
preferredTitle = titles?.english; // Or another default
break;
}
const redirectSlug = generateSlug(preferredTitle || ""); // Handle potential undefined
console.log("middleware: desired title slug", redirectSlug);
// Redirect to the language-specific page if necessary
if (slug !== redirectSlug) {
url.pathname = `/anime/${id}/${redirectSlug}`;
return NextResponse.redirect(url);
}
}
return response; // Continue if no redirection is needed
}