Skip to content

Instantly share code, notes, and snippets.

@infysumanta
Last active February 14, 2024 06:58
Show Gist options
  • Save infysumanta/d6a8c6eb90ff3e36a4d65da8f910d230 to your computer and use it in GitHub Desktop.
Save infysumanta/d6a8c6eb90ff3e36a4d65da8f910d230 to your computer and use it in GitHub Desktop.
This code snippet is a middleware function that extracts the subdomain from the request's hostname and rewrites the URL if the subdomain is "www" or exists. Otherwise, it allows the request to proceed to the next middleware.

URL Subdomain Rewriting Middleware

Preview:
import { type NextRequest, NextResponse } from "next/server";

export const config = {
  matcher: ["/((?!api/|_next/|_static/|_vercel|[\\w-]+\\.\\w+).*)"],
};

export default function middleware(req: NextRequest) {
  const url = req.nextUrl;
  const headers = req.headers;
  const hostname = req.headers.get("host");
  const domainParts = hostname?.split(".") as string[];
  const searchParams = url.searchParams.toString();
  let subdomain = null;

  const pathWithSearchParams = `${url.pathname}${
    searchParams.length > 0 ? `?${searchParams}` : ""
  }`;

  // if localhost then 1 else 2
  const isLocalhost = headers.get("host")?.includes("localhost") ? 1 : 2;

  if (domainParts?.length > isLocalhost) {
    subdomain = domainParts[0]; // assuming subdomain is the first part
  }

  if (subdomain === "www") {
    const rewriteUrl = new URL(`/${pathWithSearchParams}`, req.url);
    return NextResponse.rewrite(rewriteUrl);
  }

  if (subdomain) {
    const rewriteUrl = new URL(`/${subdomain}${pathWithSearchParams}`, req.url);
    return NextResponse.rewrite(rewriteUrl);
  }

  return NextResponse.next();
}
Associated Context
Type Code Snippet ( .ts )
Associated Tags NextRequest NextResponse config middleware url headers hostname domainParts isLocalhost subdomain Framework: Next.js reactjs js Server-side rendering URL rewriting Middleware Routing Subdomains HTTP headers Localhost Rewriting URLs Domain parsing
💡 Smart Description This code snippet defines a middleware function that handles the next/server request. It checks if there is a subdomain in the response headers and returns it as an HTTP redirect URL, or null for any domain part of this request. If not,
This code snippet is a middleware function that extracts the subdomain from the request's hostname and rewrites the URL if the subdomain is "www" or exists. Otherwise, it allows the request to proceed to the next middleware.
🔎 Suggested Searches Next js middleware for forwarding requests
Related Links https://www.geeksforgeeks.org/
https://www.geeksforgeeks.org/typescript-class/
https://www.geeksforgeeks.org/data-structures/linked-list/
https://www.npmjs.com/package/@nestjs/config
https://www.npmjs.com/package/@typescript-eslint/parser
https://www.npmjs.com/package/tsconfig-paths
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
https://developer.mozilla.org/en-US/docs/Web/API/URL/URL
https://developer.mozilla.org/en-US/docs/Web/API/URL
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
https://developer.mozilla.org/en-US/docs/Web/API/Headers/get
Related People Sumanta Kabiraj
Sensitive Information No Sensitive Information Detected
Shareable Link https://sumanta.pieces.cloud/?p=3cff4babaf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment