Next.js Discord

Discord Forum

Sending requests in nextjs server components

Unanswered
Great black wasp posted this in #help-forum
Open in Discord
Great black waspOP
I make a request to my server in layout.tsx, but I try to return data specific to each site using the origin in the headers on my server, but the origin is always empty because I make the request from the server component

13 Replies

Great black waspOP
How can I pull the origin or url of the main site in layout.tsx, I use the same code on 10 sites
I can pull origin in client components but not in server components
or if there is another way, can you tell me what to do?
basic code:

 const req = await fetch(`${api}/products`);
I need to do this operation in server components, I need to pull the data without loading the page
main layout.tsx*
@Great black wasp I make a request to my server in layout.tsx, but I try to return data specific to each site using the origin in the headers on my server, but the origin is always empty because I make the request from the server component
so you are trying to fetch to an external server and your external server expected a origin header but then nextjs server doesnt send an origin header?
have you tried adding the origin header in the fetch function?
@aardani have you tried adding the origin header in the `fetch` function?
Great black waspOP
yes I tried but I use multiple domains in a single project
export function getBaseUrl(withProtocol = true) {
    const env = process.env.NEXT_PUBLIC_VERCEL_ENV;
    if (env === "production")
        return `${withProtocol ? "https://" : ""}${process.env.NEXT_PUBLIC_VERCEL_URL}`;
    return `${withProtocol ? "http://" : ""}localhost:4000`;
}


lbut instead of giving me this domain, it gives me the vercel.app url and I want the domain
NEXT_PUBLIC_VERCEL_URL = contains vercel.app, but i want to real domain without vercel.app
Oriental
@aardani we have 40 domains for one of our apps. And we need to get the domain for the request
Writing a middleware and using the request origin might work maybe 🤔