Arduino library · Network

ESPAsyncWebServer: a web server that needs no handleClient()

ESPAsyncWebServer, now kept by the ESP32Async group, is an asynchronous web server for the ESP32 and ESP8266. Unlike the core WebServer, where loop() must call server.handleClient() to answer anyone, this one is event driven: AsyncTCP (or ESPAsyncTCP on the ESP8266) receives requests in the background and calls your handlers, so loop() can be empty or busy with sensors.

Built in on Mokxi: #include <ESPAsyncWebServer.h> and it builds, with nothing to install. Free, and no account needed.

What ESP Async WebServer does

You create AsyncWebServer server(80), register a handler per path with server.on(), and call server.begin(). Each handler gets an AsyncWebServerRequest pointer: read form fields with hasParam() and getParam(), and answer with request->send(). Pages stored in flash can carry %NAME% placeholders that a processor function fills in as the page goes out, and serveStatic() hands out files from LittleFS.

The example serves a page with a live uptime placeholder, a GET form and a POST form to the editor’s Web panel, on an ESP32-C3. What is not here: AsyncWebSocket and AsyncEventSource compile but no client connects, request headers other than Location are not passed, uploads and regex paths are missing, and a reply stops at 4 KB. A handler must also send before it returns.

Library Manager nameESP Async WebServer
AuthorESP32Async
Include#include <ESPAsyncWebServer.h>
#include <AsyncJson.h>
#include <AsyncWebSocket.h>
#include <AsyncEventSource.h>
BoardsESP32-C3, ESP32-C6, Seeed XIAO ESP32-C3, ESP32-C3 SuperMini, Seeed XIAO ESP32-C6, ESP32 DevKit, ESP32-DevKitC V4, LOLIN32 Lite, Wemos D1 R32, Cheap Yellow Display, TTGO T-Display, ESP32-S3-DevKitC-1, Seeed XIAO ESP32-S3, Arduino Nano ESP32, ESP8266 NodeMCU
In the simulatorRuns, with a gap the note below names.

Install it

It builds on ESP32-C3, ESP32-C6, Seeed XIAO ESP32-C3, ESP32-C3 SuperMini, Seeed XIAO ESP32-C6, ESP32 DevKit, ESP32-DevKitC V4, LOLIN32 Lite, Wemos D1 R32, Cheap Yellow Display, TTGO T-Display, ESP32-S3-DevKitC-1, Seeed XIAO ESP32-S3, Arduino Nano ESP32, ESP8266 NodeMCU.

In Mokxi it is built in: #include <ESPAsyncWebServer.h> and the sketch compiles, with no download, no zip and no Library Manager.

On a real board, install "ESP Async WebServer" by ESP32Async from the Arduino IDE’s Library Manager (Sketch, Include Library, Manage Libraries), or add ESP Async WebServer to lib_deps in PlatformIO. Mokxi follows the calls of release 3.12.1, so a sketch written here builds there too.

What to know in the simulator: WebSockets (AsyncWebSocket) and server-sent events (AsyncEventSource) compile and are not simulated: no client connects. A handler must send before it returns. Headers other than Location are not sent, none reach a handler, authentication passes, regex paths and file uploads are not here, and replies stop at 4 KB.

The calls you will use

In the order a sketch meets them.

AsyncWebServer server(80)

Creates the server on port 80. It does not listen until server.begin().

server.on("/", HTTP_GET, handleRoot)

Registers a handler for a path and method. A lambda is the common style: [](AsyncWebServerRequest *request) { ... }.

request->send(200, "text/plain", "Hello")

Answers with a status code, content type and body. Every request must get exactly one send().

request->send_P(200, "text/html", index_html, processor)

Sends a page from flash, replacing each %NAME% with what processor() returns for NAME.

String processor(const String &var) {
  if (var == "UPTIME") return String(millis() / 1000);
  return String();
}

request->hasParam("message", true)

Asks whether a form field arrived. Pass true for a POST body field, leave it out for a ?query field.

request->getParam("message")->value()

The field’s value as a String. getParam() returns a null pointer when the field is missing, so check hasParam() first.

server.serveStatic("/", LittleFS, "/").setDefaultFile("index.html")

Serves files from LittleFS under a URL prefix, with index.html for the bare path.

server.onNotFound(notFound)

The handler for every path nothing else matched, usually a 404 reply.

server.begin()

Starts listening. Call it after WiFi is connected and every on() is registered.

Example: ESP32 async web server: BME280, slider and relay

On the ESP32 DevKit V1. It runs in the browser exactly as printed.

sketch.ino · ESP32 DevKit V1
/*
 * ESP32 async web server: a page with a BME280's readings, a slider that
 * sets an LED's brightness and a button that switches a relay, served by
 * ESPAsyncWebServer with nothing in loop().
 *
 *   BME280   VIN -> 3V3, GND -> GND, SDA -> GPIO 21 (D21), SCL -> GPIO 22 (D22)
 *   LED      GPIO 26 (D26) -> 220 ohm -> LED -> GND, dimmed with ledcWrite()
 *   Relay    module IN -> GPIO 27 (D27), VCC -> 5 V, GND -> GND
 *            (a 5 V module that switches on a 3.3 V high; COM and NO switch
 *            the 12 V lamp)
 *
 * Libraries: ESPAsyncWebServer and AsyncTCP (ESP32Async), Adafruit BME280.
 *
 * The page is a template: the server fills each %NAME% from processor()
 * as it sends it, so every load shows the newest readings. The slider and
 * the relay button are plain HTML forms, so they work in any browser
 * without JavaScript: /slider?value=128 and /relay?state=on answer by
 * sending the browser back to the page.
 *
 * Press Run, wait for the IP on the Serial Monitor, then open the Web panel.
 * In Mokxi the network is simulated and the Web panel is the only browser;
 * on a real ESP32 any phone on the same WiFi opens http://<the IP>/.
 */
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

const char *SSID = "Mokxi-Lab";
const char *PASSWORD = "breadboard";

const int LED_PIN = 26;
const int RELAY_PIN = 27;

Adafruit_BME280 bme;
AsyncWebServer server(80);

int brightness = 0; // 0 to 255
bool relayOn = false;

const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE html><html><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ESP32 Async Web Server</title>
<style>body{font-family:sans-serif;text-align:center}td{padding:4px 12px}</style>
</head><body>
<h2>ESP32 Async Web Server</h2>
<table align="center">
<tr><td>Temperature</td><td>%TEMPERATURE% &deg;C</td></tr>
<tr><td>Humidity</td><td>%HUMIDITY% %</td></tr>
<tr><td>Pressure</td><td>%PRESSURE% hPa</td></tr>
</table>
<h3>LED brightness: %BRIGHTNESS%</h3>
<form action="/slider">
<input type="range" name="value" min="0" max="255" value="%BRIGHTNESS%">
<input type="submit" value="Set">
</form>
<h3>Relay: %RELAYSTATE%</h3>
<form action="/relay"><button name="state" value="%RELAYNEXT%">Turn %RELAYNEXT%</button></form>
<p><a href="/">Refresh readings</a></p>
</body></html>
)rawliteral";

// Fills each %PLACEHOLDER% of the page.
String processor(const String &var)
{
    if (var == "TEMPERATURE") return String(bme.readTemperature(), 1);
    if (var == "HUMIDITY") return String(bme.readHumidity(), 1);
    if (var == "PRESSURE") return String(bme.readPressure() / 100.0F, 1);
    if (var == "BRIGHTNESS") return String(brightness);
    if (var == "RELAYSTATE") return relayOn ? "on" : "off";
    if (var == "RELAYNEXT") return relayOn ? "off" : "on";
    return String();
}

void setup()
{
    Serial.begin(115200);
    ledcAttach(LED_PIN, 5000, 8); // 5 kHz PWM, 8 bits: duty 0 to 255
    ledcWrite(LED_PIN, brightness);
    pinMode(RELAY_PIN, OUTPUT);
    digitalWrite(RELAY_PIN, LOW);

    if (!bme.begin(0x76)) {
        Serial.println("No BME280 at 0x76: check SDA, SCL and the address");
    }

    WiFi.begin(SSID, PASSWORD);
    Serial.print("Connecting to WiFi");
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println();
    Serial.print("Open http://");
    Serial.println(WiFi.localIP());

    server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
        request->send(200, "text/html", index_html, processor);
    });

    // /slider?value=0..255 sets the LED's brightness
    server.on("/slider", HTTP_GET, [](AsyncWebServerRequest *request) {
        if (request->hasParam("value")) {
            brightness = constrain(request->getParam("value")->value().toInt(), 0, 255);
            ledcWrite(LED_PIN, brightness);
            Serial.print("LED brightness ");
            Serial.println(brightness);
        }
        request->redirect("/");
    });

    // /relay?state=on or off switches the relay
    server.on("/relay", HTTP_GET, [](AsyncWebServerRequest *request) {
        if (request->hasParam("state")) {
            relayOn = request->getParam("state")->value() == "on";
            digitalWrite(RELAY_PIN, relayOn ? HIGH : LOW);
            Serial.println(relayOn ? "Relay on" : "Relay off");
        }
        request->redirect("/");
    });

    // The readings as JSON, for another program to read
    server.on("/readings", HTTP_GET, [](AsyncWebServerRequest *request) {
        String json = "{\"temperature\":" + String(bme.readTemperature(), 1) +
                      ",\"humidity\":" + String(bme.readHumidity(), 1) +
                      ",\"pressure\":" + String(bme.readPressure() / 100.0F, 1) + "}";
        request->send(200, "application/json", json);
    });

    server.onNotFound([](AsyncWebServerRequest *request) {
        request->send(404, "text/plain", "Not found");
    });

    server.begin();
}

void loop()

The sketch is cut short here; the editor has every line of it.

Open it in the editor, wired and ready to run · ESP32 async web server: BME280, slider and relay: the project page

Common errors and how to fix them

The board resets with a watchdog error when a page is opened

A handler runs inside the TCP task, and a delay(), a long sensor read or a blocking HTTP call there starves it. Keep handlers short: set a flag or store the request’s values, then do the slow work in loop().

The page shows %UPTIME% or breaks where the CSS has percentages

Placeholders are only filled when you pass a processor to send_P() or send(). Once you do, every % in the page is read as a placeholder marker, so write a literal percent sign in CSS as %%.

Crash or Guru Meditation Error when a form is submitted empty

getParam() returned nullptr because the field was missing, and ->value() dereferenced it. Test hasParam() first, and pass true to both for fields in a POST body, since the default only looks at the URL query.

AsyncTCP.h: No such file or directory on an ESP8266

AsyncTCP is the ESP32 transport. On the ESP8266 include <ESPAsyncTCP.h> instead, behind #ifdef ESP32 as the example does, and install the ESP32Async versions of both so they match.

Questions and answers

Async or the built-in WebServer?

The built-in WebServer is simpler and answers only while loop() calls handleClient(). The async server answers in the background and handles several clients at once, at the cost of handlers that must never block.

Which fork should I install?

The ESP32Async organization’s ESPAsyncWebServer and AsyncTCP are the maintained ones. Older tutorials link to me-no-dev’s repositories, which work with the same code but are no longer updated.

Try ESP Async WebServer without installing anything

Open the example, change the sketch, and keep your version in a free account.