tRPCttRPC
Powered by
TuxerT
tRPC•3y ago•
26 replies
Tuxer

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.


const { data: attribute } = await axios({
  method: "GET",
  url: getApiServerUrl() + "/trpc/db.getAttribute",
  params: {
    input: JSON.stringify(trpcInput)
  },
  headers: { 'Cookie': cookie }
});

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() + 

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);
,
      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)
tRPCJoin
Move Fast & Break Nothing. End-to-end typesafe APIs made easy.
5,015Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Vanilla Client Authentication
pedroPpedro / ❓-help
3y ago
Vanilla Client Error Handling
justindgmJjustindgm / ❓-help
3y ago
Is there a way to pass context or cookies to the client provider?
Y0z64YY0z64 / ❓-help
2y ago