Skip to content

Instantly share code, notes, and snippets.

@mmyoji
Last active October 16, 2024 01:03
Show Gist options
  • Save mmyoji/94c1270993a8367e46757435be89880f to your computer and use it in GitHub Desktop.
Save mmyoji/94c1270993a8367e46757435be89880f to your computer and use it in GitHub Desktop.
[WIP] express v5 upgrade guide

express.js official migration guide is not sufficient yet.

Regexp in route path cannot be used

  • Check manually in your RequestHandler
  • Be careful declaration order
// users.router.ts
import { Router } from "express";

const r = Router();

r.get("/", indexHandler);
-r.get("/:id(\\d)", showHandler);
-r.get("/new", newHandler);
+r.get("/new", newHandler); // `GET /new` must be before `GET /:id`
+r.get("/:id", showHandler); // ensure `:id` is number in `showHandler`

req.body can be undefined

Though you have to care this even in express@4, req.body might be undefined where it was {} in the previous version.

or you can add a middleware to set {} when req.body === undefined.

// my-middleware.ts

import { type RequestHandler } from "express";

const myMiddleware: RequestHandler = (req, _res, next) => {
-  if (req.body.foo) {
+  if (typeof req.body === "object" && "foo" in req.body && req.body.foo) {
    // do something
  }
  
  next();
};

req.query is read-only

// e.g.) GET /?foo=aaa
app.get("/", (req, res) => {
  console.log(req.query);
  // { foo: "aaa" }

  req.query.foo = "bbb";
  req.query.bar = "ccc";
  console.log(req.query);
  // { foo: "aaa" } // not affected

  delete req.query.foo;
  console.log(req.query);
  // { foo: "aaa" } // not affected

  req.query = { foo: "bbb" }
  // TypeError

  res.end();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment