#host and protocol in RSC
1 messages · Page 1 of 1 (latest)
Hi @gentle junco. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
In a Next.js server component, you can get the server host name and protocol by using the headers function from next/headers. Here's an example of how you can do this:
import { headers } from "next/headers";
// Inside the server component
const headersData = headers();
const protocol = headersData.get("x-forwarded-proto");
const host = headersData.get("host");
In this code, headers() is a function that returns an instance of the Headers class. The get method of the Headers class is then used to retrieve the protocol and host from the headers.
Please note that this method works in a server component context. If you're trying to use it in a client component, you might encounter issues as next/headers is designed to work in a server component.
Sources:
- Github Issue (open): Server Components fetch() throws in page.tsx > Comments (https://github.com/vercel/next.js/issues/46840)
- Github Issue (closed): Failed to parse URL when fetching localhost using Server Components > Comments Part 6 (https://github.com/vercel/next.js/issues/48344)