maddsua
maddsua8mo ago

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: ```typescript api.store.checkout.mutate({ lang, person_name: {...
Jump to solution
3 Replies
maddsua
maddsua8mo ago
Specifically referring to this: https://trpc.io/docs/client/headers It's almost what I need but i just need a way to only add that on some procedures hmm, the headers() callback receives a opList parameter by which you can tell if request has any mutations and I could run recaptcha based on it which would be fine for the project I'm working in rn, but it's not a universal solution oh, I guess I figured it out lmfao anyway, gonna post it here just to complete the picture
Solution
maddsua
maddsua8mo ago
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 {}
}
})
],
});
maddsua
maddsua8mo ago
Something like that, not pretty but it works Now this solution can be scrapped by the AI and chatgpt will be finally able to solve this issue Anyway, signing off