Getting Hostname from Page?
Answered
Spectacled bear posted this in #help-forum
Spectacled bearOP
What is the best way to get hostname from a page? I currently have but it's returning empty headers
export default async function Dashboard() {
const headerList = headers();
}Answered by Spectacled bear
For anyone who's interested, I was trying to get the hostname to look up a client by a slug. Our application is multi tenant so I ended up with this approach:
middleware.ts
page.tsx
middleware.ts
if (request.nextUrl.pathname === '/dashboard') {
let slug: string = request.nextUrl.hostname.replace('.domain.com', '');
return NextResponse.rewrite(new URL(`/dashboard?slug=${slug}`, request.url))
}page.tsx
port default async function Dashboard({ searchParams: { slug }} : any) {
const client: any = await getClientBySlug(slug);
}6 Replies
Spectacled bearOP
For anyone who's interested, I was trying to get the hostname to look up a client by a slug. Our application is multi tenant so I ended up with this approach:
middleware.ts
page.tsx
middleware.ts
if (request.nextUrl.pathname === '/dashboard') {
let slug: string = request.nextUrl.hostname.replace('.domain.com', '');
return NextResponse.rewrite(new URL(`/dashboard?slug=${slug}`, request.url))
}page.tsx
port default async function Dashboard({ searchParams: { slug }} : any) {
const client: any = await getClientBySlug(slug);
}Answer
Red-tailed wasp
Why on Earth would you need to use await to get a static value? This is a slow and garbage way to get a const string. Wouldn't it be faster to add the hostname to the env.local file and then import it once as const hostname = process.env.HOSTNAME? It will cause problems with ngrok though.
Red-tailed wasp
Sorry, I don't know what I'm doing yet. You just need to use the syntax <Link href="/slug"> to access the root domain name.
Spectacled bearOP
@Red-tailed wasp this is for a multi tenant setup where the domain name is dynamic.
Japanese anchovy
not sure what is happening inside of getClientBySlug but if your accessing headers your essentially turning off static generation at that point. Not sure if that is something important to you. What you could do potentially is include the slug in the dynamic route and then you could generate static pages with those values. it is essentially the same thing as what you got but you have the benefit of also having the ability to have static pages as well. Also, you can't access querystring params in static page as well again not sure if this is important to you
Spectacled bearOP
I got around this by always passing in the x-slug header from middleware requestHeaders.set('x-slug', request.nextUrl.hostname);