How to use functions across server and client components?
Answered
Siricid woodwasp posted this in #help-forum
Siricid woodwaspOP
[ api.ts ]
This function needs to be called in both server and client components. However when imported and used in a client component I get an error
export async function getProfile(userId: String, area?: String) {
try {
res = await fetch(env.GRAPHQL_URL, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
query: userQueries.getEducation,
variables: { userId },
})
})
result = await res.json()This function needs to be called in both server and client components. However when imported and used in a client component I get an error
Error Error: ? Attempted to access a server-side environment variable on the client10 Replies
Giant panda
Well you need to expose the URL to the client by prefixing it with
NEXT_PUBLIC_Siricid woodwaspOP
What to do incase of API keys in the evironment variables that need to accessed? @Giant panda
I was thinking of using a route handler as an intermediary . So the client would call the api in the route handler and the routehandler (since its server-side) could call the function (getProfile) directly.
Giant panda
If you want to hide the API keys then yes
Answer
Siricid woodwaspOP
Ok thanks @Giant panda . I was thinking latency on the initial request would be an issue since we are making two fetches (api route and function). Are there any more efficient solutions (other than server actions)?
Or is my concern exaggerated?
Giant panda
If the component issuing the request is a server component you can call the 3rd party API directly without proxy since server code is not in the browser and secrets stay safe
Siricid woodwaspOP
No I am talking requesting strictly from client components. The server components call the functions directly
Giant panda
It’s a minor overhead but it can’t be optimized and is often irrelevant