Openstatus
www.openstatus.dev
1import type { NextRequest } from "next/server";
2
3export const getValidSubdomain = (host?: string | null) => {
4 let subdomain: string | null = null;
5 if (!host && typeof window !== "undefined") {
6 // On client side, get the host from window
7 // biome-ignore lint: to fix later
8 host = window.location.host;
9 }
10
11 // Exclude localhost and IP addresses from being treated as subdomains
12 if (
13 host?.match(/^(localhost|127\\.0\\.0\\.1|::1|\\d+\\.\\d+\\.\\d+\\.\\d+)/)
14 ) {
15 return null;
16 }
17
18 // Handle subdomains of localhost (e.g., hello.localhost:3000)
19 if (host?.match(/^([^.]+)\.localhost(:\d+)?$/)) {
20 const match = host.match(/^([^.]+)\.localhost(:\d+)?$/);
21 return match?.[1] || null;
22 }
23
24 // we should improve here for custom vercel deploy page
25 if (host?.includes(".") && !host.includes(".vercel.app")) {
26 const candidate = host.split(".")[0];
27 if (candidate && !candidate.includes("www")) {
28 // Valid candidate
29 subdomain = candidate;
30 }
31 }
32
33 // In case the host is a custom domain
34 if (
35 host &&
36 !(
37 host?.includes("stpg.dev") ||
38 host?.includes("openstatus.dev") ||
39 host?.endsWith(".vercel.app")
40 )
41 ) {
42 subdomain = host;
43 }
44 return subdomain;
45};
46
47export const getValidCustomDomain = (req: NextRequest | Request) => {
48 const url = "nextUrl" in req ? req.nextUrl.clone() : new URL(req.url);
49 const headers = req.headers;
50 const host = headers.get("x-forwarded-host");
51
52 let prefix = "";
53 let type: "hostname" | "pathname";
54
55 const hostnames = host?.split(/[.:]/) ?? url.host.split(/[.:]/);
56 const pathnames = url.pathname.split("/");
57
58 const subdomain = getValidSubdomain(url.host);
59 console.log({
60 hostnames,
61 pathnames,
62 host,
63 urlHost: url.host,
64 subdomain,
65 });
66
67 if (
68 hostnames.length > 2 &&
69 hostnames[0] !== "www" &&
70 !url.host.endsWith(".vercel.app")
71 ) {
72 prefix = hostnames[0].toLowerCase();
73 type = "hostname";
74 } else {
75 prefix = pathnames[1].toLowerCase();
76 type = "pathname";
77 }
78
79 if (subdomain !== null) {
80 prefix = subdomain.toLowerCase();
81 }
82
83 console.log({ type, prefix });
84
85 return { type, prefix };
86};