-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
103 lines (90 loc) · 2.52 KB
/
Copy pathproxy.ts
File metadata and controls
103 lines (90 loc) · 2.52 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
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import {
convexAuthNextjsMiddleware,
createRouteMatcher,
nextjsMiddlewareRedirect,
} from "@convex-dev/auth/nextjs/server";
import { NextResponse } from "next/server";
const LOCALE_COOKIE = "swap-language";
const ARABIC_COUNTRY_CODES = new Set([
"AE",
"BH",
"DZ",
"EG",
"IQ",
"JO",
"KW",
"LB",
"LY",
"MA",
"OM",
"PS",
"QA",
"SA",
"SD",
"SY",
"TN",
"YE",
]);
const isSignInPage = createRouteMatcher(["/signin", "/ar/signin"]);
const isProtectedRoute = createRouteMatcher([
"/server",
"/account",
"/account/(.*)",
"/onboarding",
"/onboarding/(.*)",
"/ar/server",
"/ar/account",
"/ar/account/(.*)",
"/ar/onboarding",
"/ar/onboarding/(.*)",
]);
function stripLocale(pathname: string) {
return pathname.replace(/^\/ar(?=\/|$)/, "") || "/";
}
function getCountryCode(request: Request) {
return (
request.headers.get("x-vercel-ip-country") ||
request.headers.get("cf-ipcountry") ||
request.headers.get("x-country-code") ||
""
).toUpperCase();
}
function shouldUseArabic(request: Request) {
const country = getCountryCode(request);
if (ARABIC_COUNTRY_CODES.has(country)) return true;
const acceptLanguage = request.headers.get("accept-language") || "";
return acceptLanguage.toLowerCase().startsWith("ar");
}
export default convexAuthNextjsMiddleware(async (request, { convexAuth }) => {
const { pathname, search } = request.nextUrl;
const hasArabicLocale = pathname.startsWith("/ar");
const isApiRoute = pathname.startsWith("/api") || pathname.startsWith("/trpc");
const localeCookie = request.cookies.get(LOCALE_COOKIE)?.value;
if (isApiRoute) {
return;
}
if (!hasArabicLocale && !localeCookie && shouldUseArabic(request)) {
const url = request.nextUrl.clone();
url.pathname = pathname === "/" ? "/ar" : `/ar${pathname}`;
return NextResponse.redirect(url);
}
if (isSignInPage(request) && (await convexAuth.isAuthenticated())) {
return nextjsMiddlewareRedirect(request, hasArabicLocale ? "/ar" : "/");
}
if (isProtectedRoute(request) && !(await convexAuth.isAuthenticated())) {
const next = pathname + search;
const signInPath = hasArabicLocale ? "/ar/signin" : "/signin";
return nextjsMiddlewareRedirect(
request,
signInPath + "?next=" + encodeURIComponent(next),
);
}
if (hasArabicLocale) {
const url = request.nextUrl.clone();
url.pathname = stripLocale(pathname);
return NextResponse.rewrite(url);
}
});
export const config = {
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};