- 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 Response Object
The response object, typically referred to as res in Express documentation and code, represents the HTTP response that an Express app sends when it receives an HTTP request. Think of it as your primary tool for communicating back to the client. Whether you are building a REST API, a traditional website, or a file-streaming service, the response object provides the necessary methods to format your data, set the correct headers, and terminate the request-reponse cycle.
http.ServerResponse, but Express augments it with many high-level utility methods to make common tasks easier and less verbose.
Key Features of the Response Object
- Send Response Data: Effortlessly transmit strings, HTML, JSON, or Buffer objects back to the browser or calling application.
- Set Response Headers: Manage metadata about the response, such as content type, caching instructions, or custom security tokens.
- Set Status Codes: Communicate the result of the operation using standard HTTP status codes (like 200 for success, 201 for created, or 500 for server errors).
- Redirects: Guide users to a different URL or page seamlessly.
- Handle Content Type: Express automatically attempts to set the correct
Content-Type, but you have full manual control when needed.
res method is called, the client's request will hang until it times out, leading to a poor user experience.
Components of the Response Object
res.send()
The send() method is the most versatile way to finish a request. It checks the type of data you are sending and automatically sets the Content-Type header for you (e.g., text/html for strings or application/json for objects).
Example:
app.get('/send-text', (req, res) => {
res.send('Hello, world!'); // Automatically sets Content-Type to text/html
});
res.send() twice in the same route handler. This will throw an error: "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client."
res.json()
While res.send() can handle objects, res.json() is specifically designed for APIs. It converts non-objects (like null or undefined) into valid JSON and ensures the Content-Type is explicitly set to application/json.
Example:
app.get('/send-json', (req, res) => {
res.json({
id: 1,
status: 'active',
message: 'User data retrieved successfully'
});
});
res.status()
The status() method allows you to set the HTTP status code. It is highly readable because it supports chaining with other methods like send() or json().
Example:
app.get('/not-found', (req, res) => {
// Chaining status with send
res.status(404).send('Sorry, we could not find that resource.');
});
201 for successful creation, 400 for bad client input, and 401 for unauthorized access. This makes your API predictable for other developers.
res.redirect()
When a resource has moved or a user needs to be sent to a login page, use redirect(). By default, it sends a 302 Found status, but you can specify a different code if needed.
Example:
app.get('/old-page', (req, res) => {
res.redirect('/new-page'); // Relative redirect
});
app.get('/external', (req, res) => {
res.redirect('https://google.com'); // Absolute redirect
});
res.set()
Use res.set() (or its alias res.header()) to define specific HTTP headers. This is useful for setting security policies, custom API versioning, or cache control.
Example:
app.get('/set-header', (req, res) => {
res.set('X-Powered-By', 'Awesome-App-1.0');
res.set({
'Content-Type': 'text/plain',
'Cache-Control': 'no-cache'
});
res.send('Headers have been applied.');
});
res.cookie()
Managing user sessions often requires cookies. The cookie() method makes this simple by handling the formatting of the Set-Cookie header for you.
Example:
app.get('/set-cookie', (req, res) => {
// Setting a cookie with an expiration date and security flags
res.cookie('sessionID', 'xyz123', { maxAge: 900000, httpOnly: true });
res.send('Session cookie has been set');
});
httpOnly: true flag for sensitive cookies to prevent them from being accessed by client-side JavaScript, which helps mitigate Cross-Site Scripting (XSS) attacks.
res.sendFile()
If you need to serve a static file directly, sendFile() is the way to go. It requires an absolute path to the file on your server.
Example:
const path = require('path');
app.get('/download-report', (req, res) => {
const options = {
root: path.join(__dirname, 'public'),
dotfiles: 'deny'
};
res.sendFile('report.pdf', options);
});
res.render()
For applications using server-side rendering, render() takes a template file, injects local variables into it, and sends the resulting HTML string to the client.
Example:
app.get('/profile', (req, res) => {
const userData = { name: 'Alex', joinDate: '2023-01-15' };
res.render('profile-template', userData);
});
Example Code
Here is a complete Express server demonstrating these response methods in action. You can use this as a reference for handling different client scenarios.
const express = require('express');
const path = require('path');
const app = express();
// 1. Basic Text Response
app.get('/hello', (req, res) => {
res.send('Welcome to the Express Tutorial!');
});
// 2. JSON Response for APIs
app.get('/api/status', (req, res) => {
res.status(200).json({ status: 'OK', uptime: process.uptime() });
});
// 3. Handling Errors with status codes
app.get('/restricted', (req, res) => {
res.status(403).send('You do not have permission to access this area.');
});
// 4. Practical Redirect (e.g., after a logout)
app.get('/logout', (req, res) => {
// Clear cookies then redirect
res.clearCookie('sessionID');
res.redirect('/login');
});
// 5. Custom Headers & Metadata
app.get('/download-info', (req, res) => {
res.set('X-App-Version', '2.4.0');
res.send('Check the network tab for custom headers!');
});
// 6. Serving a specific file
app.get('/get-guide', (req, res) => {
const filePath = path.join(__dirname, 'docs', 'user-guide.pdf');
res.sendFile(filePath);
});
// Start the server
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Summary
The res object is the final destination for logic in your Express routes. By mastering methods like res.json() for data, res.status() for communication, and res.cookie() for session management, you can build robust backends that communicate clearly and securely with any client. Remember to always terminate your logic with a response method to keep your server running smoothly!