Expanding the session object with express-session

Seeking assistance with TypeScript and Express session integration.

I've been exploring ways to extend my session object, specifically through merging typings based on the documentation provided:

In my types/session.d.ts file, I have the following interface that needs to be merged:

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

However, I am encountering an issue where the merge is not working as expected. For instance, in other-folder/some.ts:

req.session.userId = user.id;
// Property 'userId' does not exist on type 'Session & Partial<SessionData>'.

On the other hand, importing Session from express-session seems to resolve the error:

import { Session } from 'express-session'

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

Despite this solution, I am hesitant about importing a module in a type definition, especially since TypeScript issues a warning stating:'Session' is declared but its value is never read.

With limited expertise in TypeScript, I'm unsure if this approach is correct. Any suggestions on what could be done differently?

Your insights are much appreciated!

PS: While my tsconfig setup appears to be correct and functional for other type definitions, this specific scenario presents a challenge.

Answer №1

To enhance your modules, consider using Module Augmentation. Understanding the concept of modules is crucial, as discussed in Modules:

When working with TypeScript, files that include top-level import or export statements are viewed as modules. On the other hand, files lacking such declarations are treated as scripts, where their contents are globally accessible (including by modules).

Consider this example:

./src/main.ts:

import express from 'express';
import session from 'express-session';

const app = express();

app.use(
  session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: true },
  }),
);
app.get('/', (req, res) => {
  const user = { id: '1' };
  req.session.userId = user.id;
});

./types/session.d.ts: Ensure you have at least one top-level import or export statement to signify this file as a module, not a script. You may need to import interfaces or types from third-party node modules, but in this scenario, it is unnecessary. Simply add export {} or import 'express-session'.

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

export {};

tsconfig.json:

"typeRoots": [
  "./node_modules/@types",
  "./types",
], 

Package versions:

"express": "^4.17.1",
"@types/express": "^4.17.11",
"typescript": "^3.9.7"
"express-session": "^1.17.1",
"@types/express-session": "^1.17.3",

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

Ways to include a simple authentication header in a form

Currently, I have set up a node server using the code from https://github.com/passport/express-4.x-local-example. I made a minor change by switching from app.get('/login' to app.post('/login' in my server.js file. In pug, I designed a ...

Angular function implementing a promise with a return statement and using the then method

I have a function in which I need to return an empty string twice (see return ''. When I use catch error, it is functioning properly. However, I am struggling to modify the function so that the catch error is no longer needed. This is my current ...

Vuetify 3 does not display dialogs

I am attempting to integrate vuetify 3.alpha with vue 3. Below are the files I am working with: Temp.vue (obtained from vuetify example) <template> <div class="text-center"> <v-dialog v-model="dialog" w ...

The installed NPM package does not contain the necessary TypeScript compiled JS files and declaration files

I have recently released a TypeScript library on NPM. The GitHub repository's dist (Link to Repository Folder) directory includes all compiled JavaScript and d.ts files. However, after running npm i <my_package>, the resulting module contains on ...

Define the static property as an array containing instances of the same type

I created a class called Foo with a static property named instances that holds references to all instances. Then, I have another class called Bar which extends Foo: class Foo { static instances: Foo[]; fooProp = "foo"; constructor() { ...

Guide to Triggering a Page View Event in Google Tag Manager with Angular

Previously, I manually fired the Page View Event using JavaScript from app.component.ts while directly accessing Google Analytics: declare var gtag: Function; ... constructor(private router: Router) { const navEndEvents = this.router.events.pipe( fil ...

Troubleshooting Generic Problems in Fastify with TypeScript

I am currently in the process of creating a REST API using Fastify, and I have encountered a TypeScript error that is causing some trouble: An incompatible type error has occurred while trying to add a handler for the 'generateQrCode' route. The ...

I'm encountering a ReferenceError while using nodemon - specifically, it states that the variable "app" is

Encountering ReferenceError: app is not defined. The error message along with the source code is provided below [nodemon] restarting due to changes... [nodemon] starting node server.js D:\ebl\server\app\routes.js:4 app.get('/hea ...

Perform an action after the Ngx Bootstrap modal has been hidden

My modal features a login button: <button type="button" (click)="save()" class="btn btn-primary"> login </button> Upon clicking the button, my desired outcome is to: first hide the modal, and second navigate to another route. However, ...

What is the process of creating an instance of a class based on a string in Typescript?

Can someone please guide me on how to create an instance of a class based on a string in Nestjs and Typescript? After conducting some research, I attempted the following code but encountered an error where it says "WINDOWS is not defined." let paul:string ...

Having trouble retrieving data when updating a user in ExpressJS

Trying to update an experience array in the User model with new data, but facing issues with saving the data in the exec function. As a result, unable to push the new data to the array on the frontend. Here is the current code snippet: router.post('/ ...

Can you explain the significance of the "@" symbol in the `import from '@/some/path'` statement?

When I use IntelliJ IDEA to develop a web application in TypeScript, the autocomplete feature suggests imports from other files within my project like this: import {Symbol} from '@/components/Symbol'; I am curious about the significance of the @ ...

Receiving a Typescript error stating "Property '0' does not exist on type X" when incorporating auto-generated GraphQL code into the project

I'm struggling to comprehend how to rectify this typographical error. Here's the snippet of code causing me trouble: <script lang="ts"> import type { PlayerListQuery } from "queries"; export let player: PlayerListQ ...

Angular template error: Potential is present but not defined

Encountering an issue with my Angular application's template file (dashboard.component.html). The error message reads "Object is possibly 'undefined'." Here's the portion of the template that seems to be causing the problem: <div> ...

Using Generic Types in Response DTO with Typescript, NestJs, and Class Transformer

In my project, I am dealing with multiple endpoints that provide responses along with pagination details. My goal is to have a single parent type for the pagination and be able to use different data types for the data parameter. I attempted the following ...

When it comes to mapping routes in the express framework of Node.js

Currently, I am facing an issue while setting up the route in my app.js file. The route for the listing of flights is passed in the routes/flights.js file. When I define the route at the bottom of all routes, it results in a 404 error. However, if I place ...

Can you please provide information on the specific type of decorator used in Vuex, known as the 'vuex-class' decorator

My TypeScript project has the 'no-implicit-any' rule enabled, but I'm facing challenges when it comes to defining types for all of the 'vuex-class' decorators. For instance, when importing the namespaced action @(namespace('f ...

What could be causing the missing helper error when a previously functioning section of code is now experiencing issues?

Attempting to process a get request for a form using express, here is the code in question: app.get('/newsletter', function(req, res){ res.render('newsletter'); }); An error occurs when the request is made: > Error: Missing helper ...

Develop a type definition utilizing dotted paths from a recursive object model

Working with TypeScript, I am dealing with a nested object structure of functions defined as: type CallbackFn = (args: any) => any type CallbackObj = { [key: string]: CallbackFn | CallbackObj } const callbacks = { foo: function(args: { x: num }): st ...

Trying to connect to a socket.io server from a remotely hosted page returns an error stating "require undefined."

Trying to connect to a socket.io server hosted on Heroku from a remote client. The client site is hosted on XAMPP running on my PC. Encountering an issue with the client-side JavaScript const io = require("socket.io-client"); An error is thrown in the co ...