- 最終更新
- 2026/08/17
3秒でわかる
Express でミドルウェアを登録するメソッド。ログや認証など全リクエスト共通の処理を、各ルートに書かず一箇所にまとめて差し込むために使う。
30秒図解
もう少し詳しく
どういうものか
Express でreq と res と next の 3 つを受け取ります。
第 1 引数にパスをnext() をapp.get などの
なぜ必要か
共通の
もう
具体例
const express = require("express");
const app = express();
// 1. 全リクエストに適用される。next() を呼ばないとここで止まる
app.use((req, res, next) => {
console.log(req.method, req.url);
next();
});
// 2. 組み込みミドルウェア。これが無いと req.body は undefined のまま
app.use(express.json());
// 3. パスを指定すると /admin 以下だけに適用される
app.use("/admin", (req, res, next) => {
if (!req.headers.authorization) {
return res.status(401).json({ error: "unauthorized" });
}
next();
});
app.get("/admin/users", (req, res) => {
res.json([{ id: 1, name: "sato" }]);
});
// 4. 引数 4 つならエラー処理用。ルートより後ろに置く
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ error: "internal error" });
});
app.listen(3000);つまずきやすいところ
next() をexpress.json() をreq.body がapp.use("/admin") は /admin/users にもnext() をres.send() をreturn を似た用語との違い
| 書き方 | 対象 |
|---|---|
| app.use | メソッドを |
| app.get / app.post | 指定した |
| app.all | 全メ |


