Express.js Middlewares & Routes — Beginner Tutorial

Express.js Middlewares & Routes — Beginner Tutorial

๐Ÿ“Œ Introduction

In the previous tutorial, you learned how to create a basic Express.js application.
In this guide, we’ll go deeper into middlewares and routes, which are the core building blocks of every Express application.

By the end of this tutorial, you will clearly understand:

  • How middlewares work in Express

  • How to create custom and route-specific middlewares

  • How to organize routes using Express Router

  • How to handle errors globally

✅ Prerequisites

Before you begin, make sure you have:

  • Node.js and npm installed

  • Basic knowledge of JavaScript

  • A simple Express app (recommended)

๐Ÿงฉ Step 1 — Set Up the Project

Create a new project folder:

mkdir express-middlewares cd express-middlewares

Initialize the project and install Express:

npm init -y npm install express

Create the main file:

touch app.js

๐Ÿง  Step 2 — What Is a Middleware?

A middleware is a function that runs between the request and the response.

Middleware can:

  • Log request details

  • Authenticate users

  • Validate data

  • Modify requests or responses

Example: Logger Middleware

Open app.js and add:

const express = require('express'); const app = express(); const PORT = 3000; // Logger middleware app.use((req, res, next) => { console.log(`${req.method} ${req.url}`); next(); });

Now every incoming request will be logged in the terminal.

๐Ÿ›ฃ️ Step 3 — Add Basic Routes

app.get('/', (req, res) => { res.send('Welcome to the Homepage'); }); app.get('/about', (req, res) => { res.send('About Page'); });

Test in browser:

⏰ Step 4 — Create Custom Middleware

Create a middleware that checks working hours:

const checkTime = (req, res, next) => { const hour = new Date().getHours(); if (hour < 8 || hour > 18) { return res.send('Sorry, our service is only available from 8AM to 6PM.'); } next(); };

Apply It to a Specific Route

app.get('/service', checkTime, (req, res) => { res.send('Welcome to our service page!'); });

This middleware only runs for the /service route.

๐Ÿ“‚ Step 5 — Organize Routes with Express Router

Create Routes Folder

mkdir routes

Create routes/userRoutes.js

const express = require('express'); const router = express.Router(); router.get('/', (req, res) => { res.send('List of users'); }); router.get('/:id', (req, res) => { res.send(`User details for ID: ${req.params.id}`); }); module.exports = router;

Import Routes into app.js

const userRoutes = require('./routes/userRoutes'); app.use('/users', userRoutes);

Test in Browser

๐Ÿšจ Step 6 — Global Error Handling Middleware

Add this at the bottom of app.js:

app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something broke!'); });

This catches unexpected errors safely.

๐Ÿ“„ Step 7 — Final app.js File

const express = require('express'); const app = express(); const PORT = 3000; // Logger middleware app.use((req, res, next) => { console.log(`${req.method} ${req.url}`); next(); }); // Custom time-check middleware const checkTime = (req, res, next) => { const hour = new Date().getHours(); if (hour < 8 || hour > 18) { return res.send('Sorry, our service is only available from 8AM to 6PM.'); } next(); }; // Routes app.get('/', (req, res) => res.send('Welcome to the Homepage')); app.get('/about', (req, res) => res.send('About Page')); app.get('/service', checkTime, (req, res) => res.send('Service Page - Open!') ); // Import route file const userRoutes = require('./routes/userRoutes'); app.use('/users', userRoutes); // Global error handler app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something broke!'); }); // Start server app.listen(PORT, () => { console.log(`๐Ÿš€ Server running at http://localhost:${PORT}`); });

▶️ Step 8 — Start the Server

Run the server:

node app.js

Output:

๐Ÿš€ Server running at http://localhost:3000

๐Ÿงช Test Routes

Open your browser:

๐Ÿง  Summary

In this tutorial, you learned how to:

  • Understand and use Express middlewares

  • Create custom and route-specific middlewares

  • Organize routes using Express Router

  • Add global error handling

  • Structure an Express application professionally

Souy Soeng

Souy Soeng

Hi there ๐Ÿ‘‹, I’m Soeng Souy (StarCode Kh)
-------------------------------------------
๐ŸŒฑ I’m currently creating a sample Laravel and React Vue Livewire
๐Ÿ‘ฏ I’m looking to collaborate on open-source PHP & JavaScript projects
๐Ÿ’ฌ Ask me about Laravel, MySQL, or Flutter
⚡ Fun fact: I love turning ☕️ into code!

Post a Comment

CAN FEEDBACK
close