Skip to content

03 - Enhance Your Node.js Server: Routing, Middleware, and Database Integration

Published: at 11:00 am

Taking your Node.js server beyond the basics is essential for creating powerful and scalable backend applications. In this tutorial, you’ll learn advanced concepts, including routing, middleware, and database integration using MongoDB.

By the end of this guide, you’ll be equipped to build dynamic backend systems that can handle real-world applications.

Table of contents

Open Table of contents

Introduction

In the previous tutorial, we built a simple web server using Node.js and Express.js. Now, it’s time to take it a step further by adding advanced features. This article will cover:

These skills will help you create scalable and maintainable backend systems for modern applications.

Prerequisites

Before proceeding, ensure you have the following:

Advanced Routing in Express.js

Organizing Routes

Express.js allows for efficient routing management, which is crucial as your application grows.

Static Routes

Define routes that serve static content:

app.get("/home", (req, res) => {
  res.send("Welcome to the Home Page");
});

Dynamic Routes

Use route parameters to create dynamic endpoints:

app.get("/user/:id", (req, res) => {
  const userId = req.params.id;
  res.send(`User ID: ${userId}`);
});

Using Router Instance

For better organization, use express.Router():

const userRouter = express.Router();

userRouter.get("/:id", (req, res) => {
  res.send(`User ID: ${req.params.id}`);
});

app.use("/user", userRouter);

Middleware in Depth

Middleware functions process requests and responses, allowing you to add features like logging, error handling, and data parsing.

Built-In Middleware

Use built-in middleware to parse JSON:

app.use(express.json());

Third-Party Middleware

Install and use popular middleware:

npm install morgan
const morgan = require("morgan");
app.use(morgan("dev"));
npm install cors
const cors = require("cors");
app.use(cors());

Custom Middleware

Create your own middleware for custom functionality:

app.use((req, res, next) => {
  console.log(`${req.method} request to ${req.url}`);
  next();
});

Database Integration with MongoDB

Setting Up MongoDB

Install Mongoose to connect and interact with MongoDB:

npm install mongoose

Connecting to MongoDB

Create a connection to your database:

const mongoose = require("mongoose");

mongoose
  .connect("mongodb://localhost:27017/myDatabase", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => {
    console.log("Connected to MongoDB");
  })
  .catch(err => {
    console.error("Connection error", err);
  });

Creating a Model

Define a schema and model for your data:

const userSchema = new mongoose.Schema({
  name: String,
  email: String,
});

const User = mongoose.model("User", userSchema);

Performing CRUD Operations

const newUser = new User({ name: "John Doe", email: "john@example.com" });
newUser.save().then(() => console.log("User saved!"));
User.find().then(users => console.log(users));
User.updateOne({ name: "John Doe" }, { email: "john.doe@example.com" });
User.deleteOne({ name: "John Doe" });

Testing with Postman

Postman makes testing your server easy.

  1. Install Postman: Download it from here.
  2. Create a New Request:
    • Select the HTTP method (e.g., GET, POST).
    • Enter the API endpoint (e.g., http://localhost:3000/user).
  3. Add Request Data: For POST/PUT requests, include JSON in the body.
  4. Send the Request: Click Send and view the response in Postman.

Deployment on Render

Steps for Deployment

  1. Push Code to GitHub: Ensure your project code is in a GitHub repository.
  2. Set Up a Render Account: Visit Render and sign up.
  3. Create a New Web Service: Connect your GitHub repository to Render.
  4. Configure Deployment:
    • Build Command: npm install
    • Start Command: node server.js
  5. Set Environment Variables: Add your database URL as an environment variable in Render.
  6. Deploy: Wait for Render to build and deploy your app.

Conclusion and Further Learning

You’ve expanded your Node.js server with advanced features, including routing, middleware, and database integration. Next steps:

Stay tuned for more tutorials to deepen your backend development knowledge!


Next Post
02 - How to Build a Simple Web Server Using Node.js and Express.js: A Beginner-Friendly Guide