- Express.js Basics
- Express.js HOME
- Express.js Introduction
- Express.js Installation
- Express.js Basic App
- Express.js Routing
- Basics Routing
- Route Parameters
- Handling Query Strings
- Router Middleware
- Middleware
- What is Middleware?
- Application-Level Middleware
- Router-Level Middleware
- Built-In Middleware
- Error-Handling Middleware
- Third-Party Middleware
- Express.js HTTP
- Handling GET Requests
- Handling POST Requests
- Handling PUT Requests
- Handling DELETE Requests
- Templating Engines
- Using Templating Engines
- Setting Up EJS
- Setting Up Handlebars
- Setting Up Pug
- Request/Response
- Request Object
- Response Object
- Handling JSON Data
- Handling Form Data
- Static Files
- Serving Static Files
- Setting Up Static Folders
- Managing Assets
- Express.js Advanced
- Middleware Stack
- CORS in Express.js
- JWT Authentication
- Session Handling
- File Uploads
- Error Handling
- Databases
- Express.js with MongoDB
- MongoDB CRUD Operations
- Express.js with MySQL
- MySQL CRUD Operations
- Deployment
- Deploying Express.js Apps to Heroku
- Deploying Express.js Apps to AWS
- Deploying Express.js Apps to Vercel
Express.js Home
Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for building web and mobile applications. It acts as a layer built on top of the standard Node.js http module, making it significantly easier to manage routes, handle requests, and organize server-side logic. Express is often referred to as "unopinionated," meaning it doesn't force a specific folder structure or database on you, giving you the freedom to architect your app exactly how you want.
Key Features of Express.js
Routing
- Express allows easy creation of routes to handle HTTP requests, enabling precise control over different URL endpoints and HTTP methods (GET, POST, PUT, DELETE, etc.). For example, you can easily define a route for a user profile at
/profile/:usernameusing dynamic parameters.
express.Router class to modularize your routes. Keep your auth routes in one file and your product routes in another to keep the codebase maintainable.
Middleware Support
- Express supports middleware, which allows for the execution of code during the request-response cycle. This can include logging, authentication, error handling, or data parsing. Middleware functions have access to the request object (req), the response object (res), and the next middleware function in the stack.
Template Engines
- Express allows the use of template engines like EJS, Pug, and Handlebars to generate dynamic HTML content. While many modern developers use Express as a JSON API for React or Vue, template engines are still excellent for SEO-friendly server-side rendering or sending dynamic emails.
Error Handling
- Express provides built-in error handling, enabling developers to catch and handle errors in a consistent manner. Instead of crashing the server when an error occurs, you can write centralized catch-all functions to return helpful messages to the user.
app.use() and route calls.
Serving Static Files
- Express can easily serve static files, such as images, CSS, and JavaScript, which are commonly used in web applications. This is done through a simple built-in middleware:
express.static.
RESTful API Creation
- Express is the industry standard for building RESTful APIs. Its intuitive syntax for handling JSON makes it the go-to choice for backend developers building services that communicate with mobile apps or frontend frameworks.
Extensive Plugin Ecosystem
- Express has a large ecosystem of plugins and middleware available through npm. Whether you need to handle file uploads (Multer), secure your headers (Helmet), or handle cookies (cookie-parser), there is likely a community-tested package ready for use.
Getting Started with Express.js
Installation
- Before installing Express, ensure you have initialized your project with a
package.jsonfile usingnpm init -y. Then, install Express via npm by running the following command in your terminal:
npm install express
Creating a Simple Express App
- A basic Express application can be set up with just a few lines of code. Here’s an example of a functional "Hello World" server:
const express = require('express');
const app = express();
const PORT = 3000;
// This defines a GET route for the home page
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
- In this example,
app.gettells the server to listen for a specific URL (the root/). When a user visits that URL, the callback function runs, andres.sendsends a response back to the browser.
res.send() or res.json() ends the request-response cycle. If you try to send another response after the first one has been sent, your app will throw an "Error [ERR_HTTP_HEADERS_SENT]" exception.
Setting Up Middleware
- Middleware functions are functions that execute "in the middle" of receiving a request and sending a response. Here’s an example of a custom logger that prints the request method and time for every single visit:
app.use((req, res, next) => {
const time = new Date().toLocaleTimeString();
console.log(`[${time}] ${req.method} request to ${req.url}`);
// Important: next() must be called to move to the next function
next();
});
npm install --save-dev nodemon). It will automatically restart your server every time you save a file, saving you hours of manual restarts.
Summary
Express.js is a powerful and easy-to-use framework that simplifies web development in Node.js. With its minimalist structure, middleware support, and routing capabilities, Express provides a flexible foundation for building everything from simple landing pages to massive, scalable microservices. Because it stays close to the core logic of Node.js while removing the boilerplate, it remains the most popular choice for server-side JavaScript development today.