Rewriting subdomain.example.com to example.com/subdomain

I am deploying an Astro site with middleware and want to rewrite test.example.com to example.com/test, however it returns a 522 error.
import type { MiddlewareHandler } from "astro";

export const onRequest: MiddlewareHandler = async (context, next) => {
  const { request, locals } = context;

  // Skip non-GET requests or if the URL matches the skip pattern
  if (request.method !== "GET") return next();

  const SKIP_PATTERN = /^(?:\/_image\/|\/_astro\/|[/\w-]+\.[\w-]+$)/;
  if (SKIP_PATTERN.test(context.url.pathname)) return next();

  const frontendUrl = locals.runtime.env.FRONTEND_URL;
  const host = context.url.host;

  // Handle subdomain extraction
  let subdomain: string | undefined = undefined;
  if (host.endsWith(".localhost:1234")) {
    const parts = host.replace(":1234", "").split(".");
    subdomain = parts.length > 1 ? parts[0] : undefined;
  } else if (host.endsWith(frontendUrl)) {
    const parts = host.split(".");
    subdomain = parts.length > 2 ? parts[0] : undefined;
  }

  console.log("Subdomain:", subdomain);

  // If no subdomain, continue with the original request
  if (!subdomain) return next();

  // Rewrite the URL to include the subdomain path
  const newUrl = `${context.url.protocol}//${frontendUrl}/${subdomain}${context.url.pathname}${context.url.search}`;
  console.log("Rewriting to:", newUrl);

  const response = await fetch(newUrl);
  return response;
};

I'm guessing it's getting stuck in a loop or something? Not sure how to handle this properly
Was this page helpful?