Q25: Why should you separate your Express app logic from your server listener?
Separating the Express application setup (app.js) from the HTTP server initialization (server.js) is an architectural best practice.
Benefits
- Integration Testing: Allows testing tools like
supertestto fire API requests atappwithout starting real network port bindings. - Environment Separation: Permits wrapping the app in HTTPS servers, HTTP/2 servers, or cluster workers easily.
Modular App and Server Separation
// app.js
const express = require('express');
const app = express();
app.use(express.json());
app.get('/health', (req, res) => res.send('OK'));
module.exports = app; // Export app without binding to port
// server.js
const app = require('./app');
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server listening on port ${PORT}`));💡 Decoupling app configuration from server listening simplifies supertest integration tests.
Key Takeaways
- Decouples application setup from network port binding.
- Enables fast, clean integration testing without port conflicts.