How to set cookies in trpc response?

I have an app dir project that was created using this t3-app PR. On the client I have a form and I am using the trpc react client:
import { api } from "~/trpc/react";
[...]
const login = api.auth.login.useMutation({ ... });
import { api } from "~/trpc/react";
[...]
const login = api.auth.login.useMutation({ ... });
and I have the following route defined:
import { cookies } from "next/headers";

publicProcedure
.input(...)
.mutation(async ({ ctx, input }) => {
[...]

// somehow set a cookie
cookies().set("session", session.data.token, {
httpOnly: true,
});

[...]
}),
import { cookies } from "next/headers";

publicProcedure
.input(...)
.mutation(async ({ ctx, input }) => {
[...]

// somehow set a cookie
cookies().set("session", session.data.token, {
httpOnly: true,
});

[...]
}),
This does not set the cookie though -- no Set-Cookie header is in the response. I have no idea how to access the response manually to add the header in either.
Z
Zeryther157d ago
@Derock were you able to find a solution? I'm running into the same problem
N
Nick157d ago
You can put the adapter's req/res into Context and use it directly or wrap it in an abstraction. But the dogmatic answer is "don't", tRPC isn't a REST framework and so wants to pull you away from HTTP/Browser stuff. It's not really the best tool to build an auth system with and works best when you have separate auth and can just pass tRPC a bearer token, like with OpenID-based auth
D
DxD157d ago
@Derock I have the same issue For 3 days I tried
D
Derock157d ago
i have a solution but i am currently in a class. i will let you know how i fixed it later today
D
DxD157d ago
@Derock you saved token in cookie ? Nice…with that I can create the refresh token middleware and auth works I am happy to find you solution @Derock
D
Derock157d ago
@Zeryther / @DxD My solution was the following: inside of the route handler for TRPC, I passed the response headers:
// src/app/api/trpc/trpc/[trpc]
const handler = (req: NextRequest) =>
fetchRequestHandler({
endpoint: "/api/trpc",
req,
router: appRouter,
- createContext: () => createTRPCContext
+ createContext: ({ resHeaders }) => createTRPCContext({ req, resHeaders }),
});
// src/app/api/trpc/trpc/[trpc]
const handler = (req: NextRequest) =>
fetchRequestHandler({
endpoint: "/api/trpc",
req,
router: appRouter,
- createContext: () => createTRPCContext
+ createContext: ({ resHeaders }) => createTRPCContext({ req, resHeaders }),
});
and then updated createTRPCContext to store the resHeaders in the context, and in my tRPC routes I was able to access that and set the cookie using
ctx.resHeaders.set("Set-Cookie", `sessionToken=${token}; Expires=${expire.toUTCString()}; Path=/; HttpOnly; SameSite=Strict`);
ctx.resHeaders.set("Set-Cookie", `sessionToken=${token}; Expires=${expire.toUTCString()}; Path=/; HttpOnly; SameSite=Strict`);
Lastly, the template I used (t3-app) uses unstable_httpBatchStreamLink by default. Setting headers is not supported in this, so I had to use a splitLink so that my auth requests would use httpLink instead.
D
DxD157d ago
And works ?
More Posts
Check if Role is ADMINHey guys I have a private procedure in `T3 Stack`. I need to check if the user thats doing the actioCan middleware be used on a router?Given a router where all procedures need to use the same middleware, can the middleware be somehow aHow can I use `onSettled` in the `experimental_createTRPCNextAppDirClient`?**Context** I want to migrate the following trpc/client hook to the experimental version ```ts consStop initial refetch when prefetched with SSG helpersAnyone else struggling with this, I want to maintain refetching when the tab is refocused but don't Accessing QueryFunctionContext within server queriesHello, I know that the field 'direction' is a new addition within react query v5 as part of the QueHTTP 431: Input too longHi, we're using a complex query (multiple filters etc) with tRPC and react query integration. It hFunction to release context post-batching?In our application every customer has their own schema, therefore we need a db client per request whforwarding headers in solidjsI have a setup with solidstart, and im trying to forward the client headeres to ttrpc. Here's my seSupport @tanstack/react-query 5.4.3will it support 5.4.3 @tanstack/react-query when i install above version with my next.js it unable tHelp with inferring output```ts return ctx.prisma.product.findMany({ include: { price: { select: { Would you recommend tRPC’s usage in this case?So we have two applications, one existing, one about to be started. These two applications will talkHow to limit payload size?Is there a way to limit the payload size? E.g., if a particularly large JSON payload is sent to the Next.js app directoryHi. I have been able to set up tRPC with the app directory in Next.js. It was a frustrating experientrpc errorTrpc not working in next js 14 app router. Please help me to resolveFeature or happy accident: error message from `cause` being used as TRPC's error messageWhen a procedure throws a TRPC error with no message, it turns out that if the thrown error has a caWhen error in tRPC route, the error message is vaugeThere are no line numbers when a runtime error happens in a tRPC route. Surely I am missing somethinHow to have 2 separate trpc clients for http and websockets?I'm trying to have a setup where I can use trpc with 2 separate clients, one for normal HTTP requestHow to configure context for a standalone server?Are there any examples out there on how to set up context for a standalone server? The docs do incluDocs hard to follow with so much `next` codeNot having a great experience with the docs. There are many examples that use `next`, making it hardadding information to the QueryKey that is not part of the procedure inputwe have the situation that we have our trpc routes read some specific information from the browsesr