ESP32 WebServer Library – removeMiddleware()

Home / References / ESP32 Library / WebServer Library

Description

The removeMiddleware() method removes a previously added middleware instance from the WebServer’s middleware chain. This method allows you to dynamically unregister middleware during runtime, providing flexibility to modify the request/response processing pipeline based on changing application requirements. When a middleware is removed, it will no longer be executed for incoming requests, and if the middleware was created with automatic memory management, it will be properly deallocated. This guide is part of the Comprehensive Guide to the ESP32 Arduino Core Library, accessible on AvantMaker.com.


Syntax and Usage

The removeMiddleware() method can be used in one way:

  • Removing a Middleware Instance: server.removeMiddleware(middleware_instance) – Removes a specific middleware instance that was previously added to the server’s middleware chain.

For practical applications and examples of this method, please consult the “Example Code” section on this page. This section provides comprehensive guidance to help you better understand and apply the method effectively.


Arguments

  • middleware (Middleware*): A pointer to the middleware instance that should be removed from the middleware chain. This must be the same pointer that was previously passed to addMiddleware(). If the middleware is not found in the chain, the method will have no effect.

Return Value

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


Example Codes

Dynamic Middleware Management

This example demonstrates how to use removeMiddleware method to dynamically add and remove middleware based on application state, such as enabling/disabling authentication during runtime.

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 “/public” endpoint to see the response with logging middleware active.
5. Access “/disable-auth” to remove the authentication middleware from the “/protected” route.
6. Access “/enable-auth” to add the authentication middleware back to the “/protected” route.
7. Try accessing “/protected” before and after toggling authentication to see the difference.

/*
 * Author: Avant Maker
 * Date: June 17, 2025
 * Version: 1.0
 * License: MIT 
 * 
 * Description: 
 * This example demonstrates how to use removeMiddleware method to dynamically
 * add and remove middleware based on application state, such as enabling/disabling
 * authentication during runtime.
 *
 * 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 "/public" endpoint to see the response with logging middleware active.
 * 5. Access "/disable-auth" to remove the authentication middleware from the
 * "/protected" route.
 * 6. Access "/enable-auth" to add the authentication middleware back to the
 * "/protected" route.
 * 7. Try accessing "/protected" before and after toggling authentication to
 * see the difference.
 *
 * 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);

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

// Keep track of middleware state
bool authEnabled = true;
bool corsEnabled = true;

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 Dynamic Auth");
    auth.setAuthMethod(BASIC_AUTH);
    
    // Add initial middleware to server
    server.addMiddleware(&logger);
    server.addMiddleware(&cors);
    
    // Public route - always accessible
    server.on("/public", []() {
        server.send(200, "text/html", 
                   "<h1>Public Page</h1>"
                   "<p>This page is always accessible</p>"
                   "<p><a href='/protected'>Try Protected Page</a></p>"
                   "<p><a href='/disable-auth'>Disable Auth</a> | "
                   "<a href='/enable-auth'>Enable Auth</a></p>"
                   "<p><a href='/disable-cors'>Disable CORS</a> | "
                   "<a href='/enable-cors'>Enable CORS</a></p>");
    });
    
    // Protected route - authentication can be toggled
    server.on("/protected", []() {
        server.send(200, "text/html", 
                   "<h1>Protected Page</h1>"
                   "<p>Authentication Status: " + String(authEnabled ? "Enabled" : "Disabled") + "</p>"
                   "<p>CORS Status: " + String(corsEnabled ? "Enabled" : "Disabled") + "</p>"
                   "<p><a href='/public'>Back to Public Page</a></p>");
    }).addMiddleware(&auth);
    
    // Route to disable authentication middleware
    server.on("/disable-auth", []() {
        if (authEnabled) {
            server.removeMiddleware(&auth);
            authEnabled = false;
            Serial.println("Authentication middleware removed");
        }
        server.send(200, "text/html", 
                   "<h1>Authentication Disabled</h1>"
                   "<p>Authentication middleware has been removed</p>"
                   "<p><a href='/protected'>Try Protected Page (No Auth)</a></p>"
                   "<p><a href='/public'>Back to Public Page</a></p>");
    });
    
    // Route to enable authentication middleware
    server.on("/enable-auth", []() {
        if (!authEnabled) {
            server.addMiddleware(&auth);
            authEnabled = true;
            Serial.println("Authentication middleware added");
        }
        server.send(200, "text/html", 
                   "<h1>Authentication Enabled</h1>"
                   "<p>Authentication middleware has been added</p>"
                   "<p><a href='/protected'>Try Protected Page (With Auth)</a></p>"
                   "<p><a href='/public'>Back to Public Page</a></p>");
    });
    
    // Route to disable CORS middleware
    server.on("/disable-cors", []() {
        if (corsEnabled) {
            server.removeMiddleware(&cors);
            corsEnabled = false;
            Serial.println("CORS middleware removed");
        }
        server.send(200, "text/html", 
                   "<h1>CORS Disabled</h1>"
                   "<p>CORS middleware has been removed</p>"
                   "<p><a href='/protected'>Try Protected Page</a></p>"
                   "<p><a href='/public'>Back to Public Page</a></p>");
    });
    
    // Route to enable CORS middleware
    server.on("/enable-cors", []() {
        if (!corsEnabled) {
            server.addMiddleware(&cors);
            corsEnabled = true;
            Serial.println("CORS middleware added");
        }
        server.send(200, "text/html", 
                   "<h1>CORS Enabled</h1>"
                   "<p>CORS middleware has been added</p>"
                   "<p><a href='/protected'>Try Protected Page</a></p>"
                   "<p><a href='/public'>Back to Public Page</a></p>");
    });
    
    // Status route to check current middleware state
    server.on("/status", []() {
        server.send(200, "application/json", 
                   "{\"authentication\":" + String(authEnabled ? "true" : "false") + 
                   ",\"cors\":" + String(corsEnabled ? "true" : "false") + 
                   ",\"message\":\"Middleware status retrieved successfully\"}");
    });
    
    server.begin();
    Serial.println("HTTP server started");
    Serial.println("Visit /public to start exploring middleware management");
}

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 !!