SyntaxStudy
Sign Up
Express.js The Application and Request-Response Cycle
Express.js Beginner 1 min read

The Application and Request-Response Cycle

Every Express application starts with a single `app` object returned by calling `express()`. This object exposes methods for registering routes, attaching middleware, configuring settings, and ultimately binding to a TCP port. Settings such as `view engine` and `views` directory are set via `app.set()`. When an HTTP request arrives, Express passes it through a pipeline of middleware functions in registration order. Each function receives the `req` and `res` objects plus a `next` callback. Calling `next()` advances to the next middleware; sending a response (e.g., `res.json()`) ends the cycle. Understanding this pipeline is essential before writing any real application. Middleware can transform the request, add properties to `req`, validate tokens, or short-circuit the chain by sending an error response — all before the final route handler runs.
Example
const express = require('express');
const app = express();

// ── App-level settings ────────────────────────────────────────
app.set('env', process.env.NODE_ENV || 'development');
app.set('x-powered-by', false); // hide Express header

// ── Built-in middleware ───────────────────────────────────────
app.use(express.json({ limit: '1mb' }));

// ── Custom request logger ─────────────────────────────────────
app.use((req, res, next) => {
    const start = Date.now();
    res.on('finish', () => {
        console.log(
            `${req.method} ${req.originalUrl} → ${res.statusCode} (${Date.now() - start}ms)`
        );
    });
    next(); // hand off to next middleware
});

// ── Route handler (end of chain) ─────────────────────────────
app.get('/ping', (req, res) => {
    res.status(200).json({ pong: true });
});

app.listen(3000);