tRPCttRPC
Powered by
maddsuaM
tRPC•2y ago•
11 replies
maddsua

Procedure specific custom headers

I'm using recaptcha to protect some of the procedures, and I'm used to sending challenge tokens as headers - this way the don't dangle in actual request data. It's and Astro + trpc fetch project and the server part gives me no issues, but I can't figure out how to run recaptcha and set that header only on some of the procedures. The example shown in the docs would add headers or run function for all of them, and I don't need that
Solution
So first you add a flag to request context like this:
api.store.checkout.mutate({
  lang,
  person_name: {
    first: data.firstName,
    last: data.lastName
  },
  ...
}, {
  context: {
    getCaptcha: true
  }
})
api.store.checkout.mutate({
  lang,
  person_name: {
    first: data.firstName,
    last: data.lastName
  },
  ...
}, {
  context: {
    getCaptcha: true
  }
})


And then check for it here:
export const api = createTRPCProxyClient<AppRouter>({
  links: [
    httpBatchLink({
      url: config.endpoint,
      headers: (bruh) => {
        if (bruh.opList.some(item => item.context['getCaptcha'])) {
          return {
            'x-captcha': //  do check here and return the token
          }
        }
        return {}
      }
    })
  ],
});
export const api = createTRPCProxyClient<AppRouter>({
  links: [
    httpBatchLink({
      url: config.endpoint,
      headers: (bruh) => {
        if (bruh.opList.some(item => item.context['getCaptcha'])) {
          return {
            'x-captcha': //  do check here and return the token
          }
        }
        return {}
      }
    })
  ],
});
Jump to solution
tRPCJoin
Move Fast & Break Nothing. End-to-end typesafe APIs made easy.
5,015Members
Resources
Recent Announcements

Similar Threads

Was this page helpful?

Similar Threads

How to set up custom response headers at procedure level
NivoaNNivoa / ❓-help
2y ago
How do you set headers or cookies in procedure ?
codeforkCcodefork / ❓-help
3y ago
calling tRPC procedure from custom link
SparkSSpark / ❓-help
2y ago