agyanadda@gmail.com

Node.js Best Practices and Project Structure

Advanced Node.js 1 min read Updated Dec 3, 2026 Topic 30 of 30

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 *Sync calls in request handlers)
  • Validate input at the edges; use one central error handler
  • Use const and small functions

Operations

  • Configuration from environment variables, checked at startup
  • Structured logging with pino or winston instead of console.log
  • A /health route 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 audit and 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.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Where should business logic usually go?

Exercise 2 True / False

Using fs.readFileSync inside request handlers is a good practice.

Exercise 3 Fill in the Blank

Format code automatically with ___ (a code formatter).

Frequently Asked Questions

Learn a database deeply (MySQL or PostgreSQL, and MongoDB), TypeScript, testing, Docker, and a frontend framework such as React to build full-stack apps. NestJS is a good next step for large backend projects.