MonkeyStruct
MonkeyStruct2y ago

tRPC context and NextJS

Guys quick question about using trpc and nextjs. I'm using context with trpc to create some queries that will be only accessible by logged in users. On nextjs side I'm using react context to manage it for now. So my thinking was to pass one of the ctx variable that will be user ID to trpc server when I use useQuery. Ex) trpc.user.getSecret.useQuery(undefined, {req.body}). But I'm honestly stuck on how I can send next request body. Code for trpc context is this.
export const createContext = async (opts: CreateNextContextOptions) => {
  // console.log(opts.req, "inside trpc context");
  async function getUser() {
    console.log(opts.req.body, "res body");
    const user = await prisma.user.findUnique({
      where: { id: opts.req.body.id ? opts.req.body.id : "" },
    });

    return user ? user : null;
  }
  const user = await getUser();

  return await createContextInner({ user });
};
export const createContext = async (opts: CreateNextContextOptions) => {
  // console.log(opts.req, "inside trpc context");
  async function getUser() {
    console.log(opts.req.body, "res body");
    const user = await prisma.user.findUnique({
      where: { id: opts.req.body.id ? opts.req.body.id : "" },
    });

    return user ? user : null;
  }
  const user = await getUser();

  return await createContextInner({ user });
};
I know you can change body in api/[trpc] route but I won't have access to ReactContext there so if any of you guys have a suggestion or solution please let me know. 🙏🙏🙏
3 Replies
mark salsbery
mark salsbery2y ago
Instead of modifying the body, you could pass the id in an http header.. https://trpc.io/docs/header
Custom header | tRPC
The headers option can be customized in the config when using the httpBatchLink or the httpLink.
MonkeyStruct
MonkeyStructOP2y ago
Thank you for the information. I read that too and honestly idk why I didn't try that.
mark salsbery
mark salsbery2y ago
If you go that route, you may find a happier future self 😉