generated from dev-protocol/template-repos-static
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmiddleware.ts
92 lines (81 loc) · 2.29 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import { rewrite, next } from "@vercel/edge";
import builtInApiPaths from "./built-in-api-paths";
const dest = process.env.DEST;
const hosts = (process.env.HOSTS ?? "clubs.place")
.split(",")
.map((x) => x.trim())
.sort((a, b) => (a.split(".").length < b.split(".").length ? 0 : -1));
// export const config = {
// matcher: ["/((?!assets|chunks|_vercel|[\\w-]+\\.\\w+).*)"],
// };
const redirects = [
...hosts.map((host) => ({
host,
matchers: [
"/",
new RegExp("^/(starter|ticketing|plugins|dev-tokens|blog|post|pricing)(|/.*)$"),
],
destination: "https://www.clubs.place",
})),
{
host: "temples.clubs.stakes.social",
matchers: undefined,
destination: "https://temples.clubs.place",
},
{
host: "kougenji.clubs.stakes.social",
matchers: undefined,
destination: "https://kougenji.clubs.place",
},
];
export default function middleware(req: Request) {
const url = new URL(req.url);
const matchToRedirects = redirects.find(
({ host, matchers }) =>
host === url.host &&
(matchers
? matchers.some((matcher) =>
typeof matcher === "string"
? matcher === url.pathname
: matcher.test(url.pathname),
)
: true),
);
if (matchToRedirects) {
return Response.redirect(
new URL(
`${url.pathname}${url.search ? url.search : ""}`,
matchToRedirects.destination,
),
);
}
const hostnames = url.host.split(".") ?? [];
const [tenant] = hostnames;
const api = url.pathname.startsWith("/api/");
const html =
!api &&
(req.headers.get("accept")?.includes("text/html") ||
url.pathname
.split("/")
.slice(-1)
.every((p) => !/\..+$/.test(p)));
const bInApi = builtInApiPaths.some((p) => url.pathname.startsWith(p));
const pInApi = api && !bInApi;
const primaryHost =
hosts.find((h) => url.host === h) ??
hosts.find((h) => url.host.endsWith(h));
if ((html || pInApi) && primaryHost && url.host !== primaryHost && dest) {
const destination = new URL(url.href);
destination.pathname = `/sites_/${tenant}${url.pathname}`;
destination.host = dest;
console.log({ destination: destination.toString() });
return rewrite(destination);
}
if (dest) {
const destination = new URL(url.href);
destination.host = dest;
console.log({ destination: destination.toString() });
return rewrite(destination);
}
return next();
}