😃
fastify-cookieでreq.cookieがnullになる
結論
fastify-cookieの登録がonRequestの後だった場合、fastifyのonRequest Hook内だとreq.cookiesがnullになります。
app.addHook('onRequest', async (req, reply) => {
console.log(req.cookies) // null
}
app.register(fastifyCookie) // fastify-cookieの登録
app.get('/hoge/', (req, reply) => {
console.log(req.cookies) // { ~~ }
})
req.cookiesのinterfaceは以下のものであり、本来nullになるはずがなかったため結構ハマりました。
interface FastifyRequest extends SignerMethods {
/**
* Request cookies
*/
cookies: { [cookieName: string]: string | undefined };
}
少しだけ中身を眺める
ここで最初にnullに初期化してるっぽい。
そのあと、onRequest後にには以下の部分でcookieをparseしてくれるっぽいのだが、
これが本家fastifyの後のonRequesthookの後に走るので、onRequestでは cookieがnullになるといった感じ。
おわり
半日溶けたので、app.registerはなる早で実行しておいた方がいいのかも。
Discussion