Express.js Guide: Routing, Middleware and REST API Development
Learn Express.js routing, middleware, REST API development, MongoDB integration, and backend best practices with practical examples for beginners.
On this page
- What Is Express.js?
- 1. Getting Started with Express.js
- 2. Understanding Routing in Express.js
- Example of Express.js Routing
- Route Parameters and Query Parameters
- 3. What Is Middleware in Express.js?
- Example of Custom Middleware
- Common Types of Middleware
- 4. REST API Development with Express.js
- Example: Creating a Simple REST API
- 5. Connecting Express.js with MongoDB
- 6. Error Handling and API Best Practices
- 7. Practical Express.js Project Ideas for Beginners
- Why Learn Express.js for MERN Stack Development?
- Conclusion
Express.js Guide: Routing, Middleware and REST API Development
Express.js is a popular web framework for Node.js that helps developers build web applications, backend services, and REST APIs. It simplifies handling HTTP requests, defining routes, processing incoming data, and sending responses to clients.
For students learning the MERN stack, Express.js is an important technology because it connects the frontend built with React.js to backend logic and databases such as MongoDB. Understanding routing, middleware, and REST API development helps beginners build structured and maintainable backend applications.
In this guide, we will explore the fundamentals of Express.js, learn how routing and middleware work, build REST API endpoints, and understand best practices for developing backend applications.
What Is Express.js?
Express.js is a lightweight web framework that runs on Node.js. It provides tools for handling HTTP requests and responses without requiring developers to implement every backend feature from scratch.
With Express.js, developers can create routes, use middleware functions, handle errors, receive request data, and connect applications to databases.
Some common applications of Express.js include:
Building REST APIs for web and mobile applications.
Creating backend services for MERN stack projects.
Handling user registration and login.
Managing data through database operations.
Developing server-side applications and web services.
Express.js is widely used in JavaScript development because it works with Node.js and allows developers to use JavaScript across both frontend and backend development.
1. Getting Started with Express.js
Before learning Express.js, beginners should understand basic JavaScript, Node.js, functions, objects, and asynchronous programming.
To create a basic Express.js project, first install Node.js on your computer. Then open a terminal and run the following commands:
mkdir express-guide
cd express-guide
npm init -y
npm install expressCreate a file named server.js and add the following code:
const express = require("express");
const app = express();
const PORT = 3000;
app.get("/", (req, res) => {
res.send("Welcome to Express.js!");
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});Start the server using:
node server.jsOpen http://localhost:3000 in your browser. You should see the message:
Welcome to Express.js!This example creates an Express application, defines a route for the homepage, and starts a server on port 3000.
2. Understanding Routing in Express.js
Routing determines how an application responds to requests sent to specific URLs and HTTP methods.
For example, a student management application might use one route to display students, another to retrieve a particular student, and another to create a new student record.
Express.js supports several HTTP methods:
GET: Retrieves data.
POST: Creates a resource or submits data for processing.
PUT: Replaces or updates a resource, depending on the API design.
PATCH: Partially updates a resource.
DELETE: Removes a resource.
Example of Express.js Routing
const express = require("express");
const app = express();
app.get("/students", (req, res) => {
res.send("List of students");
});
app.get("/students/:id", (req, res) => {
res.send(`Student ID: ${req.params.id}`);
});
app.post("/students", (req, res) => {
res.send("Student created");
});
app.listen(3000, () => {
console.log("Server started");
});In this example, /students retrieves the student list, while /students/:id defines a dynamic route parameter.
If you visit /students/101, the application reads 101 through req.params.id.
Route Parameters and Query Parameters
Express.js provides different ways to receive information from a URL.
Route parameters identify a specific resource. For example:
/students/101The value 101 can be accessed through req.params.id when the route is defined as /students/:id.
Query parameters are often used for filtering, searching, and pagination. For example:
/students?course=MERNThe course value can be accessed through req.query.course.
Understanding these differences helps developers design API endpoints that are clear and easy to use.
3. What Is Middleware in Express.js?
Middleware is a function that runs during the request-response process. It can inspect or modify requests, execute additional logic, send a response, or pass control to the next middleware function.
Middleware is commonly used for logging, authentication, request parsing, validation, and error handling.
A typical middleware function receives three arguments:
req: Contains information about the incoming request.res: Represents the response sent to the client.next: Passes control to the next middleware function.
Example of Custom Middleware
const express = require("express");
const app = express();
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
app.get("/", (req, res) => {
res.send("Home page");
});
app.listen(3000);Whenever a request reaches the application, the middleware logs the HTTP method and requested URL before allowing the request to continue.
The next() function is important because it passes control to the next middleware or route handler. If middleware neither sends a response nor passes control onward, the request may remain pending.
Common Types of Middleware
1. Built-in middleware
Express.js provides middleware such as express.json() for parsing incoming JSON request bodies.
app.use(express.json());2. Application-level middleware
This middleware is registered on the Express application using methods such as app.use().
3. Router-level middleware
This middleware is attached to an Express router and can apply to a specific group of routes.
4. Error-handling middleware
Error-handling middleware receives four arguments: err, req, res, and next. It helps manage errors in a centralized way.
Middleware should be registered in the correct order because Express processes middleware and routes according to their registration sequence.
4. REST API Development with Express.js
REST API development is one of the most common uses of Express.js. A REST API allows different applications to communicate through HTTP requests and structured responses.
For example, a React frontend can send a request to an Express backend, which processes the request and returns data in JSON format.
A well-designed API generally uses resource-based URLs and appropriate HTTP methods.
MethodExample endpointPurposeGET/api/studentsRetrieve studentsGET/api/students/101Retrieve one studentPOST/api/studentsCreate a studentPATCH/api/students/101Update part of a student recordDELETE/api/students/101Delete a student
Example: Creating a Simple REST API
The following example uses an in-memory array to demonstrate basic CRUD operations. The data resets whenever the server restarts, so a database should be used for persistent storage.
const express = require("express");
const app = express();
app.use(express.json());
let students = [
{ id: 1, name: "Aman", course: "MERN" },
{ id: 2, name: "Priya", course: "Java" }
];
// Get all students
app.get("/api/students", (req, res) => {
res.json(students);
});
// Get one student
app.get("/api/students/:id", (req, res) => {
const id = Number(req.params.id);
const student = students.find(s => s.id === id);
if (!student) {
return res.status(404).json({
message: "Student not found"
});
}
res.json(student);
});
// Create a student
app.post("/api/students", (req, res) => {
const { name, course } = req.body;
if (
typeof name !== "string" ||
!name.trim() ||
typeof course !== "string" ||
!course.trim()
) {
return res.status(400).json({
message: "Valid name and course are required"
});
}
const newStudent = {
id: students.length
? Math.max(...students.map(s => s.id)) + 1
: 1,
name: name.trim(),
course: course.trim()
};
students.push(newStudent);
res.status(201).json(newStudent);
});
app.listen(3000, () => {
console.log("API running on port 3000");
});This example demonstrates how Express.js handles incoming requests, reads JSON data, searches records, validates input, and returns appropriate HTTP status codes.
For a production application, additional validation, persistent database storage, and more robust error handling would be needed.
5. Connecting Express.js with MongoDB
Express.js can connect to MongoDB to store and retrieve application data. In a MERN stack project, React handles the user interface, Express.js and Node.js handle backend requests, and MongoDB stores application records.
Developers often use Mongoose to define schemas and interact with MongoDB.
Install Mongoose with:
npm install mongooseA typical application connects to MongoDB using a connection string stored in an environment variable.
const mongoose = require("mongoose");
mongoose.connect(process.env.MONGODB_URI)
.then(() => console.log("MongoDB connected"))
.catch(err => console.error("Database connection failed", err));Create a .env file containing the appropriate database connection string and load environment variables using a suitable package such as dotenv, or use Node.js environment configuration.
Avoid hardcoding database credentials or publishing secrets in source code.
Once the connection is established, a Mongoose model can be used to create, read, update, and delete records through Express routes.
6. Error Handling and API Best Practices
Good error handling makes backend applications easier to maintain and helps clients understand what went wrong.
Developers should return appropriate HTTP status codes, validate incoming data, and avoid exposing sensitive internal details in error responses.
Common status codes include:
200 OK: The request succeeded.201 Created: A resource was created successfully.400 Bad Request: The request contains invalid data.401 Unauthorized: Authentication is required or invalid.403 Forbidden: The client does not have permission.404 Not Found: The requested resource does not exist.500 Internal Server Error: An unexpected server-side error occurred.
Other important best practices include:
Organizing routes, controllers, models, and middleware into separate modules.
Validating and sanitizing user input.
Using authentication and authorization where required.
Storing secrets in environment variables.
Avoiding unnecessary exposure of stack traces in production.
Testing API endpoints with tools such as Postman.
Using HTTPS and appropriate security middleware.
Documenting API endpoints and expected responses.
In Express.js, error-handling middleware should be registered after the routes that may pass errors to it. Asynchronous error handling depends on the Express version and the way handlers are implemented, so developers should follow the relevant version's documentation.
7. Practical Express.js Project Ideas for Beginners
Building projects helps students apply routing, middleware, and REST API concepts in realistic situations.
Here are some useful project ideas:
Student Management API: Create endpoints to add, retrieve, update, and delete student records.
Task Management API: Allow users to create tasks, change their status, and retrieve tasks based on filters.
Blog Backend: Manage posts, categories, comments, and user authentication.
Employee Management System: Store employee information and implement search, update, and deletion operations.
E-commerce Backend: Create APIs for products, categories, shopping carts, and orders.
Start with a small project, test each endpoint, and then add database integration, validation, authentication, and error handling as your skills improve.
Why Learn Express.js for MERN Stack Development?
Express.js is a core part of the MERN stack and provides the backend layer needed to connect frontend applications with databases and business logic.
Learning Express.js helps students understand how web servers work, how APIs are designed, how requests are processed, and how backend applications manage data securely.
For students exploring web development training in Jalandhar, TechCADD is one option to consider when comparing programs. Review the course syllabus, practical assignments, instructor support, and opportunities to build complete projects before choosing a training program.
Conclusion
Express.js simplifies backend development with Node.js by providing a clear approach to routing, middleware, and REST API creation. These concepts form the foundation of many modern web applications and are especially useful for developers learning the MERN stack.
Start by creating a basic server, practise HTTP methods, understand middleware execution, and build CRUD APIs. Then progress to MongoDB integration, validation, authentication, and error handling.
Consistent practice and project-based learning can help you develop stronger backend programming skills and prepare for more advanced web development projects.
Have a questionabout this?
Leave your number and a counsellor will call you back — about batch timings, fees, EMI options, placement record, or which track fits your degree.
- Free career counselling, no registration fee
- Weekday, evening, weekend or 1-on-1 batches
- Internship letter and placement support
Ready to get started?
Start building yourcareer today.
Talk to a counsellor today. One call is usually enough to know which track fits your degree, your schedule and the job you want.
- Free career counselling
- No registration fee
- Placement support included