Node.js and Express - Building Backend Web Applications
Node.js is a JavaScript runtime built on Chrome's V8 engine that allows developers to run JavaScript on the server side.
Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for building APIs and web servers.
This tutorial walks you through creating a RESTful API using Node.js and Express with routing, middleware, and database integration.
Setting Up a Node.js + Express Project
Start by initializing a Node.js project and installing Express as a dependency.
mkdir my-api && cd my-api
npm init -y
npm install express
npm install --save-dev nodemon
// server.js
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
app.get('/', (req, res) => {
res.json({ message: 'Welcome to my API!' });
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Express Routing
Express routing defines how your application responds to client requests at specific endpoints using HTTP methods like GET, POST, PUT, and DELETE.
const express = require('express');
const router = express.Router();
// GET all users
router.get('/users', async (req, res) => {
const users = await User.find();
res.json(users);
});
// GET single user
router.get('/users/:id', async (req, res) => {
const user = await User.findById(req.params.id);
if (!user) return res.status(404).json({ error: 'User not found' });
res.json(user);
});
// POST create user
router.post('/users', async (req, res) => {
const user = new User(req.body);
await user.save();
res.status(201).json(user);
});
module.exports = router;
Middleware in Express
Middleware functions are functions that have access to the request and response objects. They can execute code, modify requests, end the cycle, or pass control to the next middleware.
// Custom logger middleware
app.use((req, res, next) => {
console.log(`${req.method} ${req.url} - ${new Date().toISOString()}`);
next();
});
// Auth middleware
function authenticate(req, res, next) {
const token = req.headers.authorization;
if (!token) return res.status(401).json({ error: 'Unauthorized' });
// verify token logic here
next();
}
// Error handling middleware (must have 4 params)
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Internal Server Error' });
});
Why Use Node.js and Express?
- JavaScript on both frontend and backend for full-stack development
- Non-blocking I/O for handling thousands of concurrent connections
- Huge npm ecosystem with millions of packages
- Fast development with minimal boilerplate using Express
- Great for REST APIs, real-time apps, and microservices
- Active community and wide industry adoption
Conclusion
Node.js and Express form a powerful combination for building backend APIs and server-side applications using JavaScript.
By mastering routing, middleware, and data handling, you can build scalable and production-ready REST APIs for any kind of web application.
Codecrown