Home / References / ESP32 Library / WebServer Library
Description
The serveStatic()
method in the ESP32 WebServer Library enables your ESP32 to serve static files—such as HTML, CSS, JavaScript, or images—stored in a filesystem like SPIFFS or LittleFS. This method simplifies the process of delivering web content to clients, making it ideal for building responsive web interfaces for your projects. By mapping a URI to a filesystem path, it allows seamless access to preloaded files, enhancing the functionality of your ESP32-based web server.
Syntax and Usage
The serveStatic()
method is called on a WebServer
object to configure static file serving. Below is the basic syntax, followed by its usage variations:
server.serveStatic(uri, fs, path, cache_header);
Here are the different ways to use this method:
- With all arguments: Specify the URI, filesystem, file path, and an optional cache header to control browser caching behavior.
- Without cache header: Omit the cache header argument to serve files without specific caching instructions, relying on default browser behavior.
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.
Argument(s)
The serverStatic()
method accepts the following arguments:
uri
: Aconst char*
representing the base URI path on the web server. Requests starting with this path will be handled by this static file server. For example, using “/” will handle requests from the root directory, while “/static” would handle requests like “/static/style.css”.fs
: A reference (fs::FS&
) to an initialized filesystem object, such asSPIFFS
orLittleFS
. This tells the server which filesystem contains the static files.path
: Aconst char*
representing the base directory *within* the specified filesystem (fs
) where the static files are located. For example, ifuri
is “/” andpath
is “/www”, a request for “/index.html” will cause the server to look for the file “/www/index.html” in the filesystem.cache_header
(Optional): Aconst char*
specifying the value for the HTTPCache-Control
header. This allows you to suggest caching policies to the browser (e.g., “max-age=86400” for one day). If omitted or set toNULL
, a default caching behavior (or no specific cache header) might be applied by the server library.
Return Value
The serveStatic()
method does not return a value directly. Instead, it configures the WebServer
object to handle requests to the specified URI by serving the corresponding file from the filesystem. If the file exists and the request matches, the server responds with the file content; otherwise, it triggers a 404 error unless a custom onNotFound()
handler is defined.
Example Codes
Below are example code illustrating the usage of the serveStatic()
function. To run these examples, you’ll need to upload the necessary files to your ESP32’s flash filesystem (either SPIFFS or LittleFS). If you require help with this process, please consult the notes provided within each example’s description.
Example 1: Serve static web pages stored in the SPIFFS.
This example code illustrates the use of the ESP32 WebServer library’s serveStatic()
method. This method enables the ESP32 to automatically serve static files, such as HTML, CSS, JavaScript, and images, stored in its SPI Flash File System (SPIFFS) directly to requesting web browsers.
For testing purposes, first prepare the SPIFFS on your ESP32 by uploading an ‘index.html’ file along with any other files you intend to test. Subsequently, locate the “your_SSID” and “your_PASSWORD” lines in the code, replace the placeholders with your actual Wi-Fi network details, and then upload the sketch to your ESP32.
Once the upload is complete, open the Serial Monitor at a baud rate of 115200 to identify the IP address assigned to your ESP32. Enter this IP address into your web browser to access and view the served ‘index.html’ file with the following url:
http://[Your-ESP32-IP]/index.html
To test other uploaded files, simply append their filenames to the ESP32’s IP address in the browser’s address bar (e.g., http://[Your-ESP32-IP]/your_other_file.html).
NOTE – To ensure this example code runs correctly, you can either create your own “index.html” files or download our pre-built ones from Dropbox: [Click here to download the pre-built ‘index.html’ file]
ESP32-WebFS: Simplifying SPIFFS File Management for Your ESP32 Projects
If you are looking for a tool or need guidance to upload and manage files in the SPIFFS (SPI Flash File System) of your ESP32 microcontroller, please check out our GitHub project, ESP32-WebFS , which simplifies SPIFFS file management for your ESP32 projects. It also serves as a great reference project that you can integrate into your own projects requiring ESP32 SPIFFS management.
ESP32-WebFS can turn your ESP32 microcontroller into a web server that provides a web-based interface to manage the SPIFFS on your ESP32. It enables you to upload, download, delete, and view files stored on your ESP32, making it easy to interact with your ESP32’s file system wirelessly.
For downloads and instructions on how to use this tool, please visit the ESP32-WebFS GitHub repository.
/*
* Author: Avant Maker
* Date: March 17, 2025
* Version: 1.0
* License: MIT
*
* Description:
* This example code demonstrates how to use the ESP32 WebServer
* library's serveStatic() method to serve static web pages stored
* in the SPIFFS.
*
* 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 innovative ideas to life.
*/
#include <WiFi.h>
#include <WebServer.h>
#include <SPIFFS.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);
void setup() {
Serial.begin(115200);
// Initialize SPIFFS
if(!SPIFFS.begin(true)){
Serial.println("An error occurred while mounting SPIFFS");
return;
}
// 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());
// Serve static files from SPIFFS root directory
server.serveStatic("/", SPIFFS, "/");
// Note: Enable browser caching for static content.
// The serveStatic() method allows you to add cache control headers.
// For instance, the line below configures a "max-age" directive,
// instructing browsers to cache served files for 3600 seconds (1 hour).
// server.serveStatic("/", SPIFFS, "/", "max-age=3600");
// Handle 404
server.onNotFound([]() {
server.send(404, "text/plain", "File Not Found");
});
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
}
Example 2: Serve static web pages stored in the LittleFS file system.
The ESP32, in this setup, functions as a web server that can deliver web pages to requesting browsers. Notably, this example demonstrates a distinction between publicly accessible content and password-protected areas.
Specifically, accessing following URLs will result in the server serving the respective HTML files stored in the LittleFS.
http://[ESP32 IP]/path1/page1.html
http://[ESP32 IP]/path2/page2.html
Conversely, attempting to access content within the /protected/
path, such as the following url will trigger a username and password prompt, requiring users to provide the correct credentials defined in the code for access.
http://[ESP32 IP]/protected/protected.html
ESP32 LittleFS File Upload
To ensure the following example code runs properly, you need to upload necessary files to the LittleFS File System of your ESP32 microcontroller. If you are unsure how to do this, please check out our LittleFS reference for detailed instructions. You can access the reference directly by clicking on the following URL.
To use this code, follow these steps:
- Ensure the files are uploaded to the ESP32’s LittleFS partition according to the following directory structure. The code relies on this specific structure to find the files:
[LittleFS Root]
├── path1/
│ └── page1.html
├── path2/
│ └── page2.html
└── protected/
└── protected.html
NOTE – To ensure this example code runs correctly, you can either create your own web page files or download our pre-built ones from Dropbox: [Click here to download the web page files] - Modify the
ssid
andpassword
variables in the code to match your Wi-Fi network credentials. Then, upload the code to your ESP32 board. - To test the public pages served by the ESP32 Web Server, open a web browser and navigate to
http://[ESP32 IP]/path1/page1.html
orhttp://[ESP32 IP]/path2/page2.html
Replace[ESP32 IP]
with the actual IP address assigned to your ESP32, which will be printed in the Arduino IDE’s Serial Monitor after the ESP32 successfully connects to your Wi-Fi network. - To test the protected page, open a web browser and navigate to
http://[ESP32 IP]/protected/protected.html
You should be prompted to enter a username and password. Use the credentials defined in thewww_username
andwww_password
variables in the code (default: avantmaker / esp32admin) to access the page.
/*
* Author: Avant Maker
* Date: March 17, 2025
* Version: 1.0
* License: MIT
*
* Description:
* This example code demonstrates how to use the ESP32 WebServer
* library's serveStatic() method to serve static web pages stored
* in the LittleFS (Little File System). It shows how different
* paths can be configured to serve files directly from the filesystem.
*
* 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 innovative ideas to life.
*/
#include <WiFi.h>
#include <WebServer.h>
#include <LittleFS.h>
const char* ssid = "ssid"; // Replace with your Wi-Fi SSID
const char* password = "password"; // Replace with your Wi-Fi password
// Authentication credentials
const char* www_username = "avantmaker";
const char* www_password = "esp32admin";
WebServer server(80);
// Authentication check
bool authenticate() {
if (!server.authenticate(www_username, www_password)) {
server.requestAuthentication();
return false;
}
return true;
}
// Custom handler for protected files
void handleProtected() {
Serial.println("handleProtected");
if (!authenticate()) {
Serial.println("authenticate fail");
return;
}
String path = "/protected" + server.uri().substring(10); // Remove "/protected" from URI
Serial.print("path = ");
Serial.println(path);
if (LittleFS.exists(path)) {
Serial.println("LittleFS file path exists.");
File file = LittleFS.open(path, "r");
server.streamFile(file, getContentType(path));
file.close();
}
}
// Helper function to determine content type
String getContentType(String filename) {
if (filename.endsWith(".html")) return "text/html";
else if (filename.endsWith(".css")) return "text/css";
else if (filename.endsWith(".js")) return "application/javascript";
else if (filename.endsWith(".png")) return "image/png";
else if (filename.endsWith(".jpg")) return "image/jpeg";
else if (filename.endsWith(".ico")) return "image/x-icon";
return "text/plain";
}
void setup() {
Serial.begin(115200);
delay(200);
// Initialize LittleFS
if(!LittleFS.begin(true)){
Serial.println("An error occurred while mounting LittleFS");
return;
}
delay(200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi Connected:");
Serial.print("IP: ");
Serial.println(WiFi.localIP());
server.serveStatic("/path2", LittleFS, "/path2/");
server.serveStatic("/path1", LittleFS, "/path1/");
server.on("/protected/protected.html", handleProtected);
server.begin();
}
void loop() {
server.handleClient();
}
ESP32 Library Index
- ESP32 WiFi Library
- ESP32 WiFiClient Library
- ESP32 HTTPClient Library
- ESP32 WiFiClientSecure Library
- ESP32 WebServer Library
- Server Operation
- Client Hnadling
- Routing and Handlers
- Authentication
- Request Information
- Which ESP32 Boards are Recommended for Learners
- How to Copy Codes from AvantMaker.com
- What is SPIFFS and how to upload files to it?
- What is LIttleFS and how to upload files to it?
Ready to experiment and explore more about ESP32? Visit our website’s All About ESP32 Resources Hub, packed with tutorials, guides, and tools to inspire your maker journey. Experiment, explore, and elevate your skills with everything you need to master this powerful microcontroller platform!