SyntaxStudy
Sign Up
Express.js Beginner 1 min read

The Response Object

The `res` object extends Node's `http.ServerResponse` with helpers that make sending responses concise and correct. `res.json()` serializes a JavaScript value to JSON, sets `Content-Type: application/json`, and sends the response. `res.send()` is more general — it auto-detects the content type based on what you pass. `res.status()` sets the HTTP status code and returns `res` for chaining. `res.set()` or `res.header()` sets response headers. `res.cookie()` writes a `Set-Cookie` header with full control over options like `httpOnly`, `secure`, and `sameSite`. `res.clearCookie()` removes a cookie. For redirects, `res.redirect()` defaults to 302 but accepts a status code as the first argument. `res.sendFile()` streams a file from disk with the correct MIME type. `res.download()` sets `Content-Disposition: attachment` so browsers trigger a file download. `res.end()` terminates the response without a body, appropriate for 204 No Content responses.
Example
const express = require('express');
const path    = require('path');
const app     = express();
app.use(express.json());

// JSON response with status
app.post('/login', (req, res) => {
    const { email } = req.body;
    if (!email) return res.status(422).json({ error: 'email required' });

    // Set an httpOnly auth cookie
    res.cookie('session', 'tok_abc123', {
        httpOnly: true,
        secure:   process.env.NODE_ENV === 'production',
        sameSite: 'lax',
        maxAge:   7 * 24 * 60 * 60 * 1000, // 7 days in ms
    });

    res.status(200).json({ message: 'Logged in', email });
});

// File download
app.get('/report', (req, res) => {
    const file = path.join(__dirname, 'reports', 'monthly.pdf');
    res.download(file, 'monthly-report.pdf', (err) => {
        if (err) res.status(404).json({ error: 'File not found' });
    });
});

// Redirect
app.get('/old-path', (req, res) => {
    res.redirect(301, '/new-path');
});

// 204 No Content
app.delete('/items/:id', (req, res) => {
    res.status(204).end();
});

app.listen(3000);