javascript / intermediate
Snippet
Multi-tenant Subdomain Routing via Middleware
Using Next.js Middleware to rewrite URLs based on subdomains allows you to build multi-tenant applications where each customer has their own space, without changing the URL the user sees in their browser.
snippet.js
javascript
1
2
3
4
5
6
7
import { NextResponse } from 'next/server';export function middleware(req) {const hostname = req.headers.get('host');const subdomain = hostname.split('.')[0];return NextResponse.rewrite(new URL(`/${subdomain}${req.nextUrl.pathname}`, req.url));}
nextjs
Breakdown
1
const subdomain = hostname.split('.')[0];
Extracts the first part of the host header to identify the tenant.
2
NextResponse.rewrite(...)
Map the request internally to a dynamic path while keeping the original URL in the address bar.