What steps can I take to eliminate the overload error that occurs when I extend the Request object in Express?

I'm having trouble extending Express' Request object to access req.user, and I'm encountering an overload error. I've attempted a couple of solutions, but none of them seem to work for me.

EDIT: I am currently using Passport.js and JWT

Extend Express Request object using Typescript

Unable to extend Express Request in TypeScript

I've tried two different methods to extend Express' Request object:

  1. Using interface extend. This method sort of works, but I receive an overload error preventing me from compiling with 'tsc':

overload error

// index.d.ts file

import { IUser } from "../models/user";
import { Request } from "express";


export interface IUserRequest extends Request {
  user: IUser; // or any other type
}
  1. Creating a global namespace. This approach doesn't work as I'm unable to access the req.user property. I've attempted importing { Request } from "express", but it doesn't seem to work for this option due to the 'Request is declared but never used' error:
//index.d.ts file

import { IUser } from "../models/user";
// import { Request } from "express"

export {};

declare global {
  namespace Express {
    interface Request {
      user?: IUser;
    }
  }
}

This is the post controller that attempts to access req.user:

export const admin_code_post = [
  body("admin_code", "Wrong code buddy")
    .trim()
    .escape()
    .custom((value: string) => {
      if (value !== process.env.SECRET_CODE) {
        throw new Error("Admin code is incorrect");
      }
      return true;
    }),
  (req: IUserRequest, res: Response, next: NextFunction) => {
    const errors = validationResult(req);

    if (!errors.isEmpty()) {
      res.render("admin_code", {
        title: "Enter Code",
        errors: errors.array(),
        user: req.user,
      });
      return;
    }

    User.findOneAndUpdate(
      { username: req.user?.username }, // issue here if I create a global namespace
      { admin: true },
      (err: Error, user: IUser) => {
        if (err) return next(err);

        res.render("index", {
          title: "Welcome",
          user,
        });
      }
    );
  },
];

Unable to find req.user when using global namespace method

This is my tsconfig.json :

{
    "compilerOptions": {
      "target": "es2016",   
      "module": "commonjs", 
      "rootDir": "./src",   
      "typeRoots": [
        "./node_modules/@types",
        "./types"
      ],                    
      "sourceMap": true,    
      "outDir": "dist",     
      "noEmitOnError": true,
      "esModuleInterop": true,
      "forceConsistentCasingInFileNames": true,           
      "strict": true,                                   
      "noImplicitAny": true
    },
    "include": ["./src/**/*"],
    "exclude": ["node_modules"],
    "ts-node": {
      "files": true
    },
    "files": [
      "./src/types/index.d.ts"
    ]
  }
  

What am I doing wrong? Any suggestions would be greatly appreciated.

Answer №1

The second method you are considering should work with the following adjustments,

import { IUser } from "../models/user";

declare global {
  namespace Express {
    export interface Request { 
      user?: IUser;
    }
  }
}

Ensure that this code is placed in a file with a *.d.ts extension. For more information on namespaces and declaration merging, please refer to the documentation.

UPDATE

I just realized that you are using passport js. In the index.d.ts file of passport js, you can find the following lines of code,

declare global {
    namespace Express {
        interface AuthInfo {}
        interface User {}

        interface Request {
            authInfo?: AuthInfo | undefined;
            user?: User | undefined;

Therefore, the interface we defined earlier will not work. You can try,

const user = req.user as IUser example

or you can modify your index.d.ts as follows,

export {};

declare global {
  namespace Express {
    interface User {
      first_name: string;
      last_name: string;
      username: string;
      email: string;
      admin: boolean;
    }
  }
}

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

Is there a way to drop a pin on the Google Maps app?

Is there a way to pinpoint the specific location on Google Maps? <google-map id="map-container" width="100%" height="100%" class="maps"></google-map> ...

Angular 8: ISSUE TypeError: Unable to access the 'invalid' property of an undefined variable

Can someone please explain the meaning of this error message? I'm new to Angular and currently using Angular 8. This error is appearing on my console. ERROR TypeError: Cannot read property 'invalid' of undefined at Object.eval [as updat ...

Ways to ascertain if a TypeScript type is a specific value

Can a utility type be created to identify whether a type is a literal value? For example: type IsLiteral<T> ... type IsStringALiteral = IsLiteral<string> // false type IsStringLiteralALiteral = IsLiteral<'abc'> // true type IsS ...

Is it feasible to utilize GraphQL subscriptions with Azure Functions?

Exploring the potential of implementing GraphQL subscriptions on Azure Functions. Unfortunately, it seems that apollo-server-azure-functions may not be compatible. Are there any other options or strategies to successfully enable this functionality? ...

What are the benefits of schema creation compared to simply adding another field?

Looking to store featured products like staff picks and category-specific featured items in my system with a limit of 10 documents. Prioritizing read performance over write performance, I am considering three approaches: Add boolean fields like is_bests ...

Framer Motion's AnimatePresence feature fails to trigger animations when switching between pages

I'm running into issues with the Framer Motion library, specifically with the AnimatePresence transition. I've managed to make it work in normal situations, but when I encapsulate my Routes within a custom implementation, the exit animation fails ...

Trouble with removing elements from an array using DELETE request in Express.js

Currently, I am in the process of developing an API for my front end using Postman to manage different HTTP commands in order to create a simple to-do list. In this project, I have implemented an array to store information from POST requests and retrieve i ...

Is there a way to automatically determine the parameters of a constructor to match the default class type in TypeScript

I need a function in a class that can utilize a type from constructor arguments, but I am unsure how to achieve this. class CustomClass<Type1, Type2=any>{ a: string = 'a' constructor(private readonly parameters: { attributes: Type ...

Adding TypeScript definition file to an npm package: A step-by-step guide

Is it possible to include typescript definitions (.d.ts files) in a pure javascript project without using TypeScript itself? I'm struggling to find any information on how to do this directly in the package.json. ...

Unable to load routes from ./app.js in the file ./src/routes/index.js

Just dipping my toes into the world of nodejs. I recently moved all my routes from app.js to a separate file located at PROJECT_DIR/src/routes/index.js. However, when I try to open the page in my browser, it displays "Cannot GET /wines". Below are snippets ...

Obtaining JSON Data from API using Angular 2 Http and the finance_charts_json_callback() Callback

Having trouble retrieving JSON data from this API: I'm unsure how to access the returned finance_charts_json_callback(). Currently, I am utilizing Angular 2's http.get(): loadData() { return this.http .get(this.url) .map((res) => ...

struggling to implement dynamic reactive forms with Angular

Currently, I am experimenting with building a dynamic reactive form using Angular. While I have successfully implemented the looping functionality, I am facing some challenges in displaying it the way I want. <form [formGroup]="registerForm" (ngSubmit) ...

In mongoose, documents are able to update autonomously without any explicit request

I have encountered an issue with my verification logic. I am sending email links to users for verification, but they are getting verified even before clicking on the link. Below is the code snippet used for user registration: router.post("/register", asyn ...

Discover the power of catching Custom DOM Events in Angular

When working with an Angular library, I encountered a situation where a component within the library dispatches CustomEvents using code like the following: const domEvent = new CustomEvent('unselect', { bubbles: true }); this.elementRef.nati ...

Tips on effectively utilizing a function within middleware in Node.js

I've successfully used the checkAuth function with this format: router.get('/login', checkAuth, function(){ }) Now I'm wondering how to utilize the checkAuth function with this format: routes file router.get('/login', con ...

Error in Typescript for callback function: The type 'Function' does not match any signature

I am encountering an error stating that Type 'Function' does not match the signature for the filter function below. This is because the filter function expects a specific type. How can I define my callback function to align with what the filter f ...

Transfer items on a list by dragging and dropping them onto the navigation label of the target component

I'm currently exploring how to move an element from a list to a <div> and then see it transferred to another list. The objective is to allow users to drag items from one list onto the labels in a sidebar navigation, causing the item to switch t ...

Can a standard tuple be matched with its corresponding key?

This code snippet showcases a function that can recognize that the key "banana" cannot have the value "red": type Fruits = { banana: 'yellow' | 'green' strawberry: 'red' } const fruit = <K extends keyof Fruits>(modu ...

Learn how to serve JSON results without rendering any views or CSS using Express.js 4

I am currently utilizing express 4 to develop a json API service, but I am encountering difficulties in sending a simple json without attempting to render the view. var express = require('express'); var router = express.Router(); modul ...

Why am I getting the "Cannot locate control by name" error in my Angular 9 application?

Currently, I am developing a "Tasks" application using Angular 9 and PHP. I encountered a Error: Cannot find control with name: <control name> issue while attempting to pre-fill the update form with existing data. Here is how the form is structured: ...