| Level Navigation: 1 | 2 | 3 | (4ℹ️) | (5ℹ️) | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14⚡ | 15⚡ | (16ℹ️) | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26⚡ | 27⚡ | 28⚡ | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39⚡ | 40⚡ |
Refactor your Express server to separate app configuration from server startup. This is a common practice that makes your code more testable, reusable, and better organized.
In your current setup, everything is in one file (src/index.js): the app creation, routes, and the app.listen() call. As your project grows, you’ll want to:
src/app.js: Move your Express app creation and configuration here, then export it.src/index.js: Import the app and handle server startup (the listen() call).src/app.js and Export the AppCreate a new file src/app.js and move your Express app setup there:
// src/app.js
import express from 'express';
const app = express();
// Middleware
app.use(express.json());
app.use(express.static('public'));
// Routes
app.get('/', (req, res) => {
res.send('<h1>Hello Express!</h1><p>Your server is working!</p>');
});
app.get('/happy-birthday', (req, res) => {
res.json({
name: 'Alice',
age: 25,
greeting: 'Happy Birthday! 🎉'
});
});
// ... all your other routes ...
// Export the app so it can be imported elsewhere
export default app;
Key changes:
app.jsexport default app;app.listen() call — that will go in a different filesrc/index.js to Import and Start the ServerUpdate src/index.js to import the app and handle server startup:
// src/index.js
import app from './app.js';
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
Key changes:
import app from './app.js';listen() call herePORT for flexibility (important for deployment)After refactoring, your project structure should look like this:
your-project/
├── src/
│ ├── app.js ← App configuration (middleware, routes)
│ └── index.js ← Server startup (listen call)
├── public/
│ └── ...
└── package.json
npm run dev
Exporting with export default:
export default app; makes the app the default export from the moduleimport app from './app.js' or import myApp from './app.js'Why this pattern is common:
In the next level, you’ll set up testing. Having the app exported makes it easy to import in your test files without needing to start a server. This refactor sets you up for success with automated testing!
Note: If you’re using TypeScript, the same pattern applies—just use .ts extensions and TypeScript syntax.