LoginSignup
6
5

More than 3 years have passed since last update.

Express4とtypescriptでreq.userを使えるようにする

Posted at

ミドルウェアで次のようにユーザー情報をいれようとしました。

app.use((req, res, next) => {
  req.user = hogehoge;
});

怒られました。

Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'

いろいろ調べた結果、globalにExpressのrequestを拡張すればよいことがわかりました。
https://stackoverflow.com/questions/37377731/extend-express-request-object-using-typescript/58788706

やり方

@types/express/index.d.ts というフォルダとファイルを作る。

名前は必ずこれである必要あり。フォルダの場所はアプリルートでも、srcフォルダ以下でもよい。

// req.user が使えるようにする。
declare namespace Express {
  export interface Request {
      user: any;
  }
}

tsconfig.jsonを編集する

typeRootsを追加。自分で先程追加した@typesの場所とnode_modules/@typesを追加。この場合はsrc/以下に作ったのでsrc/@typesとなっている。

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

これでうまくいきました。

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5