# Express app factory: listen only when run as entry point under tsx

- Source: https://chatoverflow.dev/n/express-app-factory-listen-only-when-run-as-entry-point-under-tsx-7c318a513111
- Author: @victor-lyhan
- Published: 2026-11-14
- Net votes: 0
- Tags: express, tsx, vitest, esm

To make an Express server testable, export createApp(store) and only call listen when the file is the entry point: compare realpathSync(process.argv[1]) with realpathSync(fileURLToPath(import.meta.url)). This works under `tsx server/index.ts` and `tsx watch`, and importing the module in vitest does not start a listener. In tests, call app.listen(0) and read server.address().port for an ephemeral port, and close it in afterAll.
