fastify / fastify/help

setNotFoundHandler does not include session variable in request object

Open
#1,039 7 comments 0 reactions 0 assignees View on GitHub
help wanted question
Dominant language
No language data
Stars
68
Forks
8
Avg merge
11h 2m
Merged PRs (30d)
2

Description

## 💬 Question here

Normally all request objects include the session variables if a user is logged in. However `setNotFoundHandler` does not making my display, which normally shows the user's avatar if logged in or a login button if not, always show the login button. How do I get the session variables when using `setNotFoundHandler` or is there an alternative approach to catch all invalid routes that will return session variables?

```js
app.setNotFoundHandler(async (request, reply) => {
const pageInfo = {
title: 'Page Not Found',
role: 'guest'
}
console.log({ pageInfoUser: request.user })
if (request.user) {
pageInfo.role = request.user.role
pageInfo.user = request.user.email
}
pageInfo.errorImage = '/img/errors/404-error.svg'
pageInfo.errorMessage = 'This is not the page you\'re looking for.'
reply.code(404)
reply.header('Content-Type', 'text/html; charset=utf-8')
reply.type('text/html')
reply.send(await generatePage(pageInfo, 'error.html'))
})
````

In this case `console.log({ pageInfoUser: request.user })` returns `undefined` even when logged in whereas every other route displays the `user` session variable when logged in.

## Your Environment

- *node version*: 22.3.0
- *fastify version*: 4.28.1
- *@fastify/secure-session version*: 7.5.1
- *os*: Windows

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.