Enhancing the session object with new properties

I am attempting to include extra properties in the session object

req.session.confirmationCode = confirmationCode;

However, I encounter an error stating that the property confirmationCode does not exist

Property 'confirmationCode' does not exist on type 'Session & Partial<SessionData>'.

I have an index.d.ts file located in the types directory where I define this property

declare global {
  namespace session {
    interface SessionData {
      confirmationCode: number;
    }
  }
}

export {};

This is my tsconfig.json configuration file

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "lib": ["dom", "es6", "es2017", "esnext.asynciterable"],
    "sourceMap": true,
    "outDir": "./dist",
    "moduleResolution": "node",
    "removeComments": true,
    "strict": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "resolveJsonModule": true,
    "noImplicitAny": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noStrictGenericChecks": true
  },
  "exclude": ["node_modules"],
  "include": ["src"]
}

In the source code for @types/express-session package, I found out that I can extend the session object like so

declare module "express-session" {
  interface SessionData {
    confirmationCode: number;
  }
}

Yet, when I try this approach, I receive an error mentioning that the session function is not callable

Type 'typeof import("express-session")' has no call signatures

What is the correct way to properly extend the session object?

UPD1: Here is how I invoke the session function

app.use(
  session({
    name: "wishlify",
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false,
    cookie: {
      maxAge: 1000 * 60 * 60 * 24 * 60, // 2 months
      secure: process.env.NODE_ENV === "production",
    },
  })
);

Answer №1

I discovered a solution in the midst of this inquiry.

By inserting export {}; into the index.d.ts file, everything is now operating as intended.

This adjustment transforms the file from a script to a module.

The updated version of the index.d.ts file

declare module "express-session" {
  interface SessionData {
    confirmationCode: number;
  }
}

export {};

Answer №2

Upon delving into the depths of

node_modules > @types > express-session > index.d.ts
, I stumbled upon the definition for Session that caught my attention. (I've stripped away all the comments)

class Session {
  private constructor(request: Express.Request, data: SessionData);
  id: string;
  cookie: Cookie;
  regenerate(callback: (err: any) => void): this;
  destroy(callback: (err: any) => void): this;
  reload(callback: (err: any) => void): this;
    @see Cookie
  resetMaxAge(): this;
  save(callback?: (err: any) => void): this;
  touch(): this;
}

I took the liberty to include a new property in my session, namely userId.

Subsequently, the contents of my

node_modules > @types > express-session > index.d.ts
now appear as follows:

class Session {
  private constructor(request: Express.Request, data: SessionData);
  id: string;
  userId: number; // This addition is what sets it apart.
  cookie: Cookie;
  regenerate(callback: (err: any) => void): this;
  destroy(callback: (err: any) => void): this;
  reload(callback: (err: any) => void): this;
    @see Cookie
  resetMaxAge(): this;
  save(callback?: (err: any) => void): this;
  touch(): this;
}

While I can't guarantee that this approach is foolproof, it certainly served my purpose.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: Android package not found when building a NativeScript app with TypeScript

I encountered the following error message: main-page.ts(15,26): error TS2304: Cannot find name 'android'. This error occurred after setting up a new NativeScript project using TypeScript. tns create demo --template typescript I then added the ...

Showcase the data stored in express-session in a React application

I set up an OpenID passport.js strategy (passport-steam) for my MERN-stack application. The currently logged-in user's data is stored in an express-session, accessible through the object req.session.passport.user in my Node.js file. What is the most ...

Navigating the path requests between React and Express

I am currently developing an app that incorporates login and registration functionality using React and Express. To handle form data and submission, I have implemented Formik in my project: > const initialValues={{username:"", email:"", password:""}} o ...

Using a custom TypeScript wrapper for Next.js GetServerSideProps

I developed a wrapper for the SSR function GetServerSideProps to minimize redundancy. However, I am facing challenges in correctly typing it with TypeScript. Here is the wrapper: type WithSessionType = <T extends {}>( callback: GetServerSideProps&l ...

Dealing with a 404 Error in Node.js and Express Routing

After successfully creating a Node/Express app tutorial earlier, I encountered issues when trying to replicate it for a new project on both Ubuntu and Windows. The basic routing consistently fails and results in 404 errors, which is incredibly frustrating! ...

Error in TypeScript React: 'Display' property is not compatible with index signature

My design page in React with TypeScript template is using Material UI, with custom styles implemented using the sx prop of Material UI. To customize the styling, I have created a separate object for the properties related to the sx props: const myStyles = ...

LambdaFunctionAssociationError: The size of the function code exceeds the maximum allowed limit

Encountering an error while trying to add a Lambda function association to a CloudFront distribution com.amazonaws.services.cloudfront.model.InvalidLambdaFunctionAssociationException: The function code size exceeds the maximum allowed size for functions ...

A peculiar Axios network error occurs exclusively on a particular device

While working on my expo project using react native, I encountered a [AxiosError: Network Error] when attempting to sign up for my app on my iOS device. Interestingly, this error does not occur when using a simulator or Postman, but only when scanning th ...

Issue with dynamically typed object properties in Typescript codebases

Check out this TypeScript code snippet: export type Mutation = (state: State, data: unknown) => void export type Mutations = { [key: string]: Mutation } private buildMutations(): Mutations { return { ['3']: (state, data) => ...

Toggle the visibility of an input field based on a checkbox's onchange event

I am facing a challenge where I need to display or hide an Input/Text field based on the state of a Checkbox. When the Checkbox is checked, I want to show the TextField, and when it is unchecked, I want to hide it. Below is the code snippet for this compon ...

"Troubleshooting issues with data loading using React's useEffect function

While working on my project, I encountered a strange issue where the isLoading state is being set to false before the data fetching process is completed. I am using the useEffect hook to show a loading spinner while fetching data from an API, and then disp ...

Is it time to swap out "localhost" with the service name in Docker?

I have successfully dockerized my reactjs app and express app. Check out the docker-compose.yml file I used: version: "3" services: client: image: react-app build: ./client ports: - "3000:3000" volumes: ...

Tips on adding a new item to a collection only if it doesn't already exist, but if it does, updating the price and quantity when

Greetings, I am a newcomer to Vue and am currently working on building a MEVN application. My goal is to have a functionality where when a user adds an item to their cart, it should store one document in MongoDB. If the user adds more of the same item, onl ...

ExpressJS does not support the 'Save' function

Working on a ticketing API using NodeJS + ExpressJS. Encountering an error when trying to modify a previously created ticket using the PUT method. Error /home/ismael/projects/nodejs-ticketing/routes/ticket.js:38 item.save(function(err){ ...

"Although TypeOrm successfully generates the database, there seems to be a connectivity issue

Attempting to set up a JWT authentication system using NestJs and SQLite. The code successfully generates the SQLite file, but then throws an error stating "Unable to connect to the database." Upon checking with the SQLite terminal, it became apparent that ...

The most effective method for dynamically incorporating tables into a Node.js and Express application using Sequelize

After conducting some research, I have hit a roadblock in finding the right solution. My project involves creating a personal budgeting application using node, Express, and Sequelize. The goal is to allow users maximum flexibility by dynamically generating ...

Array of JSON data passed in the request body

Recently, I have been attempting to pass JSON data to my req.body. The data structure is as follows: answers = ["A","B"]; //An array to be included in the JSON Object var Student_Answers = { //JSON object definition Answers: answers, matricNumber: ...

Providing structured Express app to deliver HTML and JavaScript content

Currently, I am working with Express and facing a seemingly simple challenge. Here is the structure of my directories: |-config |---config.js |---routes.js |-server.js |-scripts |---controllers |------controllers.js |---directive ...

Is it not possible to call this authentication expression in a Typescript file when using Next JS?

I am currently developing a sign-in method for my Next.js application and I have been referring to the GitHub repository's recommended documentation. However, upon reaching the authentication folder step, I encountered an error regarding the sign-in ...

What happens when an OPTIONS request is processed with the `preFlightContinue` setting enabled?

Recently, I came across the concept of a "preflight OPTIONS request" in Express that I realize I don't fully understand. This is typically how it's handled: const cors = require('cors'); const app = express(); app.use(cors({ preflig ...