Express

Lesson 01

App factory vs server startup

Create the Express app separately from the process that starts listening.

Good Code

src/app.ts
import express from "express";
import { createReviewsRouter } from "./reviews/router";

export function createApp() {
  const app = express();

  app.use(express.json());
  app.use("/reviews", createReviewsRouter());

  return app;
}

Bad Code

src/app.ts
import express from "express";
import { createReviewsRouter } from "./reviews/router";

const app = express();

app.use(express.json());
app.use("/reviews", createReviewsRouter());
app.listen(process.env.PORT || 3000);

export default app;

Review Notes

What to review

Good Code

The good version exports an app factory, so tests and workers can create the same app without starting a server.

Bad Code

The bad version starts listening as a module side effect. Importing the app for tests or scripts now opens a port unexpectedly.

Takeaways

  • An Express app should be buildable for tests without opening a port.