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:
- Setting up dynamic and static routes.
- Understanding and using middleware effectively.
- Integrating a database like MongoDB.
These skills will help you create scalable and maintainable backend systems for modern applications.
Prerequisites
Before proceeding, ensure you have the following:
- A basic Node.js and Express.js server (from the previous tutorial).
- Node.js and npm installed.
- MongoDB installed locally or an account on MongoDB Atlas.
- Familiarity with JSON data structures.
- Postman for testing API endpoints.
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:
morgan
for logging:
npm install morgan
const morgan = require("morgan");
app.use(morgan("dev"));
cors
for enabling Cross-Origin Resource Sharing:
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
- Create a User:
const newUser = new User({ name: "John Doe", email: "john@example.com" });
newUser.save().then(() => console.log("User saved!"));
- Read Users:
User.find().then(users => console.log(users));
- Update a User:
User.updateOne({ name: "John Doe" }, { email: "john.doe@example.com" });
- Delete a User:
User.deleteOne({ name: "John Doe" });
Testing with Postman
Postman makes testing your server easy.
- Install Postman: Download it from here.
- Create a New Request:
- Select the HTTP method (e.g., GET, POST).
- Enter the API endpoint (e.g.,
http://localhost:3000/user
).
- Add Request Data: For POST/PUT requests, include JSON in the body.
- Send the Request: Click Send and view the response in Postman.
Deployment on Render
Steps for Deployment
- Push Code to GitHub: Ensure your project code is in a GitHub repository.
- Set Up a Render Account: Visit Render and sign up.
- Create a New Web Service: Connect your GitHub repository to Render.
- Configure Deployment:
- Build Command:
npm install
- Start Command:
node server.js
- Build Command:
- Set Environment Variables: Add your database URL as an environment variable in Render.
- 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:
- Add user authentication with JWT.
- Build RESTful APIs for complex applications.
- Explore deployment scaling strategies.
Stay tuned for more tutorials to deepen your backend development knowledge!