Express.js - Extend type of Request with Typescript

Express.js - Extend type of Request with Typescript

2023-08-04
1 min read

Introduction

This article is going to talk about how to extend Request type in Express.js. Version of Express is 4.18 and Typescript is used 5.1.6

How to do it?

Preparation

First of all, you need to create Modules .d.ts. The file can be in any directory, but this article saves file to src/types/express (express last directory) with file name index.d.ts.

typescript
import express from 'express';

In created file, import express. If you have any types error, installing types for express.js is required

bash
npm i @types/express --dev

Update tsconfig.json

The tsconfig.json file should be a little bit changed.

json
{
  ...
  "typeRoots" : [
    "./src/types",
    "./node_modules/@types"
  ]
  ...
}

Add directory path to created file and all types in node modules into typeRoots property as an Array.
typeRoots property will handle type modules.

Namespace

typescript
declare global {
  namespace Express {
    interface Request {
      user?: Record<string,any>
    }
  }
}

Type declare global to declare global variables. And then Write namespace with Express in global. In namespace, create interface with Request. This example shows extend user object to Request.

Full source code

typescript
import express from 'express';

declare global {
  namespace Express {
    interface Request {
      user?: Record<string,any>
    }
  }
}

That's all. Very Easy!

Ref

Free open source project made by Youngjin