Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How to skip a middleware in Express.js ?
Next article icon

Built-in Middleware Functions in Express.js

Last Updated : 29 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Express.js is a Node.js framework used to develop the backend of web applications. While you can create custom middleware in Express.js using JavaScript, Express.js also provides several built-in middleware functions for use in Express applications. Middleware are functions that are executed when called and then pass control to the next middleware function using the next() function. They act as an intermediary layer.

Express.js provides various built-in middleware functions to handle common tasks. Some of the most popular built-in middleware functions include:

Table of Content

  • Express.json([options])
  • Express.urlencoded([options])
  • Express.static(root,[options])
  • Express.text([options])
  • Express.raw([options])
  • Express.Router([options])

Express.json([options])

This middleware basically works when the client sends a request with a Content-Type of application/json. It automatically parses the payload and populates req.body with the JSON data.

Example:

const express = require('express');
const app = express();

// Use the express.json() middleware to parse JSON data
app.use(express.json());

app.post('/submit', (req, res) => {
// Access the parsed JSON data from req.body
const { name, age } = req.body;
res.send(`Received data: Name - ${name}, Age - ${age}`);
});

app.listen(5000, () => {
console.log('Server is running on port 5000');
});

Express.urlencoded([options])

This middleware basically works when the client sends a request with a Content-Type of application/x-www-form-urlencoded. It automatically parses URL-encoded data, such as UTF-8 encoded or gzip data, and populates req.body with the parsed data. If there is no body to parse, the Content-Type does not match, or an error occurs, req.body will be an empty object ({}).

Example:

const express = require('express');
const app = express();

// Using express.urlencoded() middleware
// to parse URL-encoded data
app.use(express.urlencoded({ extended: true }));

app.post('/submit', (req, res) => {
// Access the parsed URL-encoded data from req.body
const { firstName, lastName, email } = req.body;

res.send(`Received data: First Name - ${firstName},
Last Name - ${lastName}, Email - ${email}`);
});

app.listen(3000, () => {
console.log('Server is running on port 3000');
});

Express.static(root,[options])

This middleware basically works to serve static files, like images, CSS files, and JavaScript files, from a specified directory in an Express application. By using express.static(), you set a root directory where static files are located, and Express will automatically serve these files when requested. For example, with express.static('public'), a request for /images/logo.png will be resolved to public/images/logo.png.

Note: If a requested file is not found, instead of sending a 404 response immediately, express.static() calls next() to pass control to the next middleware in the stack. This lets you handle errors or serve dynamic content. By using next(), you can integrate custom error-handling middleware to manage cases where static files are not found and provide a custom 404 page or other responses, ensuring your application handles such scenarios gracefully.

Example:

const express = require('express');
const path = require('path');
const app = express();
const port = 5000;

// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, 'public')));

app.listen(port, () => {
console.log(`Server is running at : ${port}`);
});

Express.text([options])

The express.text() middleware basically parses incoming request bodies with a Content-Type of text/plain. It extracts the raw text data and populates the req.body property with this text, allowing your application to handle plain text data seamlessly.

If there is no body to parse, the Content-Type does not match text/plain, or an error occurs, req.body will be an empty string ("").

Example:

const express = require('express');
const app = express();
const port = 5000;

// Use express.text() middleware to parse text/plain request bodies
app.use(express.text());

app.post('/submit', (req, res) => {
// Access the parsed text from req.body
const text = req.body;
res.send(`Received text: ${text}`);
});

app.listen(port, () => {
console.log(`Server is running at :${port}`);
});

Express.raw([options])

The 'express.raw()' middleware in Express.js is designed to handle incoming request bodies with a 'Content-Type' of 'application/octet-stream' or other binary data types. This middleware parses the raw buffer data from the request body and makes it available on the 'req.body' property as a Buffer object.

For example, if a POST request contains binary data, using express.raw() allows you to access this data directly through req.body.

Example:

const express = require('express');
const app = express();

// Middleware to parse raw binary data
app.use(express.raw({ type: 'application/octet-stream' }));

app.post('/upload', (req, res) => {
const binaryData = req.body;

const dataString = binaryData.toString('utf-8');

res.send(`Received binary data: ${dataString}`);
});

app.listen(5000, () => {
console.log('Server is running on port 5000');
});

Express.Router([options])

The express.Router() middleware basically creates modular route handlers. It acts as a mini Express app, handling requests, middleware, and routes separately from the main application. You define routes and middleware for the router, then mount it on a path in the main app using app.use() for better organization and scalability.

Example:

Node
const express = require('express'); const router = express.Router();  // Define routes for the user resource router.get('/', (req, res) => {     res.send('User list'); });  router.post('/create', (req, res) => {     res.send('User created'); });  module.exports = router; 
Node
const express = require('express'); const app = express();  const userRoutes = require('./routes/userRoutes');  // Mount the router on a path app.use('/users', userRoutes);  app.listen(5000, () => {     console.log('Server is running on port 5000'); }); 

Next Article
How to skip a middleware in Express.js ?

V

vikash147
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • Express.js

Similar Reads

  • Edge Functions and Middleware in Next JS
    Next JS is a React-based full-stack framework developed by Vercel that enables functionalities like pre-rendering of web pages. Unlike traditional react apps where the entire app is loaded on the client. Next.js allows the web page to be rendered on the server, which is great for performance and SEO
    4 min read
  • What is Middleware in Express.js ?
    Middleware functions have access to the request object and the response object and also the next function in the application request-response lifecycle. Middlewares are used for: Change the request or response object.Execute any program or codeEnd the request-response lifecycleCall the next middlewa
    2 min read
  • How to skip a middleware in Express.js ?
    If we want to skip a middleware we can pass parameters to the middleware function and decide based on that parameter which middleware to call and which middleware to not call. Prerequisite: express.js: To handle routing. Setting up environment and execution: Step 1: Initialize node project npm init
    1 min read
  • Express.js res.links() Function
    The res.links() function is used to join the links provided as properties of the parameter to populate the response’s Link HTTP header field. Syntax: res.links( links ) Parameter: The link parameter describes the name of the link to be joined. Return Value: It returns an Object. Installation of the
    2 min read
  • Middleware in Express
    Middleware in Express refers to functions that process requests before reaching the route handlers. These functions can modify the request and response objects, end the request-response cycle, or call the next middleware function. Middleware functions are executed in the order they are defined. They
    6 min read
  • Express.js router.all() Function
    The router.all() function is just like the router.METHOD() methods, except that it matches all HTTP methods (verbs). It is very helpful for mapping global logic for arbitrary matches or specific path prefixes. Syntax: router.all(path, [callback, ...] callback)Parameter: The path parameter is the pat
    2 min read
  • Express.js res.get() Function
    The res.get() function returns the HTTP response header specified by the field. The match is case-insensitive. Syntax: res.get( field ) Parameter: The field parameter describes the name of the field. Return Value: It returns an Object. Installation of the express module: You can visit the link to In
    2 min read
  • Express.js req.get() Function
    The req.get() function returns the specified HTTP request header field which is a case-insensitive match and the Referrer and Referrer fields are interchangeable. Syntax: req.get( field )Parameter: The field parameter specifies the HTTP request header field. Return Value: String. Installation of the
    2 min read
  • Express.js | app.render() Function
    The app.render() function is used to render the HTML of a view via the callback function. This function returns the HTML in the callback function. Syntax: app.render(view, [locals], callback)Parameters: view: It is the name of the HTML page which is to be rendered.locals: It is an optional parameter
    2 min read
  • Express res.json() Function
    The res.json() function sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using the JSON.stringify() method. Syntax: res.json( [body] )Parameters: The body parameter is the body that is to be sent in the response. Ret
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences