Working with cookies in openAPIHandler #960
-
I'm not able to recover the cookie or send it. I used the help functions but they didn't work either. import { createServer } from 'node:http'
import { setCookie } from '@orpc/server/helpers'
import { CORSPlugin } from '@orpc/server/plugins'
import { PORT, VERSION } from '@/constants/config'
import { ZodSmartCoercionPlugin } from '@orpc/zod'
import { OpenAPIHandler } from '@orpc/openapi/node'
import { ZodToJsonSchemaConverter } from '@orpc/zod/zod4'
import { OpenAPIReferencePlugin } from '@orpc/openapi/plugins'
import { router } from './router'
const prefix = '/api'
const openAPIHandler = new OpenAPIHandler(router, {
plugins: [
new CORSPlugin(),
new ZodSmartCoercionPlugin(),
new OpenAPIReferencePlugin({
docsProvider: 'scalar', // ou swagger
schemaConverters: [new ZodToJsonSchemaConverter()],
docsPath: '/docs',
specGenerateOptions: {
info: {
title: 'oRCP - Documentation',
version: VERSION,
},
},
}),
],
})
const server = createServer(async (req, res) => {
const headers = new Headers()
headers.forEach((value, key) => res.setHeader(key, value))
const result = await openAPIHandler.handle(req, res, {
prefix: '/api',
context: { headers },
})
setCookie(headers, 'sessionIdss', '123456', {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
})
if (!result.matched) {
res.statusCode = 404
res.end('Not found')
}
})
const url = `http://localhost:${PORT}${prefix}`
server.listen(PORT, () => {
console.log(`
───────────────────────────୨ৎ────────────────────────
𖤍 Server: ${url}
𖤍 Documentation: ${url}/docs
───────────────────────────୨ৎ────────────────────────
`)
}) export const loginRoute = os
.$context<{ headers: Headers }>()
.route({ method: 'POST', path: '/identity/login' })
.handler(async ({ context }) => {
if (context.headers === undefined) {
return {
message: 'Bad Request',
}
}
const name = 'name'
const cookieString = serialize(name, 'joao', {
path: '/',
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
})
context.headers.append('Set-Cookie', cookieString)
console.log({ 'Set-Cookie': context.headers.get('Set-Cookie') })
const cookieHeader = context.headers.get('cookie')
console.log({ cookieHeader })
console.log({ getCookie: getCookie(context.headers, name) })
if (!cookieHeader) {
return {
message: 'No cookie header present',
}
}
console.log({
pase: parse(cookieHeader)[name],
})
return { message: 'Login successful' }
}) {
"Set-Cookie": "name=joao; Path=/; HttpOnly; SameSite=Strict",
}
{
cookieHeader: null,
}
{
getCookie: undefined,
} obs: This was just a test because I wanted to make an auth cookie, but even though I managed to save the cookie in storage, I couldn't read it later with any route. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 14 replies
-
Hi @DIEGOHORVATTI! I'm Dosu and I’m helping the orpc team. The main issue is that your context.headers is a new, empty Headers object per request—it does not contain the incoming request's headers, so it can't be used to read cookies sent by the client. The setCookie and getCookie helpers only operate on the Headers abstraction you provide, and oRPC does not automatically parse or propagate cookies between Node.js req/res and your context.headers. This means:
Here's a minimal pattern: const server = createServer(async (req, res) => {
// Initialize headers with incoming request headers
const headers = new Headers(req.headers);
// Pass headers to context
const result = await openAPIHandler.handle(req, res, {
prefix: '/api',
context: { headers },
});
// Set cookies for the response
setCookie(headers, 'sessionIdss', '123456', { /* options */ });
// Write all headers to the response
headers.forEach((value, key) => res.setHeader(key, value));
if (!result.matched) {
res.statusCode = 404;
res.end('Not found');
}
}); This way, getCookie will work as expected, and cookies you set will be sent to the client. There is no built-in middleware in oRPC that does this for you—you need to handle it manually in your server code [source] [source]. To reply, just mention @dosu. How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other |
Beta Was this translation helpful? Give feedback.
-
Here are mistakes in your snippets: const server = createServer(async (req, res) => {
const headers = new Headers()
headers.forEach((value, key) => res.setHeader(key, value))
const result = await openAPIHandler.handle(req, res, {
prefix: '/api',
context: { headers },
})
setCookie(headers, 'sessionIdss', '123456', {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
})
if (!result.matched) {
res.statusCode = 404
res.end('Not found')
}
})
const cookieString = serialize(name, 'joao', {
path: '/',
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
})
context.headers.append('Set-Cookie', cookieString)
console.log({ 'Set-Cookie': context.headers.get('Set-Cookie') })
const cookieHeader = context.headers.get('cookie')
console.log({ cookieHeader })
console.log({ getCookie: getCookie(context.headers, name) })
The main important here is |
Beta Was this translation helpful? Give feedback.
And use this instead of
new Header(req.headers)
https://orpc.unnoq.com/docs/plugins/request-headers