javascript / expert
Snippet
Tenant-Aware Request Decorator in Edge Middleware
Implement a decorator pattern at the Edge level to inject multi-tenancy context into headers. This allows downstream Server Components and Route Handlers to access the tenant identity without re-parsing the URL or headers manually.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
import { NextResponse } from 'next/server';export function middleware(req) {const tenantId = req.nextUrl.hostname.split('.')[0];const response = NextResponse.next();response.headers.set('x-tenant-id', tenantId);response.headers.set('x-middleware-cache', 'no-cache');return response;}
nextjs
Breakdown
1
NextResponse.next()
Initializes the response object while continuing the middleware chain.
2
response.headers.set(...)
Injects custom metadata into the response context for downstream use.
3
req.nextUrl.hostname
Extracts the subdomain to determine the specific tenant identity.