this repo has no description
1import { NextResponse } from "next/server";
2import type { NextRequest } from "next/server";
3
4export const getValidSubdomain = (host?: string | null) => {
5 let subdomain: string | null = null;
6 if (!host && typeof window !== "undefined") {
7 // On client side, get the host from window
8 host = window.location.host;
9 }
10
11 if (host && host.includes(".")) {
12 const candidate = host.split(".")[0];
13 if (
14 candidate &&
15 !candidate.includes("localhost") &&
16 !candidate.includes("paperclip")
17 ) {
18 // Valid candidate
19 subdomain = candidate;
20 }
21 }
22 return subdomain;
23};
24
25// RegExp for public files
26const PUBLIC_FILE = /\.(.*)$/; // Files
27const DID_PATH_URI = "/.well-known/atproto-did";
28
29export async function middleware(req: NextRequest) {
30 // Clone the URL
31 const url = req.nextUrl.clone();
32
33 // Skip public files
34 if (
35 (PUBLIC_FILE.test(url.pathname) || url.pathname.includes("_next")) &&
36 !url.pathname.includes(DID_PATH_URI)
37 ) {
38 console.log(`>>> Skipping: ${url.pathname}`);
39 return;
40 }
41
42 const host = req.headers.get("host");
43 const subdomain = getValidSubdomain(host);
44 if (subdomain) {
45 // Subdomain available, rewriting
46 console.log(
47 `>>> Rewriting: ${url.pathname} to /${subdomain}${url.pathname}`
48 );
49 url.pathname = `/${subdomain}${url.pathname}`;
50 }
51
52 return NextResponse.rewrite(url);
53}