-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
38 lines (33 loc) · 1.03 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
import { NextRequest, NextResponse } from "next/server";
import { redis } from "./lib/upstash";
export const config = {
matcher: [
"/((?!api|_next/static|_next/image|favicon.ico|logo.png|og.png|signin|links|public|github.svg|zez.png).*)",
],
};
export default async function middleware(req: NextRequest) {
const path = req.nextUrl.pathname.split("/")[1];
if (["", "public", "links"].includes(path)) {
return NextResponse.next();
}
const find = await redis.get<{ url: string }>(
`${process.env.NEXT_PUBLIC_BASE_URL}:${path}`
);
if (find?.url) {
try {
await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/link/${path}/incr`, {
method: "POST",
});
} catch (error) {
console.log(error);
}
}
if (!find) return NextResponse.rewrite(new URL("/", req.url));
if (
req.nextUrl.searchParams.get("bot") ||
/bot/i.test(req.headers.get("user-agent") as string)
) {
return NextResponse.rewrite(new URL(`/_link/${path}`, req.url));
}
return NextResponse.redirect(find.url);
}