374

I’m trying to add a property to express request object from a middleware using typescript. However I can’t figure out how to add extra properties to the object. I’d prefer to not use bracket notation if possible.

I’m looking for a solution that would allow me to write something similar to this (if possible):

app.use((req, res, next) => {
    req.property = setProperty(); 
    next();
});
1
  • 1
    you should be able to extend the request interface that the express.d.ts file provides with the fields you want. Commented May 22, 2016 at 19:17

35 Answers 35

356

You want to create a custom definition, and use a feature in Typescript called Declaration Merging. This is commonly used, e.g. in method-override.

Create a file custom.d.ts and make sure to include it in your tsconfig.json's files-section if any. The contents can look as follows:

declare namespace Express {
   export interface Request {
      tenant?: string
   }
}

This will allow you to, at any point in your code, use something like this:

router.use((req, res, next) => {
    req.tenant = 'tenant-X'
    next()
})

router.get('/whichTenant', (req, res) => {
    res.status(200).send('This is your tenant: '+req.tenant)
})
Sign up to request clarification or add additional context in comments.

12 Comments

Not working for me: I get Property 'tenant does not exist on type 'Request' ` Doesn't make a difference if I explicitly include it in tsconfig.json or not. UPDATE With declare global as @basarat pointet out in his answear works, but I had to do import {Request} from 'express' first.
FWIW, this answer is now obsolete. JCM's answer is the correct way to augment the Request object in expressjs (4.x at least)
For future searches - a good example I found that worked out of the box: github.com/3mard/ts-node-example
@EricLiprandi Who is JCM and where is the answer you're referring to? Please link when referencing another answer. Names can change over time.
@devklick that is a very good question! I guess the answer has since been deleted... I have not dealt with that in a few years. But I would assume basarat's answer would be the authority. He is kind of a big deal ;)
|
257

As suggested by the comments in the index.d.ts, you simply declare to the global Express namespace any new members. Example:

declare global {
  namespace Express {
    interface Request {
      context: Context
    }
  }
}

Full Example:

import * as express from 'express';

export class Context {
  constructor(public someContextVariable) {
  }

  log(message: string) {
    console.log(this.someContextVariable, { message });
  }
}

declare global {
  namespace Express {
    interface Request {
      context: Context
    }
  }
}

const app = express();

app.use((req, res, next) => {
  req.context = new Context(req.url);
  next();
});

app.use((req, res, next) => {
  req.context.log('about to return')
  res.send('hello world world');
});

app.listen(3000, () => console.log('Example app listening on port 3000!'))

More

Extending global namespaces is also covered in the TypeScript Deep Dive.

10 Comments

Why is global needed in the declaration? What happens if its not there?
This works with interfaces, but in case anyone needs to merge types, note that types are "closed" and cannot be merged: github.com/Microsoft/TypeScript/issues/…
I also had to add to my tsconfig.json: { "compilerOptions": { "typeRoots": ["./src/typings/", "./node_modules/@types"] }, "files": [ "./src/typings/express/index.d.ts" ] }
What I don't understand is the casing of Express. Why does it need to be Express instead of express? Is the way it works that the first letter of the library should be capitalized?
what if I have like 10-20 definition files? Do I have to include all of them manually?
|
153

For newer versions of express, you need to augment the express-serve-static-core module.

This is needed because now the Express object comes from there: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/8fb0e959c2c7529b5fa4793a44b41b797ae671b9/types/express/index.d.ts#L19

Basically, use the following:

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

16 Comments

This worked for me, whereas extending the plain-old 'express' module did not. Thank you!
Was struggling with this, in order to get this to work, I had to import the module as well: import {Express} from "express-serve-static-core";
@andre_b Thanks for the hint. I think that the import statement turns the file into a module, and this is the part that's necessary. I've switched to using export {} which also works.
Make sure the file this code goes in is not called express.d.ts, otherwise the compiler will try to merge this in to the express typings, resulting in errors.
Make sure your types must be first in typeRoots! types/express/index.d.ts and tsconfig => "typeRoots": ["./src/types", "./node_modules/@types"]
|
122

After trying 8 or so answers and not having a success. I finally managed to get it working with jd291's comment pointing to 3mards repo.

Create a file in the base called types/express/index.d.ts. And in it write:

declare namespace Express {
    interface Request {
        yourProperty: <YourType>;
    }
}

and include it in tsconfig.json with:

{
    "compilerOptions": {
        "typeRoots": ["./types"]
    }
}

Then yourProperty should be accessible under every request:

import express from 'express';

const app = express();

app.get('*', (req, res) => {
    req.yourProperty = 
});

12 Comments

Works for Express v4.17.1 and typescript v4.3.4
What if I want to customize different requests with different custom props?
need to wrap the namespace in a declare global {} and this will work.
@MattGoodwin, I too had to do this. But can you explain why?
Weird thing is happening. When I write the global definition in the file types/express.d.ts it doesn't work. But, if the file is types/express/index.d.ts it works. No idea what the hell is going on!
|
62

The accepted answer (as the others) does not works for me but

declare module 'express' {
    interface Request {
        myProperty: string;
    }
}

did. Hope that will help someone.

8 Comments

Similar method is described in ts docs under "Module Augmentation". It's great if you don't want to use *.d.ts files and just store your types within regular *.ts files.
this is the only thing that worked for me as well, all other answers seem to need to be in .d.ts files
This works for me as well, provided that I put my custom-declarations.d.ts file in the TypeScript's project root.
I extended the original type to preserve it: import { Request as IRequest } from 'express/index'; and interface Request extends IRequest. Also had to add the typeRoot
After trying every answer, this is the only one that worked for me. For now, i had to add it directly to my main file, i hope i'll find another way that will be cleaner.
|
56

None of the offered solutions worked for me. I ended up simply extending the Request interface:

import {Request} from 'express';

export interface RequestCustom extends Request
{
    property: string;
}

Then to use it:

import {NextFunction, Response} from 'express';
import {RequestCustom} from 'RequestCustom';

someMiddleware(req: RequestCustom, res: Response, next: NextFunction): void
{
    req.property = '';
}

Edit: Depending on your tsconfig, you may need to do it this way instead:

someMiddleware(expressRequest: Request, res: Response, next: NextFunction): void
{
    const req = expressRequest as RequestCustom;
    req.property = '';
}

12 Comments

that will work, but quite verbose if you have 100s of middleware functions, amirite
As of 1.10.2020, it seems like creating a new interface that extends the Response/Request interface from Express itself, should work totally fine. I have interface CustomResponse extends Response { customProperty: string} and where I call it someMiddleware(res: CustomResponse) and it works fine, with access to properties that exist both on Response and the newly defined interface.
I prefer this method, its more explicit and clear than silently extending the request object somewhere behind the scenes. Makes it clear what properties are yours and what are from the source module
"Depending on your tsconfig" - depending on what property of the tsconfig? I want to change it accordingly to be able to use the interface solution. Why does this not work by default, seems a bit against the rules of OOP to me..
I think, @Yusuf and I got the same error: Type '(req: CustomRequest, res: Response<any, Record<string, any>>) => Promise<void>' is not assignable to type 'RequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'. Types of parameters 'req' and 'req' are incompatible.
|
52

In 2025 this one is working:

With express 4.17.1 the combination of https://stackoverflow.com/a/55718334/9321986 and https://stackoverflow.com/a/58788706/9321986 worked:

in types/express/index.d.ts:

declare module 'express-serve-static-core' {
    interface Request {
        task?: Task
    }
}

and in tsconfig.json:

{
    "compilerOptions": {
        "typeRoots": ["./types"]
    }
}

BTW: Think twice if you want to do this! I did this when I didn't know about TDD - now I can't imagine to not use tests for code in my daily work - and "poluting" the request object and letting it wander around in the application increases the chance that you need to mock the req for a lot of tests. Maybe it's better to read about Clean Code, SOLID, IOSP, IOSP 2.0 and IODA and things like that and understand why adding properties to the request to have it available "at the other end of the app" might not be the best idea.

6 Comments

Finally found one that worked :)
This worked for me!
finally worked for me
does not work for me, and caused my entire project to get errors because it started importing the wrong Request. And both your references are linked to the question itself
I tried this but I when I run my app it crashes and I get an error: TSError: ⨯ Unable to compile TypeScript
|
43

Alternative solution

This is not actually answering to the question directly, but I'm offering an alternative. I was struggling with the same problem and tried out pretty much every interface extending solution on this page and none of them worked.

That made me stop to think: "Why am I actually modifying the request object?".

Use response.locals

Express developers seem to have thought that users might want to add their own properties. That's why there is a locals object. The catch is, that it's not in the request but in the response object.

The response.locals object can contain any custom properties you might want to have, encapsulated in the request-response cycle, thus not exposed to other requests from different users.

Need to store an userId? Just set response.locals.userId = '123'. No need to struggle with the typings.

The downside of it is that you have to pass the response object around, but it's very likely that you are doing it already.

https://expressjs.com/en/api.html#res.locals

Typing

Another downside is the lack of type safety. You can, however, use the generic types on the Response object to define what's the structure of the body and the locals objects:

Response<MyResponseBody, MyResponseLocals>

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/express/index.d.ts#L127

Caveats

You cannot really guarantee that the userId property is actually there. You might want to check before accessing it, especially in case of objects.

Using the example above to add an userId, we could have something like this:

interface MyResponseLocals {
  userId: string;
}

const userMiddleware = (
  request: Request,
  response: Response<MyResponseBody, MyResponseLocals>,
  next: NextFunction
) => {
  const userId: string = getUserId(request.cookies.myAuthTokenCookie);
  // Will nag if you try to assign something else than a string here
  response.locals.userId = userId;
  next();
};

router.get(
  '/path/to/somewhere',
  userMiddleware,
  (request: Request, response: Response<MyResponseBody, MyResponseLocals>) => {
    // userId will have string type instead of any
    const { userId } = response.locals;

    // You might want to check that it's actually there
    if (!userId) {
      throw Error('No userId!');
    }
    // Do more stuff
  }
);

5 Comments

A more notable downside of this is that response.locals remains untyped. Any value stored in it is any.
That is very much true, but I'm happy to accept it as a trade off.
Since Request and Response are Genereics by definitions, since locals have been defined exactly for that, this should be the accepted answers. I desagree with Martti Laine, Response.locals should be strongly typed using this method. But you have to specify "interface MyResponseLocals extends Record<string, any>{...}" to match the generic constraint
I disagree. res.locals are for exposing stuff to the client. RES is Client Context not Server Context. "This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on to templates rendered within the application."
It does not solve the problem if your request object is altered by another middleware. For example if you use express-session then it adds 'session' property to your 'req' and then you are back at square 1
30

All of these responses seem to be wrong or outdated in some way or another.

This worked for me in May, 2020:

in ${PROJECT_ROOT}/@types/express/index.d.ts:

import * as express from "express"

declare global {
    namespace Express {
        interface Request {
            my_custom_property: TheCustomType
        }
    }
}

in tsconfig.json, add / merge the property such that:

"typeRoots": [ "@types" ]

Cheers.

3 Comments

Works with Webpack + Docker, import* can be replaced with export {};
Doesn't work. Property 'user' does not exist on type 'Request'.
same here, did you manage to solve it @OliverDixon?
21

I solved this problem by creating a new type without extending the Request type globally.

import { Request } from 'express'
    
type CustomRequest = Request & { userId?: string }

You must use extend properties with optional(?) operator to not have 'No overload matches this call' error.

Package Versions :

    "@types/express": "^4.17.13",
    "@types/morgan": "^1.9.3",
    "@types/node": "^17.0.29",
    "typescript": "^4.6.3",
    "express": "^4.18.0",

2 Comments

Personally, I like this solution the best, as it feels much more typescript-esque, the namespace variant seems much more extended-javascript-esque.
This is the way to do it, nice work. Eloquent solution for the win.
19

If you are looking for solution that works with express4, here it is:

@types/express/index.d.ts: --------must be /index.d.ts

declare namespace Express { // must be namespace, and not declare module "Express" { 
  export interface Request {
    user: any;
  }
}

tsconfig.json:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es2016",
    "typeRoots" : [
      "@types", // custom merged types must be first in a list
      "node_modules/@types",
    ]
  }
}

Ref from https://github.com/TypeStrong/ts-node/issues/715#issuecomment-526757308

4 Comments

Cannot find module 'express' or its corresponding type declarations.
Thank you. Spent 2 days trying ti fix this
This is the correct response 👏
This is what worked for me. Thank you!
17

While this is a very old question, I stumbled upon this problem lately.The accepted answer works okay but I needed to add a custom interface to Request - an interface I had been using in my code and that didn't work so well with the accepted answer. Logically, I tried this:

import ITenant from "../interfaces/ITenant";

declare namespace Express {
    export interface Request {
        tenant?: ITenant;
    }
}

But that didn't work because Typescript treats .d.ts files as global imports and when they have imports in them they are treated as normal modules. That is why the code above doesn't work on a standard typescript setting.

Here's what I ended up doing

// typings/common.d.ts

declare namespace Express {
    export interface Request {
        tenant?: import("../interfaces/ITenant").default;
    }
}
// interfaces/ITenant.ts

export interface ITenant {
    ...
}

6 Comments

This works for my main file, but not in my routing files or controllers, I get no linting, but when I try to compile it says "Property 'user' does not exist on type 'Request'." (I'm using user instead of tenant), but if I add // @ts-ignore above them, then it works (though that's a silly way to fix it of course. Do you have any thoughts on why it may not be working for my other files?
That is a very strange thing @Logan. Can you share your .d.ts, tsconfig.json and the use instance? Plus, what version of typescript are you using as this importing in global modules is only supported starting from TS 2.9? That could help better.
I've uploaded data here, pastebin.com/0npmR1Zr I'm not sure why the highlighting is all messed up though This is from the main file prnt.sc/n6xsyl This is from another file prnt.sc/n6xtp0 Clearly some part of it understands what's going on, but the compiler does not. I'm using version 3.2.2 of typescript
Suprisingly, ... "include": [ "src/**/*" ] ... Works for me but "include": ["./src/", "./src/Types/*.d.ts"], doesn't. I haven't gone in dept in trying to understand this yet
Importing interface by using dynamic imports works for me. Thanks
|
14

This answer will be beneficial to those who rely on npm package ts-node.

I was also struggling with the same concern of extending request object, I followed a lot of answers in stack-overflow & ended with following the below-mentioned strategy.

I declared extended typing for express in the following directory. ${PROJECT_ROOT}/api/@types/express/index.d.ts

declare namespace Express {
  interface Request {
    decoded?: any;
  }
}

then updating my tsconfig.json to something like this.

{
  "compilerOptions": {
     "typeRoots": ["api/@types", "node_modules/@types"]
      ...
  }
}

even after doing the above steps, the visual studio stopped complaining, but unfortunately, the ts-node compiler still used to throw.

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

Apparently, the ts-node was not able to locate the extended type definitions for request object.

Eventually after spending hours, as I knew the VS Code was not complaining & was able to locate the typing definitions, implying something is wrong with ts-node complier.

Updating start script in package.json fixed it for me.

"start": "ts-node --files api/index.ts",

the --files arguments play a key role here find determining the custom type definitions.

For further information please visit: https://github.com/TypeStrong/ts-node#help-my-types-are-missing

4 Comments

The --files flag for ts-node was the missing piece for why I couldn't get merged types to work for me.
This one's the winner!!!
Thanks a lot. I had the same issue. --files worked for me too
Thank you:)) can confirm the --files flag for ts-node worked
13

This is what worked for me when using Nestjs and Express. As on Nov 2020.

Create a file: ./@types/express-serve-static-core/index.d.ts

Note: must have exactly the above path and file name. So that Typescript declaration merging will work.

import { UserModel } from "../../src/user/user.model";

declare global{
    namespace Express {
        interface Request {
            currentUser: UserModel
        }
    }
}

add this to your tsconfig.json

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

3 Comments

For some reason, only your solution almost worked for me. It's just that it wouldn't work unless I declare Express directly without global.
@Danry declare global is only needed when you import any modules in the same *.d.ts file
amazing that no solution "just works"
10

In TypeScript, interfaces are open ended. That means you can add properties to them from anywhere just by redefining them.

Considering that you are using this express.d.ts file, you should be able to redefine the Request interface to add the extra field.

interface Request {
  property: string;
}

Then in your middleware function, the req parameter should have this property as well. You should be able to use it without any changes to your code.

7 Comments

How do you "share" that information throughout your code? If I define a property in Request, say Request.user = {}; in app.ts how does userController.ts know about it?
@Nepoxx if you redefine an interface the compiler will merge the properties and make them visible everywhere, that's why. Ideally you'd do the redefinition in a .d.ts file. :)
That seems to work, however if I use the type express.Handler ( instead of manually specifying (req: express.Request, res: express.Response, next: express.NextFunction) => any)), it does not seem to refer to the same Request as it complains that my property does not exist.
I wouldn't expect it to, unless express.Handler extends the Request interface. does it?
I can make that work if I use declare module "express" but not if I use declare namespace Express. I'd rather use the namespace syntax but it just doesn't work for me.
|
7

2024 update

I was trying to find modern way in a new project to extend Response.locals and tried almost everything in this thread again and had no luck (came here by Google search forgetting all about that I posted this answer before).

So I wanted to share what finally worked for me was:

// somePath/express/index.d.ts <--- Make sure it is in tsconfig "include"
import 'express';

interface Locals {
  message?: string;
}

declare module 'express' {
  export interface Response  {
    locals: Locals;
  }
}

To help anyone who is just looking for something else to try here is what worked for me in late May of 2020 when trying to extend ExpressJS' Request. I had to have tried more than a dozen things before getting this to work:

  • Flip the order of what everyone is recommending in the "typeRoots" of your tsconfig.json (and don't forget to drop the src pathing if you have a rootDir setting in tsconfig such as "./src"). Example:
"typeRoots": [
      "./node_modules/@types",
      "./your-custom-types-dir"
]
  • Example of custom extension ('./your-custom-types-dir/express/index.d.ts"). I had to use inline import and default exports to use classes as a type in my experience so that is shown too:
declare global {
  namespace Express {
    interface Request {
      customBasicProperty: string,
      customClassProperty: import("../path/to/CustomClass").default;
    }
  }
}
  • Update your nodemon.json file to add the "--files" command to ts-node, example:
{
  "restartable": "rs",
  "ignore": [".git", "node_modules/**/node_modules"],
  "verbose": true,
  "exec": "ts-node --files",
  "watch": ["src/"],
  "env": {
    "NODE_ENV": "development"
  },
  "ext": "js,json,ts"
}

1 Comment

I am from 2021. Still doesn't work
6

I have same problem and resolve it like this:

// /src/types/types.express.d.ts
declare namespace Express {
    export interface Request {
        user: IUser
    }
}

But some conditions are required!

  1. Add to tsconfig.json config
"paths": {
    "*": [
        "node_modules/*",
        "src/types/*"
    ]
},

After this tsc will build bundle, but ts-node not.

  1. You must add --files to compiler command
ts-node --files src/server.ts

2 Comments

This worked for me, except for second part - I added the paths to the the typeRoots property of my tsconfig file. "typeRoots": [ "./node_modules/*", "./src/types/*" ]
Thank you for this, this is very simple and worked for me. I only want id from the user here what i did only 2 steps src/types/types.express.d.ts declare namespace Express { export interface Request { id: string } } in tsconfig.json "paths": { "*": [ "./src/types/*" ] }
5

One possible solution is to use "double casting to any"

1- define an interface with your property

export interface MyRequest extends http.IncomingMessage {
     myProperty: string
}

2- double cast

app.use((req: http.IncomingMessage, res: http.ServerResponse, next: (err?: Error) => void) => {
    const myReq: MyRequest = req as any as MyRequest
    myReq.myProperty = setProperty()
    next()
})

The advantages of double casting are that:

  • typings is available
  • it does not pollute existing definitions but extends them, avoiding confusion
  • since the casting is explicit, it compiles fines with the -noImplicitany flag

Alternatively, there is the quick (untyped) route:

 req['myProperty'] = setProperty()

(do not edit existing definition files with your own properties - this is unmaintainable. If the definitions are wrong, open a pull request)

EDIT

See comment below, simple casting works in this case req as MyRequest

3 Comments

@akshay In this case, yes, because MyRequest extends the http.IncomingMessage. It it were not the case, double casting via any would be the only alternative
It is recommended that you cast to unknown instead of any.
Casting like this unfortunately requires the same repeated casting in every subsequent function in the chain. For example middleware1, middleware2, middleware3, AND the route itself. But this is the only implementation I've found that implements context-relevant typings, rather than just globally extending Request and putting every possible property on that.
5

Maybe this issue has been answered, but I want to share just a little, now sometimes an interface like other answers can be a little too restrictive, but we can actually maintain the required properties and then add any additional properties to be added by creating a key with a type of string with value type of any

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

interface IRequest extends Request {
  [key: string]: any
}

app.use( (req: IRequest, res: Response, next: NextFunction) => {
  req.property = setProperty();

  next();
});

So now, we can also add any additional property that we want to this object.

2 Comments

This one worked for me.
This give me errors when using Strict: true in my tsconfig.json. Although it works runtime.
5

If you tried all the answers and still didn't get it to work, here is a simple hack

app.use((req, res, next) => {
    (req as any).property = setProperty(); 
    next();
});

This will cast the req object to any, therefore you can add any property you want. Keep in mind that by doing this you will lose type safety with req object.

1 Comment

you can just turn off typescript!
4

Solution which finally worked for me with typescript 4.8.4 and express 4.18.2:

Taking this COMMENT and wrapping the whole thing in "declare global" like this:

declare global {
  declare module 'express-serve-static-core' {
    interface Request {
      userId?: string;
    }
  }
}

File structure:

/typeDeclarations/express/index.d.ts
/tsconfig.json

I have also added path to my declarations to the tsconfig file, but everything also worked without it.

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

Comments

3

I used response.locals object to store the new property. Here is the complete code

export function testmiddleware(req: Request, res: Response, next: NextFunction) {
    res.locals.user = 1;
    next();
}

// Simple Get
router.get('/', testmiddleware, async (req: Request, res: Response) => {
    console.log(res.locals.user);
    res.status(200).send({ message: `Success! ${res.locals.user}` });
});

Comments

2

on mac with node 12.19.0 and express 4, using Passport for auth, I needed to extend my Session object

similar as above, but slightly different:

import { Request } from "express";


declare global {
  namespace Express {
    export interface Session {
      passport: any;
      participantIds: any;
      uniqueId: string;
    }
    export interface Request {
      session: Session;
    }
  }
}

export interface Context {
  req: Request;
  user?: any;
}```

Comments

2

Simple solution which worked for me is to create a new custom interface extending express Request. This interface should contain all your custom req properties as optional. Set this interface as type for the middleware req.

// ICustomRequset.ts
   import { Request } from "express"
   export default interface ICustomRequset extends Request {
       email?: string;
       roles?: Array<string>;
   }

// AuthMiddleware.ts
...
export default async function (
  req: ICustomRequset,
  res: Response,
  next: NextFunction
) {
  try {
      // jwt code
      req.email=jwt.email
      req.roles=jwt.roles
      next()
  }catch(err){}

3 Comments

This question is about the addition of custom properties to existing request interface that can only be done using type declaration files.
@AbhishekPankar why would you say that extension can only be done using type declaration files? @AshiSultan 's implementation looks fine to me. Admittedly I can't get it to work though. Typescript doesn't like when this middleware is applied on the final route.No overload matches this call
@defraggled What I meant was without using external interfaces, type declaration is the only solution
2

I've usually followed one of the examples in the other answers, but in my latest project extending the Request type is not reliable. So I ended with a different solution that retains the per request middleware-to-middleware communication without monkey patching.

Initially set up a really small module using a WeakMap providing a middleware to initialise and a getter for the context later

import type { Request } from 'express'

export interface Context {
    // Put whatever you're sharing in here
}

// Intentionally not exported to avoid shenanigans
const contextStore = new WeakMap<Request, Context>()

export function createContextMiddleware(request: Request) {
    contextStore.set(request, {
        // Initialise shared context
    })
}

export function getContext(request: Request): Context | undefined {
    return contextStore.get(request)
}

And the consuming middleware will use getContext(req) and do a null check to avoid mishaps

export const myExcellentMiddleware = function (req, res) {
    const ctx = getContext(req)
    if (!ctx) {
        // This should be handled as an 500 internal server error
        throw new Error('Server error')
    }

    // Have fun coding ...
}

It depends on a global approach, but it acts like it's only available to the middleware per request because of the WeakMap. WeakMap is excellent here as you don't have to think about discarding unused values stored in it, because when GC events happen it will automatically remove it for you.

Depending on how much you trust the future contributors and review processes you can assume there will always be a context for each request by:

  • adding a non-null assertion to the end of the get (.get(request)!),
  • removing the unedfined union, and
  • remove the null checks in the middleware.

I for one make mistakes and prefer to leave strong reminders for good code.

1 Comment

This is the correct answer. It introduces a request-scoped store without monkey-patching Express types in in potentially misleading ways.
1

It might be already quite late for this answer, but anyway here is how I solved:

  1. Make sure you have your types source included in your tsconfig file (this could be a whole new thread)
  2. Inside your types directory add a new directory and name it as the package you want to extend or create types for. In this specific case, you will create a directory with the name express
  3. Inside the express directory create a file and name it index.d.ts (MUST BE EXACTLY LIKE THAT)
  4. Finally to make the extension of the types you just need to put a code like the following:
declare module 'express' {
    export interface Request {
        property?: string;
    }
}

Comments

1

The easiest method is to extend the type you want and add your own properties

in tsconfig.ts specify the root of local types

{
  // compilerOptions:
  "typeRoots": ["node_modules/@types", "**/@types"],
}

now create any .d.ts file inside @types, you can put @types in the root or anyware.

@types/express.d.ts

declare namespace Express {
  interface Request {
    // add arbitrary keys to the request
    [key: string]: any;
  }
}

Comments

1

dep : "@types/express": "^4.17.17" "typescript": "^5.1.6"

My goal is add __platform as req object attribute and define req.body req.query type. Below is the specific code I want to use.

import Request from 'express';
interface QueryProps{
  username: string;
}
interface BodyProps{
  witdh: number;
  height: number;
}
type IRequest = Request<object,object,BodyProps,QueryProps>
function testHandler(req:IRequest,res,next){
  req.__platform // no error
  req.query.username // no error 
  req.body.with // no error 
  req.body.height // no error
}

below ts type declare works for me.

// index.d.ts
import { Request as ExpressRequest } from 'express';
declare module 'express' {
  interface Request extends ExpressRequest {
    __platform: string;
  }
}
declare module 'express-serve-static-core' {
  interface Request {
    __platform: string;
  }
}

Comments

1

for typescript 5.8

(not sure lowest version supported)

express official support override Request, no more patch or declare "module" or any config needed.

  1. create file any/where/in/project/any-file-name.d.ts
  2. write this:
declare namespace Express {
    export interface Request {
        io: SocketIO.Server;
        user: JwtPayload;
        property: string;
    }
}
  1. use it anywhere:
import type {Request} from 'express';

someRouter.use((req:Request) => {
    console.log(req.user);
});
  • you can ctrl+click Request in export interface **Request** to see what you can extend
  • you can declare namespace Express any times you want, to make everything modular

1 Comment

Bro A Life saver thanks alot!!
0

For simple case, I use the headers property in outer middleware and get it later in inner middleware.

// outer middleware
req.headers["custom_id"] = "abcxyz123";

// inner middleware
req.get("custom_id");

drawbacks:

  • can only store string. if you want to store other types such as json or number, you might have to parse it later.
  • the headers property is not documented. Express only documents the req.get() method. So you have to use the exact version of Express that works with property headers.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.