I'm having trouble understanding how to handle cookies with tRPC.
I'm confused particularly about how to send cookies back from the server, and then how to read the cookies from the res. Every SO and GitHub post I've found regarding tRPC cookies has not helped.
Here's a sample of my code so you have an idea as to where I'm at.
Feel free to ask any clarifying questions
// backend/index.ts
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
app.use(cookieParser())
app.use(
"/login/v1",
trpcExpress.createExpressMiddleware({
router: loginRouter,
createContext: createLoginContext
})
);
app.listen(PORT, () => console.log(`server is running on port ${PORT}`));
// backend/router.ts
export async function createLoginContext({req,res}: trpcExpress.CreateExpressContextOptions) {
return {
req,
res
}
}
export type LoginContext = trpc.inferAsyncReturnType<typeof createLoginContext>
export const loginRouter = trpc.router<LoginContext>()
.mutation('testCookies', {
async resolve({ctx, input}):Promise<any> {
console.log(ctx.req.cookies);
ctx.res.cookie('I set this cookie','cooookkiiieee')
return ??
}
});
// client/requests.ts
const createLoginRouter = () => {
return createTRPCClient<LoginRouter>({
url: "http://localhost:5000/login/v1",
headers: {
// use universal cookie to set a cookie property?
}
})
}
export const testCookiesRequest = async() => {
const client = createLoginRouter()
try {
const val = await client.mutation('testCookies')
return val
} catch(e) {
throw e
}
}