Checking for a cookie as a TRPC middleware

Hello, For a certain group of TRPC routes I would like to check if a certain cookie has a certain value (If it does not, I would like to prevent the request from proceeding). What would be the best way to go about doing this? At the moment, I do not believe that data such as cookie is provided in any sort of context. I would also like it if it could be middleware-like, so that any route using that procedure is guaranteed to be authenticated already. Thanks for the help!
8 Replies
Liam
LiamOP2y ago
I assume it would be something in the trpc.ts fle, something like a private procedure of some sort
Keef
Keef2y ago
GitHub
create-t3-turbo/context.ts at main · t3-oss/create-t3-turbo
Clean and simple starter repo using the T3 Stack along with Expo React Native - create-t3-turbo/context.ts at main · t3-oss/create-t3-turbo
Keef
Keef2y ago
Just plop in what you need (cookie) then it’ll be available for each request Then just define your procedure and make use of it in a endpoint
Keef
Keef2y ago
Define Procedures | tRPC
- A publicProcedure can be viewed as the equivalent of a REST-endpoint or a function.
Keef
Keef2y ago
Here’s the author making use of a procedure and the context they defined in that repo I linked earlier
Keef
Keef2y ago
GitHub
create-t3-turbo/auth.ts at main · t3-oss/create-t3-turbo
Clean and simple starter repo using the T3 Stack along with Expo React Native - create-t3-turbo/auth.ts at main · t3-oss/create-t3-turbo
Liam
LiamOP2y ago
Thanks! So if I understand correctly, I need to make a middleware and then add a exported procedure with the middleware attached (.use()'d) to it. Is there a way to access the cookies through the passed in context, or would it be best to pass it in the input? If passing it in via the input, how would I define that that is required for all requests? Nvm, now seeing more of what you meant. Basically you can define things that get passed in the context via
type CreateContextOptions = {
session: Session | null;
};
type CreateContextOptions = {
session: Session | null;
};
and then pass them in @
export const createContext = async (opts: CreateNextContextOptions) => {
const session = await getServerSession(opts);

return await createContextInner({
session,
});
};
export const createContext = async (opts: CreateNextContextOptions) => {
const session = await getServerSession(opts);

return await createContextInner({
session,
});
};
I guess is what I am missing is how can I get the cookies here to pass into the context? I don't see in any of these functions where I have access to some kind of headers/cookies object.
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server