Loading

Quipoin Menu

Learn • Practice • Grow

express-js / Built-in Middleware
tutorial

Built-in Middleware

Express comes with several built-in middleware functions that handle common tasks. These are included out of the box, so you don't need to install additional packages. The most commonly used are `express.json()` and `express.urlencoded()` for parsing request bodies.

express.json()

This middleware parses incoming requests with JSON payloads. It's essential for building APIs that accept JSON data.
const express = require('express');
const app = express();

<!-- Parse JSON bodies -->
app.use(express.json());

app.post('/api/users', (req, res) => {
  console.log(req.body); <!-- Now contains parsed JSON -->
  res.json({ received: req.body });
});

Without `express.json()`, `req.body` would be `undefined` or the raw request stream.

express.urlencoded()

This middleware parses incoming requests with URL-encoded payloads (the format sent by HTML forms with `method="POST"`).
<!-- Parse URL-encoded bodies (form data) -->
app.use(express.urlencoded({ extended: true }));

app.post('/submit-form', (req, res) => {
  console.log(req.body); <!-- { name: 'John', email: 'john@example.com' } -->
  res.send('Form submitted');
});

extended: true vs false

OptionDescription
extended: trueParses nested objects using the `qs` library (more powerful).
extended: falseParses using the `querystring` library (simpler, flat objects).

express.static()

This built-in middleware serves static files like HTML, CSS, images, and client-side JavaScript.
<!-- Serve files from the 'public' folder -->
app.use(express.static('public'));

<!-- Now files in public/ are accessible: -->
<!-- http://localhost:3000/css/style.css -->
<!-- http://localhost:3000/images/logo.png -->

Combining Built-in Middleware
const express = require('express');
const app = express();

<!-- Parse JSON and form data -->
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

<!-- Serve static files -->
app.use(express.static('public'));

<!-- Now your app can handle JSON APIs, form submissions, and static files -->

Two Minute Drill

  • `express.json()` parses incoming JSON requests – essential for REST APIs.
  • `express.urlencoded()` parses form submissions (URL-encoded data).
  • `express.static()` serves static files from a directory.
  • These are built-in – no need for additional npm packages.
  • Always place body-parsing middleware before routes that need the data.

Need more clarification?

Drop us an email at career@quipoinfotech.com