2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Express】ミドルウェアで共通処理を一元化する

Posted at

はじめに

Express.jsは、Node.jsでWebアプリケーションを構築するためのフレームワークです。

その中でミドルウェアは、リクエストとレスポンスの間に挟み込み、共通の処理を担う非常に便利な機能です。

この記事では、Expressで共通処理をミドルウェアとして実装する方法を記載します。

開発環境

開発環境は以下の通りです。

  • Windows11
  • Node.js 22.18.0
  • npm 11.5.2
  • Express 5.0.3
  • TypeScript 5.9.2
  • tsx 4.20.5

環境構築

まずは、今回のプロジェクトで必要なパッケージをインストールします。

# プロジェクトフォルダを作成
mkdir express-middleware-sample
cd express-middleware-sample

# package.jsonを作成
npm init -y

# 必要なパッケージをインストール
npm install express
npm install -D typescript @types/node @types/express tsx

# tsconfig.jsonを作成
npx tsc --init

サンプルコードの実装

今回は、すべてのリクエストに対して、リクエストが来た時刻とURLをログに出力するミドルウェアを作成します。

1. ロギングミドルウェアの実装

src/middlewares/logger.ts というファイルを作成し、以下のコードを記述します。

src/middlewares/logger.ts
import type { Request, Response, NextFunction } from "express";

export const loggerMiddleware = (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  // リクエストURLと時刻をログ出力
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);

  // 次のミドルウェアまたはルートハンドラへ処理を渡す
  next();
};

ミドルウェアは、RequestResponseNextFunctionの3つの引数をとる関数です。
next()を呼び出すことで、次の処理にバトンを渡します。これを忘れると、処理がそこで止まってしまいます。

2. アプリケーション本体の実装

次に、このミドルウェアを使うアプリケーション本体を作成します。src/index.tsというファイルに以下のコードを記述します。

src/index.ts
import express from 'express';
import { loggerMiddleware } from './middlewares/logger'; // 作成したミドルウェアをインポート

const app = express();
const port = 3000;

// 作成したミドルウェアを適用
// すべてのリクエストに対してこのミドルウェアが実行される
app.use(loggerMiddleware);

// ルートハンドラ
app.get('/', (req, res) => {
  res.send('Hello, Express!');
});

app.get('/about', (req, res) => {
  res.send('This is the about page.');
});

// サーバーを起動
app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});

app.use(loggerMiddleware)と記述することで、GET /GET /aboutなどのすべてのルートハンドラが実行される前にloggerMiddlewareが実行されます。

動作確認

実装したアプリケーションを起動して、正しく動作するか確認します。

  1. ターミナルで以下のコマンドを実行

    # アプリケーションをtsxで起動
    npx tsx src/index.ts
    

    サーバーが起動し、「Server is running at http://localhost:3000」と表示されます。

  2. ブラウザで以下のURLにアクセス

    • http://localhost:3000/
    • http://localhost:3000/about
  3. ターミナルを確認すると、以下のようなログが出力される

    Server is running at http://localhost:3000
    [2025-08-24T09:13:00.000Z] GET /
    [2025-08-24T09:13:00.001Z] GET /about
    

    アクセスしたタイミングで、ミドルウェアがログを出力していることが確認できます。

まとめ

Expressのミドルウェアを使うことで、認証、ロギング、エラーハンドリングといったアプリケーション全体で共通して行いたい処理を、各ルートハンドラから分離して記述することができます。
これにより、コードの再利用性が高まり、保守性も向上します。

参考

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?