How to Get Header Hostname in Next.js Server Components
March 20, 2024
In some projects, it's crucial to access the hostname for routing, tenancy, or branding purposes. In this guide, we'll explore different ways to get the hostname in Next.js server components, especially if you're working with subdomains like blog.example.com.
Server-Side Hostname Access
In Next.js server components, we can access request headers using headers
from next/headers:
import { headers } from "next/headers";
export default async function BlogPage() {
const headerList = headers();
const host = headerList.get("host");
return (
<div>
<h1>Current Host: {host}</h1>
</div>
);
}
This approach ensures consistent hostname handling during server-side rendering.
Why This Matters
For multi-tenant apps, distinguishing between domains can help:
- Personalize content
- Route users correctly
- Modify styles dynamically
Stay tuned for more Next.js tips and tricks!