Create the Server Entry Point

Create src/server.js.

This file will be responsible for:

  1. Loading environment variables.
  2. Connecting to MongoDB.
  3. Importing the Express application.
  4. Starting the HTTP server.

The database connection must complete before the server begins accepting requests that depend on MongoDB.

src/server.js
import 'dotenv/config';
import app from './app.js';
import { connectDatabase } from './config/database.js';

const PORT = process.env.PORT || 3000;

async function startServer() {
  await connectDatabase();

  app.listen(PORT, () => {
    console.log(`REST API running at http://localhost:${PORT}`);
  });
}

startServer().catch((error) => {
  console.error('Application startup failed:', error);
  process.exit(1);
});

Loads configuration, connects to MongoDB, and starts the Express application only after the database connection succeeds.

Key Takeaways
  • The server entry point controls application startup.

  • Connect to the database before accepting requests.

  • Separate app.js from server.js for easier testing.