Extends Express session SessionData type

Emmanuel Gautier / October 30, 2022

1 min read

Express Session provides a way to store data shared across different HTTP Requests. The mechanism is to set a cookie with a session id, then retrieve and store data by this id during each request processing. This mechanism allows to store a lot of different data. There is a Typescript type named SessionData which allows knowing what contains a session but not the data you will define after without defining them.

To define what is the content of the SessionData type globally in the application, you have to define a file global.d.ts and declare the content of the typing. Here is an example of what can contain the global.d.ts defined:

declare global {
  declare module 'express-session' {
    interface SessionData {
      userId?: string
    }
  }
}

The properties should be always optional since the session created is empty when created.

This way to define session data is the same as every framework using express-session package. NestJS exposes a way to access sessions with express session or the fastify equivalent. This typing definition is exactly the same as NestJS.

Consulting

If you're seeking solutions to a problem or need expert advice, I'm here to help! Don't hesitate to book a call with me for a consulting session. Let's discuss your situation and find the best solution together.

Share this post
Follow the RSS feed