ToP
ToP
TtRPC
Created by ToP on 3/9/2025 in #❓-help
Cannot set headers after they are sent to the client
I have used login system from this repo https://github.com/itsrakeshhq/finance-tracker/tree/main/backend/src/modules/auth but reworked it to tRPC v11 (11.0.0-rc.824). I changed nothing regarding logic, only stuff regarding new version of tRPC and also i am using tRPC standalone not express. Now I have issue when i try to set cookies in authRouter.login
const authRouter = router({
login: publicProcedure
.input(UsersInsertSchema)
.mutation(({ input, ctx }) => new AuthController().loginHandler(input, ctx)),
})
const authRouter = router({
login: publicProcedure
.input(UsersInsertSchema)
.mutation(({ input, ctx }) => new AuthController().loginHandler(input, ctx)),
})
Which leads to:
async loginHandler(data: typeof users.$inferInsert, ctx: Context) {
const { accessToken, refreshToken } = await super.login(data)

const cookies = new Cookies(ctx.req, ctx.res, {
secure: process.env.NODE_ENV === 'production',
})
cookies.set('accessToken', accessToken, { ...accessTokenCookieOptions })
cookies.set('refreshToken', refreshToken, {
...refreshTokenCookieOptions,
})
cookies.set('logged_in', 'true', { ...accessTokenCookieOptions })

return { success: true }
}
async loginHandler(data: typeof users.$inferInsert, ctx: Context) {
const { accessToken, refreshToken } = await super.login(data)

const cookies = new Cookies(ctx.req, ctx.res, {
secure: process.env.NODE_ENV === 'production',
})
cookies.set('accessToken', accessToken, { ...accessTokenCookieOptions })
cookies.set('refreshToken', refreshToken, {
...refreshTokenCookieOptions,
})
cookies.set('logged_in', 'true', { ...accessTokenCookieOptions })

return { success: true }
}
Setting cookies there throws this error.
{
"message": "Cannot set headers after they are sent to the client",
"code": "ERR_HTTP_HEADERS_SENT"
}
{
"message": "Cannot set headers after they are sent to the client",
"code": "ERR_HTTP_HEADERS_SENT"
}
How is that possible? Nothing is sent to client before return from this function right? If I remove cookies code, it works fine. But it is quite important to set cookies for login endpoint 😅 I am stuck on this for hours and I tried everything! Please help 🙏 Node v22.12.0 npm v11.0.0
7 replies