TS2339: Issue with extending the Express Request object with properties such as req.payload

I'm in the process of converting my Express app to TypeScript and running into an issue with middleware storing data in the request object.

Even though I define req.payload, I keep encountering an error. Here's a snippet of my code:

// server.ts

import { Application } from 'express';
import { Request, Response, NextFunction } from 'express';

import express from 'express';
const app: Application = express();

function middleware1(req: Request, res: Response, next: NextFunction) {
  req.payload = {
    name: 'bob',
  };

  next();
}

app.use(middleware1);

app.get('/', (req, res, next) => {
  res.json({ message: 'hello world' });
});

const PORT = process.env.PORT || 5005;

app.listen(PORT, () => {
  console.log(`Server listening on port http://localhost:${PORT}`);
});

Attempting to manipulate req.payload triggers this TypeScript error:

Property 'payload' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.(2339)

To resolve this, I referred to this article on extending Express Request interface.

I added a file @types/express/index.d.ts like so:

// @types/express/index.d.ts

declare global {
  namespace Express {
    interface Request {
      payload?: {};
    }
  }
}

I updated tsconfig.json as follows:


// tsconfig.json

// ...

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

Despite trying various configurations in the declaration file and tsconfig.json, I'm still stuck with the same error.

Is there anything else I should be doing?

Here's a simplified version of the code on StackBlitz

Answer №1

Understanding the global scope may be a bit tricky, and it's also important to consider declaring namespaces. Here's a suggested solution:

@types/express/index.d.ts:

declare namespace Express {
  interface Request {
    payload?: {};
  }
}

If you're using ts-node, don't forget to include the "files" property in your tsconfig.json file as well:

{
  "compilerOptions": {
    //...
  },
  "files": ["src/@types/express/index.d.ts"]
}

Feel free to check out this example on stackblitz for more insights: https://stackblitz.com/edit/stackblitz-starters-d48bzi?file=src%2F%40types%2Fexpress%2Findex.d.ts,src%2Fserver.ts

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

Using `next()` after custom middleware execution leads to an error being thrown

I have been working on setting up viewpages to display the authenticated user's information, such as their name or email, when they are logged in. To achieve this, I am utilizing the res.locals function to store the user data globally for easy access ...

Unraveling the mysteries of webpack configuration

import * as webpack from 'webpack'; ... transforms.webpackConfiguration = (config: webpack.Configuration) => { patchWebpackConfig(config, options); While reviewing code within an Angular project, I came across the snippet above. One part ...

creating a pre-filled date input field in the user interface

Hey there, I'm just getting started with vmware clarity UI. Currently, I am facing an issue with using datetime-local. I am trying to prepopulate the current date and time in the datetime-local field using ngModel with the format 2017-06-13T13:00. Whi ...

What is the best way to fetch all the orders from my product schema using response.send?

This is my custom Product schema const productSchema = new mongoose.Schema({ title: { type: String, required: [true, "Title is required"] }, details: { type: String, required: [true, "Details are r ...

Employing socket.io for transmitting data to a particular view or ID

Currently, I am developing a web application that utilizes NodeJS, Express, and MongoDB. Within this application, there is a view accessible to all users which displays different images based on the selection made by the user (no login required). This spec ...

leveraging external transports in winstonjs

Encountering an issue where the logger is only functioning properly with local strategies when called from an export function inside a controller triggered by HTTP requests, while slack and sentry notifications are not being sent. The setup for the logger ...

ExpressJS method override not functioning properly for hidden PUT method in HTML form

Using express and mongoose/mongo to develop a task management application. Concept: Authors can set reminders. In the app.js file: var bodyParser = require('body-parser') var methodOverride = require('method-override') app.use(bodyPar ...

One way to determine the sequence in which spec files are executed using jest is by specifying the order manually. For example, you can designate spec.file1.js to run before spec

Is there a way to configure jest so that my spec files are run in the following order: spec.file2.js, spec.file3.js, spec.file5.js, spec.file1.js I could use some assistance with setting this up... ...

Issue with Vercel Deployment: 'Page Cannot Be Found - Error 404'

When attempting to deploy my API on Vercel, I consistently encounter the same issue. The problem arises when: https://i.sstatic.net/6JjUJ.png I am using Node, Express, and Typescript. My project consists of a dist folder, as well as an initial src directo ...

Exporting an angular component as a module

I have successfully created a widget using Angular elements that works well in HTML. However, I am unsure of how to export it as a module for use in other Angular, React, Vue web applications. I want to be able to import import { acmaModule } from package- ...

Easy-to-use blog featuring Next.js 13 and app router - MDX or other options available

Currently in the process of transitioning a Gatsby website to Next.js (v13.4) and utilizing the new App Router. However, I'm facing some challenges when it comes to migrating the blog section over because there isn't much accurate guidance availa ...

What is the method to access the information within the observer?

When I receive the data from the observer in the console, here is what I see: https://i.stack.imgur.com/dVzwu.png However, I am only interested in extracting this specific data from each item on the list: https://i.stack.imgur.com/g8oHL.png To extract ...

The console is displaying 'undefined' when attempting to render the JSON response in Vue

In my vue.js application, I'm trying to display text using TypeScript. Here is an example of the JSON response: { "data": [ { "firstName": "Foo", "lastName": "Smith" }, { "firstName": "Mi ...

The stacked bar chart in Apex is not displaying correctly on the x-axis

Currently, I am utilizing the Apex stacked bar chart within my Angular 16 project. In this scenario, there are 4 categories on the x-axis, but unfortunately, the bars are not aligning correctly with the x-axis labels. The data retrieved from my API is as ...

Storing data consistently across connections in a Node/Express API

Currently, I am in the process of developing a Node/Express API front-end that connects to a MongoDB. While everything works smoothly with a single connection, issues arise when there are 2 or more connections. Whenever I attempt to make simultaneous call ...

Next.js allows for the wrapping of a server component within a client component, seamlessly

I am currently working on a project where I have implemented a form to add data to a JSON using GraphQL and Apollo Client. The project is built with TypeScript and Next.js/React. However, I am facing a conflicting error regarding server client components ...

Sending an HTTP request from within an Express/Node.js application

I am currently in the process of setting up an express service for a program I am developing. The goal is to interact with an external API, retrieve the data, and store it in a MongoDB database that I have already set up. While this task may seem straight ...

The error message "TypeError: Router.use() expects a middleware function, but received a [type of function]" is a common occurrence in FeathersJS

Struggling to bind a method to my /userAuthenticationInfo route, I've made several adjustments in my code based on other posts related to this issue but still unable to make it work. I am using feathersJS's express implementation, and even with e ...

Creating an array of objects using Constructors in Typescript

Utilizing TypeScript for coding in Angular2, I am dealing with this object: export class Vehicle{ name: String; door: { position: String; id: Number; }; } To initialize the object, I have followed these steps: constructor() { ...

Error encountered when initializing a variable within the constructor of a TypeScript file in Angular 4

This is the content of my app.component.html file PL Auth Username: Password : Generate OTP Enter OTP : Login This is the code in my app.component.ts file import { Component, OnInit } from '@angular/core' ...