Extending the Request type from Express with Typescript

Having a NodeJs app with Express and Typescript, I am attempting to extend the Request type from Express.

I have created an index.d.ts file with the following code snippet:

import { User } from "models/user";

declare global {
  namespace Express {
    export interface Request {
      currentUser: User
    }
  }
}

Although my code editor (VSCode) indicates that everything is fine and autocomplete is working correctly, TypeScript throws an error at runtime:

src/api/controllers/post.controller.ts:60:24 - error TS2339: Property 'currentUser' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'.

To resolve this issue, I came across the following code snippet which solved my problem:

import { User } from 'models/user';
declare module "express-serve-static-core" {
  export interface Request {
    currentUser: User
  }
}

I had to place this code in any file within my app for it to work. However, I am still puzzled as to why this solution works while the initial one does not. Can anyone provide an explanation?

I am running my app using the ts-node package with the command ts-node ./src/index.ts

Here is my tsconfig.json file:

{
  "compilerOptions": {
    "target": "ES2016",                          
    "module": "commonjs",                     
    "strict": true,                           
    "baseUrl": "./src",                       
    "typeRoots": [
      "./src/@types",
      "./node_modules/@types"
    ],                       
    "types": ["reflect-metadata"],                           
    "experimentalDecorators": true,        
    "emitDecoratorMetadata": true,         
    "skipLibCheck": true,                     
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"],
  "exclude": [
    "node_modules"
  ]
}

Answer №1

To utilize the newer versions of express, it is essential to enhance the express-serve-static-core module.

This enhancement is necessary because the Express object now originates from there: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/8ab6e159d4a832c6fea8704b32f814624ae680de/types/express/index.d.ts#L19

To implement this, simply add the following:

@types/express/index.d.ts

import { Express } from "express-serve-static-core";

declare module 'express-serve-static-core' {
  interface Request {
    myField?: string
  }
  interface Response {
    myField?: string
  }
}

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

VueJs with typescript encounters issues with recursive child components, resulting in a warning stating "Unknown custom element" being thrown

I am currently working on a dynamic form that is generated by a DataTypeObject (dto). I have encountered an issue with a warning message while creating recursive components. This warning points to a list of components with the same type as their parent: ...

Learning to retrieve the value from a dynamically generated input tag in a TypeScript file

<div *ngFor="let task of arrayList"> <input id="task.fieldName" *ngIf="task.key === 'Others'" type="text" class="form-control"> </div> When dealing with dynamically created input fields based on a condition, the challenge is ac ...

Using Pocketbase OAuth in SvelteKit is not currently supported

I've experimented with various strategies, but I still couldn't make it work. Here's the recommendation from Pocketbase (): loginWithGoogle: async ({ locals }: { locals: App.Locals }) => { await locals.pb.collection('users' ...

Storing Data with expressjs/session in NodeJS

My development project involves 3 files: app.js, index.js (routes), and Users.js (controller). Upon successful user login (verification between POST data and the database), I aim to store information in a session using expressjs/session. Below is how I c ...

Having trouble opening video files with fs.readFileSync in node.js?

I'm having trouble retrieving a video file by sending the file name as a request parameter to an express router endpoint. Although I can see the parameter logged in the console using console.log, I am unable to see the actual video file data logged. I ...

NodeJs: The local server seems to be stuck on loading and is not displaying any information

I am currently working on a new project that involves using JS, NodeJS, and SQL. While this is not my first time working with these technologies, I am facing an issue where the backend endpoint keeps loading when I try to test it. The only difference this ...

Node.js integration with PayPal IPN consistently reports as invalid

I've read through multiple discussions on this topic, but after going through every thread, I still can't get it to work. Before throwing in the towel, I want to make one final attempt: My setup includes the latest version of nodejs with express ...

Is it possible for a Node.js/Express server to securely handle all UTF-8 characters?

At the moment, my setup involves a node server running Express that is connected to a PostgreSQL database with UTF-8 encoding support. In terms of frontend, I'm using Angular which has built-in measures for preventing unsafe injection. I am curious i ...

Synchronizing data between Node.js server and client

For my latest project, I decided to create a unique HTTP ping health monitor using React and Node.js. My idea is to develop a monitor that utilizes intervals to send axios requests to the server for URL information, which will then be displayed on the clie ...

Issue arose when attempting to remove an item from an array within React

I have a handleAd function that adds new components to an array, and I also have a handleDelete function that is supposed to remove the selected element from the array. I am generating unique keys for each element to prevent deletion issues. Initially, th ...

Upon clicking a button, I aim to retrieve the data from the rows that the user has checked. I am currently unsure of how to iterate through the rows in my mat-table

My goal is to iterate through the column of my mat-table to identify the rows that have been checked, and then store the data of those rows in an array. <td mat-cell *matCellDef="let row"> <mat-checkbox (click)="$event.stopPropagation()" (c ...

Can specifying the view engine in ExpressJS restrict res.render() to search for templates only in the views folder?

When I set this app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); Does it automatically make res.render([path]); start in the views directory? In simpler terms, is res.render() alw ...

The node.js express app.get and app.post are currently malfunctioning

I have encountered an issue with my Express JS code. Currently, I am using app.use and everything works perfectly. However, when I try to use app.post or app.get instead of app.use, the code stops working and my IDE (WebStorm) does not recognize these meth ...

Exploring the process of inferring union types in TypeScript

const type p1 = { a: number, b: string } const type p3 = { a: string } const type p4 = p1 | p3 let sample: p4 = { a: '123', b: '123' } function checkP3(obj: p4): obj is p3 { return typeof (<p3>obj).a === 'string' ...

What is causing the net::ERR_CONNECTION_RESET in Node JS and ExpressJS?

Our application, built on ExpressJS and NodeJS, is hosted on a Linode server and served at port 3000. Although the app has been functioning well for a year, we have recently encountered consistent connection errors. The errors vary, but they are mostly re ...

Ways to confirm the visibility of a web element on the screen with serenity-js

In the current project, I am utilizing the Serenity-js BDD framework with a screenplay pattern approach. However, I am encountering an issue when attempting to assert the visibility of an element on a web page using the "that" method from the Ensure class. ...

Problem with Andular's datepicker functionality and local change detection

Currently, we are facing a challenge where local change detection is necessary for our component to improve performance, but it causes issues with the mat datepicker overlay. When navigating with arrow keys within the overlay and changing the month or year ...

In search of a fresh and modern Facebook node template

I've been on the hunt across the internet for a quality node.js Facebook template, but all I seem to stumble upon is this https://github.com/heroku/facebook-template-nodejs. It's okay, but it's built using express 2.4.6 and node 0.6.x. I wan ...

What could be causing the images to not display on my HTML page?

My program is designed to display an image based on the result of the random function. Here is my HTML: <div> <h2>Player 0:</h2> <div id="MainPlayer0"></div> </div> Next, in my TypeScript fi ...

Can you tell me the origin of the callback function in this express application?

After completing some freecodecamp exercises, I decided to dive into the Express js tutorial provided by MDN at this link for backend development. I've hit a roadblock in understanding where the callback in the async.parallel function is sourced from ...