A clean folder structure
src/
config/ settings from env
routes/ URL definitions
controllers/ request handling
services/ business logic
models/ database access
middleware/ auth, validation, errors
utils/
app.js Express app
server.js starts the server
tests/
Code
- Use ES modules and async/await
- Keep controllers thin; put logic in services
- Never block the event loop (no
*Synccalls in request handlers) - Validate input at the edges; use one central error handler
- Use
constand small functions
Operations
- Configuration from environment variables, checked at startup
- Structured logging with pino or winston instead of
console.log - A
/healthroute for monitoring - Graceful shutdown on
SIGTERM: stop accepting requests, close the database, then exit
Quality
- ESLint and Prettier for consistent code
- Tests for important routes
npm auditand regular updates- Consider TypeScript for larger projects
Practice projects
A URL shortener, a notes API with JWT login, a real-time chat, and a file-sharing app.
Example
Example — Graceful shutdown
JavaScript
// server.js
import { app } from './app.js';
import { pool } from './db.js';
const server = app.listen(process.env.PORT ?? 3000, () => {
console.log('Server started');
});
async function shutdown(signal) {
console.log(`${signal} received, shutting down...`);
server.close(async () => { // stop new connections, finish current ones
await pool.end(); // close database connections
console.log('Closed cleanly');
process.exit(0);
});
setTimeout(() => process.exit(1), 10_000).unref(); // force exit after 10s
}
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
When PM2, Docker or Ctrl+C stops the app, it finishes in-flight requests and closes the database instead of cutting users off mid-request.