ESP32 WebServer Library – addMiddleware()

Home / References / ESP32 Library / WebServer Library

Description

The addMiddleware() method adds a middleware instance or function to process HTTP requests and responses. Middleware provides a powerful way to implement cross-cutting concerns such as authentication, logging, CORS handling, and request/response modification in a reusable and composable manner. Middleware functions are executed in the order they are added and can intercept requests before they reach the handler or modify responses before they are sent to the client. This method is part of the Comprehensive Guide to the ESP32 Arduino Core Library, accessible on AvantMaker.com.


Syntax and Usage

The addMiddleware() method can be used in two different ways:

  • Adding a Middleware Instance: server.addMiddleware(middleware_instance) – Adds a pre-created middleware object that extends the Middleware class.
  • Adding a Middleware Function: server.addMiddleware(middleware_function) – Adds a lambda function or function pointer that implements middleware logic.

Arguments

  • middleware (Middleware*): A pointer to a middleware instance that extends the Middleware base class. The middleware object must remain in scope for the lifetime of the server.
  • fn (Middleware::Function): A function that matches the signature std::function<bool(WebServer &server, Callback next)>. The function receives the WebServer instance and a callback to invoke the next middleware in the chain.

Return Value

Returns a reference to the WebServer instance (WebServer&), allowing for method chaining. This enables you to add multiple middleware or configure other server settings in a fluent interface style.


Example Codes

Example 1: Adding Pre-built Middleware Instances

This example demonstrates how to use addMiddleware method to add pre-built middleware instances for logging, CORS, and authentication to a WebServer.

How to use this example:

1. Replace “your_wifi_ssid” and “your_wifi_password” with your actual WiFi credentials.
2. Upload the code to your ESP32.
3. Open the Serial Monitor to see the logging output and IP address.
4. Access the main page at the displayed IP address to see the basic response.
5. Try to access “/admin” endpoint – you’ll be prompted for authentication (username: admin, password: password123).
6. All requests will be logged and CORS headers will be automatically added to responses.

/*
 * Author: Avant Maker
 * Date: June 17, 2025
 * Version: 1.0
 * License: MIT 
 * 
 * Description: 
 * This example demonstrates how to use addMiddleware method to 
 * add pre-built middleware instances for logging, CORS, and authentication
 * to a WebServer.
 *
 * How to use this example:
 * 1. Replace "your_wifi_ssid" and "your_wifi_password" with your actual
 * WiFi credentials.
 * 2. Upload the code to your ESP32.
 * 3. Open the Serial Monitor to see the logging output and IP address.
 * 4. Access the main page at the displayed IP address to see the basic
 * response.
 * 5. Try to access "/admin" endpoint - you'll be prompted for authentication
 * (username: admin, password: password123).
 * 6. All requests will be logged and CORS headers will be automatically added
 * to responses.
 *
 * Code Source:
 * This example code is sourced from the Comprehensive Guide
 * to the ESP32 Arduino Core Library, accessible on AvantMaker.com.
 * For additional code examples and in-depth documentation related to
 * the ESP32 Arduino Core Library, please visit:
 *
 * https://avantmaker.com/home/all-about-esp32-arduino-core-library/
 *
 * AvantMaker.com, your premier destination for all things
 * DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated
 * to empowering makers, learners, and enthusiasts with
 * the resources they need to bring their nnovative ideas to life.
 */


#include <WiFi.h>
#include <WebServer.h>
#include <Middlewares.h>

const char* ssid = "your_SSID";          // Replace with your Wi-Fi SSID
const char* password = "your_PASSWORD";  // Replace with your Wi-Fi password

WebServer server(80);

// Create middleware instances
LoggingMiddleware logger;
CorsMiddleware cors;
AuthenticationMiddleware auth;

void setup() {
    Serial.begin(115200);
    
    // Connect to WiFi
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
        Serial.println("Connecting to WiFi...");
    }
    Serial.println("Connected to WiFi");
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());
    
    // Configure middleware
    logger.setOutput(Serial);
    
    cors.setOrigin("*");
    cors.setMethods("GET,POST,PUT,DELETE,OPTIONS");
    cors.setHeaders("Content-Type,Authorization");
    
    auth.setUsername("admin");
    auth.setPassword("password123");
    auth.setRealm("ESP32 Admin");
    auth.setAuthMethod(BASIC_AUTH);
    
    // Add middleware to server (executed in order)
    server.addMiddleware(&logger);
    server.addMiddleware(&cors);
    
    // Add routes
    server.on("/", []() {
        server.send(200, "text/html", "<h1>Welcome to AvantMaker ESP32 Server</h1>");
    });
    
    // Protected route with authentication middleware
    server.on("/admin", []() {
        server.send(200, "text/html", "<h1>Admin Panel</h1><p>Access granted!</p>");
    }).addMiddleware(&auth);
    
    server.begin();
    Serial.println("HTTP server started");
}

void loop() {
    server.handleClient();
}

This page is part of the Comprehensive Guide to the ESP32 Arduino Core Library, accessible on AvantMaker.com.

Example 2: Method Chaining with Multiple Middleware

This example demonstrates how to use addMiddleware method with method chaining to add multiple middleware in a fluent interface style and shows middleware execution order.

How to use this example:

1. Replace “your_wifi_ssid” and “your_wifi_password” with your actual WiFi credentials.
2. Upload the code to your ESP32.
3. Open the Serial Monitor to observe the middleware execution order.
4. Access “/test” endpoint to see the middleware chain execution in the Serial Monitor output.
5. Visit “/httpbin-test” to see the CORS-enabled page that can make cross-origin requests.
6. Notice how middleware executes in the order they were added: Logger → CORS → Middleware 1 → Middleware 2 → Handler → Middleware 2 (after) → Middleware 1 (after).

/*
 * Author: Avant Maker
 * Date: June 17, 2025
 * Version: 1.0
 * License: MIT 
 * 
 * Description: 
 * This example demonstrates how to use addMiddleware method with method
 * chaining to add multiple middleware in a fluent interface style and
 * shows middleware execution order.
 *
 * How to use this example:
 * 1. Replace "your_wifi_ssid" and "your_wifi_password" with your actual
 * WiFi credentials.
 * 2. Upload the code to your ESP32.
 * 3. Open the Serial Monitor to observe the middleware execution order.
 * 4. Access "/test" endpoint to see the middleware chain execution in
 * the Serial Monitor output.
 * 5. Visit "/httpbin-test" to see the CORS-enabled page that can make
 * cross-origin requests.
 * 6. Notice how middleware executes in the order they were added:
 * Logger → CORS → Middleware 1 → Middleware 2 → Handler → Middleware 2
 * (after) → Middleware 1 (after).
 *
 * Code Source:
 * This example code is sourced from the Comprehensive Guide
 * to the ESP32 Arduino Core Library, accessible on AvantMaker.com.
 * For additional code examples and in-depth documentation related to
 * the ESP32 Arduino Core Library, please visit:
 *
 * https://avantmaker.com/home/all-about-esp32-arduino-core-library/
 *
 * AvantMaker.com, your premier destination for all things
 * DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated
 * to empowering makers, learners, and enthusiasts with
 * the resources they need to bring their nnovative ideas to life.
 */

#include <WiFi.h>
#include <WebServer.h>
#include <Middlewares.h>

const char* ssid = "your_wifi_ssid";
const char* password = "your_wifi_password";

WebServer server(80);
LoggingMiddleware logger;
CorsMiddleware cors;

void setup() {
    Serial.begin(115200);
    
    // Connect to WiFi
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
        Serial.println("Connecting to WiFi...");
    }
    Serial.println("Connected to WiFi");
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());
    
    // Configure middleware
    logger.setOutput(Serial);
    cors.setOrigin("https://www.httpbin.org")
        .setMethods("GET,POST,OPTIONS")
        .setHeaders("Content-Type");
    
    // Chain multiple middleware additions
    server.addMiddleware(&logger)
          .addMiddleware(&cors)
          .addMiddleware([](WebServer &server, std::function<bool()> next) -> bool {
              Serial.println("Middleware 1: Before handler");
              bool result = next();
              Serial.println("Middleware 1: After handler");
              return result;
          })
          .addMiddleware([](WebServer &server, std::function<bool()> next) -> bool {
              Serial.println("Middleware 2: Before handler");
              bool result = next();
              Serial.println("Middleware 2: After handler");
              return result;
          });
    
    // Add test route
    server.on("/test", []() {
        Serial.println("Handler: Processing request");
        server.send(200, "text/plain", "Middleware chain executed successfully!");
    });
    
    // Route for testing with httpbin.org
    server.on("/httpbin-test", []() {
        server.send(200, "text/html", 
                   "<h1>CORS Test</h1>"
                   "<p>This page can be accessed from https://www.httpbin.org</p>"
                   "<script>"
                   "fetch('/test').then(r => r.text()).then(console.log);"
                   "</script>");
    });
    
    server.begin();
    Serial.println("HTTP server started");
    Serial.println("Visit /test to see middleware execution order");
}

void loop() {
    server.handleClient();
}

For more ESP32 development resources and tutorials, visit the All About ESP32 Resources Hub on  AvantMaker.com

error: Content is protected !!