- 最終更新
- 2026/08/17
3秒でわかる
リクエストが本処理に届く前と、応答が返る途中に割り込ませる共通処理。ログや認証チェックを各処理へ書き写さず、1 か所にまとめておくために使います。
30秒図解
もう少し詳しく
どういうものか
Web フレームワークにおける
Express なら (req, res, next) をnext() を
なぜ必要か
ログイン確認、
具体例
const express = require("express");
const app = express();
// 全リクエストの所要時間を記録する
app.use((req, res, next) => {
const start = Date.now();
res.on("finish", () => {
console.log(req.method, req.url, Date.now() - start, "ms");
});
next();
});
// 管理画面だけログインを必須にする
function requireLogin(req, res, next) {
if (!req.headers.authorization) {
return res.status(401).json({ error: "ログインが必要です" });
}
next();
}
app.get("/admin", requireLogin, (req, res) => {
res.json({ ok: true });
});つまずきやすいところ
いちばんnext() の
登録のapp.use はreq.body がnext() も
似た用語との違い
同じ
覚え方
空港の


