How do you handle calling your own API route?
Answered
West African Lion posted this in #help-forum
West African LionOP
How do you handle calling your own API route from a server component?
In Next when you try to fetch your API route from a server component you need to input the whole url including the domain, unlike in client components where you just input the relative route.
I know some people just do the actions that the API route does directly in the server component.
But that’s not an option because I need caching.
I know that I could just create an env variable with the base url and use that, but that doesn’t seem like an elegant way of doing this.
How do you or other projects handle this?
In Next when you try to fetch your API route from a server component you need to input the whole url including the domain, unlike in client components where you just input the relative route.
I know some people just do the actions that the API route does directly in the server component.
But that’s not an option because I need caching.
I know that I could just create an env variable with the base url and use that, but that doesn’t seem like an elegant way of doing this.
How do you or other projects handle this?
Answered by B33fb0n3
First things first: don't fetch your own api route in server components. Instead: create a function (just a plain function. No server action) and call this method in your api route (if needed) and in your server component. You will have cache in it (data cache) if you using
fetch6 Replies
@West African Lion How do you handle calling your own API route from a server component?
In Next when you try to fetch your API route from a server component you need to input the whole url including the domain, unlike in client components where you just input the relative route.
I know some people just do the actions that the API route does directly in the server component.
But that’s not an option because I need caching.
I know that I could just create an env variable with the base url and use that, but that doesn’t seem like an elegant way of doing this.
How do you or other projects handle this?
First things first: don't fetch your own api route in server components. Instead: create a function (just a plain function. No server action) and call this method in your api route (if needed) and in your server component. You will have cache in it (data cache) if you using
fetchAnswer
There are many ways to do this, and it will depend on your fetcher library you choose to use. some common ones include
- fetch
- axios
- fetch
- axios
- React Query
- The classic SWR method
- useFetch()
- The classic SWR method
- useFetch()
@West African Lion solved?
West African LionOP
Yes
@West African Lion Yes
Happy to help. Please mark solution