Wait! Don’t Start Your Server Before MongoDB Connects

posted 4 min read

Hey everyone!
In the previous article, I explained how to connect MongoDB to your Node.js app using Mongoose.
But if you noticed — we didn’t talk about starting the server yet!

We’ll see how to start the Express server only after your database connection is successful — a small but important step to avoid future errors and follow best practices.

Current Project Structure Recap
So far, here’s how your folder structure looks:

your-project/
├── index.js            // Main entry point (will start the server)
├── db/server.js        // MongoDB connection
├── constants/idbname.js  // DB name or other constants
├── .env

❓ Before We Start Coding the Server...
There’s one important question that needs to be answered first:

Should we start the server before connecting to the database, or after the connection is successful?

Answer: Always Start the Server After the Database Connection
Why?

  1. The server starts immediately — it assumes everything is ready.

  2. Meanwhile, the MongoDB connection is still being established (and it's an asynchronous operation).

  3. If a user hits an API route that depends on the database — for example, /users, /posts, or /login —
    Your server will try to access the database that hasn’t connected yet.

  4. This leads to errors Or even app crashes in worst cases.

  5. Basically: Your server is accepting requests it isn’t ready to handle yet. That’s like

First connect to MongoDB, and then only if that’s successful, start the Express server.

Now that we know why the server should start only after a successful DB connection, let’s set up the Express server step-by-step.

1. Install Express
First, let’s install Express using npm:

npm install express

This will add Express to your project dependencies so you can create and run your server.

2. Create an app.js File
Inside your root folder, create a new file named app.js. This file will handle creating the Express app instance

Set "type": "module" in package.json
This tells Node.js to treat .js files as ES modules, enabling import and export.

⚠️ Without This?
If you don’t set "type": "module", then writing this:

import express from "express";

will throw an error like:

SyntaxError: Cannot use import statement outside a module

3 Simple Steps to Initialize Express in app.js

Step 1: Import Express

import express from "express";

Step 2: Create the App Instance

const app = express();

This app variable is now your entire Express application. You’ll use it to define routes, middlewares, etc.

Step 3: Export the App

export default app;

Exporting the app allows you to import and use it in your index.js file (where you'll start the server after connecting to MongoDB).

import express from "express"
const app = express();
export default app;

for now, this minimal setup is perfect.

Quick Reminder from the Previous Article

In our previous article, we created an async function called connectionDB() that handles the MongoDB connection logic.
We then called this function in index.js to actually initiate the connection.

But here’s something important you should understand

When you create an async function like this:

async function connectionDB() {
  // your logic here
}

...it always returns a Promise by default, whether you explicitly return something or not.

This means — when we call this function:

connectionDB()

We can attach .then() and .catch() to it, just like any other Promise:

connectionDB()
  .then(() => {
    // Code to run after DB is connected
  })
  .catch((err) => {
    // Handle DB connection error
  });

Why We Use .then() and .catch() for Database Connection

.then() — If DB Connection is Successful

 connectionDB()
  .then(() => {
    // If connection is successful, start the server
    app.listen(3000, () => {
      console.log(` Server started successfully`);
    });
  })

This means:

  1. If MongoDB connects successfully
  2. Then we start our Express server using app.listen().
  3. This ensures the server starts only when the DB is ready.

.catch() — If DB Connection Fails
But what if the connection fails? For example:

  1. Wrong MongoDB URI,
  2. Incorrect username or password,
  3. Or internet issues?

In that case, the .catch() block runs:

.catch((err) => {
  console.log(" Server failed to start due to DB connection error:", err);
});

This stops the server from running without a working database, which could lead to serious bugs or crashes in your app.

// index.js

import dotenv from "dotenv";
import app from "./app.js";
import connectionDB from "./db/server.js";

// Load environment variables from .env file
dotenv.config();
 
// Connect to the database first
connectionDB()
  .then(() => {
    // If connection is successful, start the server
    app.listen(3000, () => {
      console.log(` Server started successfully`);
    });
  })
  .catch((err) => {
    // If connection fails, do NOT start the server
    console.log(" Server failed to start due to DB connection error:", err);
  });

Wrapping Up
And that’s how you start your server only after your database connection is successful — the clean, professional way.

Remember:
Make sure to import your app.js file into index.js like this:

import app from "./app.js";
This ensures your Express server is ready to run once everything else (like DB connection) is set.

This setup is not too lengthy — it's actually a very compact and organized way to structure your backend.

With this approach, your project is:

  • Modular

  • Error-resilient

  • Production-ready

Bonus Tip: Special Characters in Your MongoDB Password
Let me share a quick issue I faced (and many beginners do too):

❓ What if your MongoDB password contains special characters like @, #, or $?

If your password has characters like @, the MongoDB connection will fail unless you encode them properly in the URI.

The Fix:
Let’s say your password is:

myPass@123

Your MongoDB URI will break at @, because @ has a special meaning in URLs.

Instead, you must URL-encode the special characters.
For example, @ becomes %40.

So your password becomes:

myPass%40123

And your connection string should look like this:

mongodb+srv://username:myPass%*Emails are not allowed*/

Pro Tip: If you don’t want to mess with encoding, just avoid using special characters in your DB password — or change them to something simpler.

  • If this article helped you even a little, drop a like ❤️ — it really motivates me to share more practical content like this!*
If you read this far, tweet to the author to show them you care. Tweet a Thanks

Great step-by-step guide—thanks for making this clear and beginner-friendly! Do you have any tips on handling multiple database connections with this setup?

More Posts

Why I'm Building My Personal Brand Before Launching My App

Matheo Gomez - Mar 9

6 Amazing Websites For Developers That You Don’t Know Till Yet.

paruidev - Jan 26

Ditch Your GUID Frustrations: Introducing ByteAether.Ulid v1.0.0 for .NET!

Joonatan Uusväli - Jul 9

5 Key Software Architecture Principles for Starting Your Next Project

ByteMinds - Mar 26

Learn the basics about how REST APIs work

SuperheroJT - Feb 23
chevron_left