-
Notifications
You must be signed in to change notification settings - Fork 760
/
middleware.ts
81 lines (68 loc) · 2.13 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
import { NextFetchEvent, NextRequest, NextResponse } from "next/server";
import AppMiddleware from "@/lib/middleware/app";
import DomainMiddleware from "@/lib/middleware/domain";
import { BLOCKED_PATHNAMES } from "./lib/constants";
import IncomingWebhookMiddleware, {
isWebhookPath,
} from "./lib/middleware/incoming-webhooks";
import PostHogMiddleware from "./lib/middleware/posthog";
function isAnalyticsPath(path: string) {
// Create a regular expression
// ^ - asserts position at start of the line
// /ingest/ - matches the literal string "/ingest/"
// .* - matches any character (except for line terminators) 0 or more times
const pattern = /^\/ingest\/.*/;
return pattern.test(path);
}
export const config = {
matcher: [
/*
* Match all paths except for:
* 1. /api/ routes
* 2. /_next/ (Next.js internals)
* 3. /_static (inside /public)
* 4. /_vercel (Vercel internals)
* 5. /favicon.ico, /sitemap.xml (static files)
*/
"/((?!api/|_next/|_static|vendor|_icons|_vercel|favicon.ico|sitemap.xml).*)",
],
};
export default async function middleware(req: NextRequest, ev: NextFetchEvent) {
const path = req.nextUrl.pathname;
const host = req.headers.get("host");
if (isAnalyticsPath(path)) {
return PostHogMiddleware(req);
}
// Handle incoming webhooks
if (isWebhookPath(host)) {
return IncomingWebhookMiddleware(req);
}
if (
(process.env.NODE_ENV === "development" && host?.includes(".local")) ||
(process.env.NODE_ENV !== "development" &&
!(
host?.includes("localhost") ||
host?.includes("papermark.io") ||
host?.endsWith(".vercel.app")
))
) {
return DomainMiddleware(req);
}
if (
!path.startsWith("/view/") &&
!path.startsWith("/verify") &&
!path.startsWith("/unsubscribe")
) {
return AppMiddleware(req);
}
const url = req.nextUrl.clone();
if (
path.startsWith("/view/") &&
(BLOCKED_PATHNAMES.some((blockedPath) => path.includes(blockedPath)) ||
path.includes("."))
) {
url.pathname = "/404";
return NextResponse.rewrite(url, { status: 404 });
}
return NextResponse.next();
}