T
Join ServertRPC
❓-help
How to pass context to vanilla client?
Hi,
I have a next app where I use trpc. Now I need to call some trpc functions from outside of any components. My first solution was to just call the endpoint with axios.
This is working fine, but I lose typing support.
My new solution is to use the vanilla client. But using the vanilla client I can't find a way to pass context to the request, for example to pass a cookie. Now my walkaround is creating a getter function that each time creates a new trpc client with the context needed.
This is also working fine, but feels a bit hacky to me, because each time it creates a new client.
How would be the proper solution to call a trpc function with context like a cookie using the vanilla client? (I can't use hooks here)
I have a next app where I use trpc. Now I need to call some trpc functions from outside of any components. My first solution was to just call the endpoint with axios.
const { data: attribute } = await axios({
method: "GET",
url: getApiServerUrl() + "/trpc/db.getAttribute",
params: {
input: JSON.stringify(trpcInput)
},
headers: { 'Cookie': cookie }
});
This is working fine, but I lose typing support.
My new solution is to use the vanilla client. But using the vanilla client I can't find a way to pass context to the request, for example to pass a cookie. Now my walkaround is creating a getter function that each time creates a new trpc client with the context needed.
export const getClientWithCookie = ({cookie}: {cookie: string}) => createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: getApiServerUrl() +
/trpc,
headers() {
return {
cookie: cookie,
};
},
}),
],
});
const attribute = await getClientWithCookie({cookie: cookie}).db.getAttribute.query(trpcInput);
This is also working fine, but feels a bit hacky to me, because each time it creates a new client.
How would be the proper solution to call a trpc function with context like a cookie using the vanilla client? (I can't use hooks here)