Extending the Express Request Interface in Typescript to Include Additional Properties

In order to enhance the Express Request interface with a new property called "context" for middleware purposes, I am trying to achieve the following:

const myMiddleware = (req: Request, res: Response, next: NextFunction) => {
  req.context.something = 'something'
  next()
}

Currently, the error message displays:

Property 'context' does not exist on type 'Request'.

To resolve this issue, I attempted declaration merging by creating a custom.d.ts file as follows:

export {}
declare global {
    namespace Express {
        interface Request {
            context?: any
        }
    }
}

I included export {} in the file to prevent an error, but the context property remains elusive.

Augmentations for the global scope can only be directly nested in external modules or ambient module declarations.

Despite researching multiple solutions, extending the Request interface seems undesirable, and modifying the tsconfig.json with typeRoots or files properties did not yield positive results.

An additional suggestion involved using the express-serve-static-core module which also proved ineffective:

declare module 'express-serve-static-core' {
  interface Request {
    context?: any
  }
}

Despite numerous attempts based on similar questions, none of the proposed solutions seem to work in my case, leading me to believe that I might be missing a crucial step.

My project structure is as follows:

tsconfig.json
src/
  custom.d.ts
  some_folder/
    some_file_that_needs_req.context

And here is my current tsconfig.json configuration:

{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es6",
    "allowJs": true
  }
}

Answer №1

When setting up my project, I started by importing Express using the statement:

import * as express from 'express'

However, in my middleware function signature, I mistakenly used (req: Request, res: Response) instead of

(req: express.Request, res: express.Response)
. This caused me to unknowingly use the lib.dom.d.ts Request interface from the typescript package, rather than the intended express Request interface.

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

What seems to be the issue with my @typescript-eslint/member-ordering settings?

I am encountering an issue where my lint commands are failing right away with the error message shown below: Configuration for rule "@typescript-eslint/member-ordering" is throwing an error: The value ["signature","public-static-field","pro ...

Troubleshooting problem with CRUD operations in MySQL, Express, React.js, and Node.js

Is there a way to post data from three input fields in a form to a MySQL database table using Axios? I have attempted multiple times but have been unsuccessful. Can someone provide the code for connecting to the database and inserting the query? //PostFo ...

Issue with API/CORS not fetching while utilizing react-email in ASP.NET/React.JS application

My React App is running at port 44411 and react-email is running at port 3000. I followed a tutorial on setting up react-email, but it didn't work initially. After some troubleshooting, I managed to make my API request go through Postman. The next st ...

Confusing generic function overload in TypeScript

During my exploration of TypeScript, I came across an unusual situation. function concat5<T>(strs: T, strs2: T): T; function concat5(strs: string, strs2: string) { return strs + strs2; } concat5(123, 12); concat5({a:1}, {b:2}); Upon reviewing ...

Implementing Typescript for managing state in React components

Currently, I have a state set up like this: const [newInvoice, setInvoice] = useState<InvoiceType | null>(invoice) The structure of my InvoiceType is as follows: customer_email: string customer_name: string description: string due_date: stri ...

Showing error messages in Angular when a form is submitted and found to be invalid

My form currently displays an error message under each field if left empty or invalid. However, I want to customize the behavior of the submit button when the form is invalid. <form #projectForm="ngForm" (ngSubmit)="onSubmit()"> ...

Tips for eliminating unicode characters from Graphql error messages

In my resolver, I have implemented a try and catch block where the catch section is as follows: catch (err: any) { LOG.error("Failed to get location with ID: " + args.id); LOG.error(err); throw new Error(err); ...

Effortlessly passing props between components using React TypeScript 16.8 with the help

In this scenario, the component is loaded as one of the routes. I have defined the type of companyName as a string within the AppProps type and then specified the type to the component using <AppProps>. Later on, I used {companyName} in the HTML rend ...

What could be causing the 'public' directory to not be served by app.use() after saving, even though the path seems to be correct?

I'm currently working on a tutorial for node and express, but I am facing an issue with the app.use function. Despite following the tutorial exactly, the public directory is not being served as expected. When I visit localhost:3000, I see the word Wea ...

Reorganizing the layout of a React grid in response to changes in screen size

Currently, I'm facing a challenge in creating a container for a React app that includes a Highcharts chart and three textboxes. My struggle lies in getting the three textboxes to adjust and rearrange beneath the chart component when resizing the scree ...

EJS template variable inventory

I'm currently utilizing espress.js in combination with the ejs template engine. My goal is to retrieve a collection of variables that are being passed to the view... Below is an example of a controller: homeAction(req, res) { res.re ...

Could you provide insight into the reason behind debounce being used for this specific binding?

function debounce(fn, delay) { var timer return function () { var context = this var args = arguments clearTimeout(timer) timer = setTimeout(function () { fn.apply(context, args) }, delay) ...

Incorrectly modifying the _locals property while rendering a MySQL result in Express/Node.js leads to the error: "Cannot assign to read only property '_

I am currently using Handlebars to display data retrieved from a MySQL query. The route is set up as shown below: var query = "SELECT col1, col2, col3 FROM table WHERE section >= " + start + " AND section <= " + end + " ORDER BY col1 ASC"; connecti ...

Node.js Development and Production Environments

*** I'm new to nodejs and would love some advice, thank you so much :) I currently have a server running my nodejs application (REST API). My application has two environments (development and production). In development, I frequently update the code ...

Encountering the issue "Unexpected token <" when using express to handle a 304 not modified response for the vue.js library

My Express server setup looks like this: var express = require('express'); var path = require('path'); var app = express(); app.use(express.static('public')); app.use('/', function (req, res) { res.sendFile( ...

Angular's GET HTTP request has resulted in a 500 error message, specifically the Internal Server Error

Attempting to send a GET request to the server where only authenticated users can access a specific route ("/user") after logging in. However, even after a successful login, users are unable to gain access to the "/user" route. A middleware function named ...

Struggling to securely post data to an Express server by hashing passwords with bcrypt?

I'm currently working on developing an API using Express and Sequelize. Specifically, I am writing a function to create a new user where I utilize bcrypt for password hashing. const createNewUser = (data) => { return new Promise(async (resolve, ...

Listening for Internet Connection in Ionic and Angular

Currently, I am working on implementing a listener in my Ionic app that can detect changes in network activity and respond accordingly. import { Component } from '@angular/core'; import { Network } from '@capacitor/network'; @Component ...

To enable iteration of iterators when trying to spread, utilize the TypeScript compiler option '--downlevelIteration'

I have a function that accepts an argument of either an object or an array. const handleScenarioChange = (scenario: Scenario | Scenario[]) => { if (isArray(scenario)) { const scenarios = [...state.selectedScenarios, ...scenario]; const unique ...

Retrieving a single object from an array in node.js utilizing elemMatch

My goal is to extract a single object from an array of objects in a data collection using elemMatch. Here is the sample data: [ { "_id": "5ba10e24e1e9f4062801ddeb", "user": { "_id": "5b9b9097650c3414ac96bacc", "firstName": "blah", ...