Loading data on page open
Unanswered
Asiatic Lion posted this in #help-forum
Asiatic LionOP
Hey I have an api that requires me to send session, ip, and useragent data with the request to get data back. I want to call
GET /users/
for the api when loading my Navbar
component. I have an api class called api.server.ts
in /app/libs/
that uses the following function to create an Api instance: export const createApi = async () => {
const headersList = await headers();
const cookieStore = await cookies();
const sess = cookieStore.get("session")
if(!sess) throw new Error("No session cookie found.");
const ip = headersList.get("CF-Connecting-IP") || headersList.get("X-Forwarded-For") || headersList.get("X-Real-IP");
if (!ip && !isDev()) throw new Error("Unable to fetch ip address.");
return new API(sess.value, ip!, headersList.get("User-Agent")!);
};
whenever I try calling it in Navbar
and then in my page.tsx
I get the following error (attached). How can I go about doing this?3 Replies
Asiatic LionOP
bumpp
@Asiatic Lion Hey I have an api that requires me to send session, ip, and useragent data with the request to get data back. I want to call `GET /users/` for the api when loading my `Navbar` component. I have an api class called `api.server.ts` in `/app/libs/` that uses the following function to create an Api instance: js
export const createApi = async () => {
const headersList = await headers();
const cookieStore = await cookies();
const sess = cookieStore.get("session")
if(!sess) throw new Error("No session cookie found.");
const ip = headersList.get("CF-Connecting-IP") || headersList.get("X-Forwarded-For") || headersList.get("X-Real-IP");
if (!ip && !isDev()) throw new Error("Unable to fetch ip address.");
return new API(sess.value, ip!, headersList.get("User-Agent")!);
}; whenever I try calling it in `Navbar` and then in my `page.tsx` I get the following error (attached). How can I go about doing this?
It's treating it as a server component (default tsx file). This means you can't use next/headers because it interprets it as a page component or a component that expects to return a React.ReactNode. If you want to handle something like this, you could try creating an API route or a server action (not recommended for this approach) that is invoked from the root layout or from the main layout you're using instead of having a file of this type.
This answer is mostly based on what I've worked with and what I understand. In case you're trying an exotic approach that you've seen work on other people's projects, I suggest you take a closer look at your implementation.