ESP32 Sensor Data to a Website with Cloud MQTT and Netlify

In this article (15 sections)
- What we will build
- Why MQTT, and why the browser connects directly
- What you need
- Step 1: Wire the sensors
- Step 2: Create a free cloud MQTT account
- Step 3: Install the Arduino libraries
- Step 4: The ESP32 code (Part 1)
- Step 5: Test before you build the website
- Step 6: Build the website
- Step 7: Put the website on Netlify
- A word on security
- Part 2: Control a relay from the website
- If something does not work
- Turn this into your college project
- Frequently asked questions
You have an ESP32 and a sensor on your desk, and you want to see the readings on a website from anywhere, and later switch something on and off with a button. This guide shows you exactly how, with every account, every setting and every line of code, using a free cloud MQTT broker and free Netlify hosting.
What we will build
Part 1 shows live temperature, humidity and light readings on a web page. Part 2 adds a relay ON/OFF button on the same page. This is how the data travels:
- 1ESP32 reads the sensorsA DHT11 (temperature and humidity) and an LDR (light) are read every 5 seconds.
- 2ESP32 publishes to the cloudIt sends the readings as a small JSON message to a topic on the HiveMQ Cloud MQTT broker, over Wi-Fi.
- 3The broker passes it onThe broker delivers the message to everyone who has subscribed to that topic.
- 4The website receives itYour page on Netlify connects to the broker from the browser and updates the numbers instantly.
- 5The button sends commands backIn Part 2 the page publishes ON or OFF to a relay topic, and the ESP32, which subscribes to it, switches the relay.
Why MQTT, and why the browser connects directly
- Light and fast: MQTT messages are tiny, so it works well on a small ESP32
- Live: the broker pushes new data to the page the moment it arrives, so there is no refreshing
- Two-way: the same system carries sensor data to the website and commands back to the ESP32
- No server of your own: the cloud broker sits in the middle, and Netlify only serves a static page

What you need
- ESP32 development board and a USB cable that can carry data
- DHT11 sensor module with 3 pins (VCC, GND and DATA)
- LDR (light sensor) and a 10 kΩ resistor
- Relay module (for Part 2) and some jumper wires and a breadboard
- Arduino IDE with ESP32 board support installed
- A 2.4 GHz Wi-Fi network with internet access
- An email address for the free HiveMQ and Netlify accounts, and a text editor like Notepad
Step 1: Wire the sensors
| Part | Part pin | Connect to ESP32 |
|---|---|---|
| DHT11 | VCC (+) | 3V3 |
| DHT11 | GND (-) | GND |
| DHT11 | DATA / OUT | GPIO 4 |
| LDR | Leg 1 | 3V3 |
| LDR | Leg 2 | GPIO 34, and also to GND through the 10 kΩ resistor |
| Relay (Part 2) | VCC / IN / GND | 5V (VIN) / GPIO 26 / GND |
Step 2: Create a free cloud MQTT account
We use HiveMQ Cloud, which has a free plan. Other brokers work the same way, only the names of the settings change.
- 1Sign upGo to hivemq.com, choose HiveMQ Cloud and sign up for the free plan with your email.
- 2Create a clusterCreate a free (serverless) cluster and pick the region that is closest to you. Wait a minute until it is running.
- 3Note the cluster URLOpen the cluster. You will see a URL like
abcd1234.s1.eu.hivemq.cloud. This is your MQTT host. - 4Note the portsPort 8883 is MQTT over TLS, which the ESP32 uses. Port 8884 is secure WebSocket, which the website uses.
- 5Create credentialsOpen Access Management (or Credentials) and add a username and password. Create two users:
esp32-devicefor the ESP32 andweb-userfor the website. If your plan lets you set permissions, give the website user as little as possible. - 6Choose a unique topicA topic is just a name. Use something unique, for example
robozz/yourname123/sensors, so that nobody else mixes in.
| Broker option | Cost | Good for |
|---|---|---|
| HiveMQ Cloud | Free plan available (limits can change) | This tutorial: easy setup, TLS and WebSockets included |
| EMQX Cloud serverless | Free quota available | A similar alternative |
| Mosquitto on your own server | Software is free, the server costs money | Full control, for advanced users |
| Public test brokers | Free | Only for a quick test. Anyone can read your data, so never use them for a real project |
Step 3: Install the Arduino libraries
In the Arduino IDE open Sketch, Include Library, Manage Libraries and install these three:
- PubSubClient by Nick O’Leary, for MQTT
- DHT sensor library by Adafruit, for the DHT11
- Adafruit Unified Sensor, which the DHT library needs
Step 4: The ESP32 code (Part 1)
Change the lines marked CHANGE THIS: your Wi-Fi name and password, the HiveMQ host, the device username and password, and your own topic. Then upload.
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
#include <DHT.h>
// ---- CHANGE THIS ----
const char* WIFI_SSID = "YOUR_WIFI_NAME";
const char* WIFI_PASS = "YOUR_WIFI_PASSWORD";
const char* MQTT_HOST = "abcd1234.s1.eu.hivemq.cloud"; // your cluster URL
const char* MQTT_USER = "esp32-device";
const char* MQTT_PASS = "YOUR_DEVICE_PASSWORD";
const char* TOPIC_DATA = "robozz/yourname123/sensors";
// ---------------------
const int MQTT_PORT = 8883;
#define DHT_PIN 4
#define LDR_PIN 34
DHT dht(DHT_PIN, DHT11);
WiFiClientSecure secureClient;
PubSubClient mqtt(secureClient);
unsigned long lastSend = 0;
void connectWifi() {
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
}
void connectMqtt() {
while (!mqtt.connected()) {
Serial.print("Connecting to MQTT... ");
String clientId = "esp32-" + String((uint32_t)ESP.getEfuseMac(), HEX);
if (mqtt.connect(clientId.c_str(), MQTT_USER, MQTT_PASS)) {
Serial.println("connected");
} else {
Serial.print("failed, state = ");
Serial.println(mqtt.state());
delay(3000);
}
}
}
void setup() {
Serial.begin(115200);
dht.begin();
connectWifi();
secureClient.setInsecure(); // see the security note below
mqtt.setServer(MQTT_HOST, MQTT_PORT);
}
void loop() {
if (WiFi.status() != WL_CONNECTED) connectWifi();
if (!mqtt.connected()) connectMqtt();
mqtt.loop();
if (millis() - lastSend > 5000) {
lastSend = millis();
float t = dht.readTemperature();
float h = dht.readHumidity();
int light = analogRead(LDR_PIN);
if (isnan(t) || isnan(h)) {
Serial.println("DHT11 read failed");
return;
}
char msg[100];
snprintf(msg, sizeof(msg), "{\"temp\":%.1f,\"hum\":%.1f,\"light\":%d}", t, h, light);
mqtt.publish(TOPIC_DATA, msg);
Serial.println(msg);
}
}setInsecure() makes the ESP32 skip checking the broker’s certificate. The connection is still encrypted, but the ESP32 cannot be sure it is talking to the real broker. This is fine for learning. For a real product, load the broker’s root certificate with setCACert() instead.Step 5: Test before you build the website
- 1Open the Serial MonitorSet it to 115200 baud. You should see the dots, then “WiFi connected”, then “connected” for MQTT, then a message like
{"temp":28.5,"hum":61.0,"light":2310}every 5 seconds. - 2Open the HiveMQ web clientIn your cluster there is a Web Client. Connect with the website user, subscribe to your topic, and watch the same messages arrive. If they do, the cloud side works.

Step 6: Build the website
Create a folder called esp32-dashboard and inside it a file named index.html. Paste the code below, then change the host, user, password and topic at the top of the script. Use the website user here, not the device user.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ESP32 Live Dashboard</title>
<style>
body { font-family: Arial, sans-serif; background: #f4f6f5; margin: 0; padding: 20px; color: #1c1c1a; }
h1 { font-size: 1.4rem; }
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; max-width: 600px; }
.card { background: #fff; border-radius: 12px; padding: 16px; box-shadow: 0 1px 4px rgba(0,0,0,.1); }
.value { font-size: 2rem; font-weight: bold; color: #2a7560; }
.label { color: #6e6e69; font-size: .85rem; }
#status { margin: 12px 0; font-size: .9rem; }
</style>
</head>
<body>
<h1>ESP32 Live Dashboard</h1>
<div id="status">Connecting...</div>
<div class="grid">
<div class="card"><div class="label">Temperature</div><div class="value"><span id="temp">--</span> °C</div></div>
<div class="card"><div class="label">Humidity</div><div class="value"><span id="hum">--</span> %</div></div>
<div class="card"><div class="label">Light (0 to 4095)</div><div class="value"><span id="light">--</span></div></div>
</div>
<p class="label">Last update: <span id="time">never</span></p>
<script src="https://unpkg.com/mqtt@5/dist/mqtt.min.js"></script>
<script>
// ---- CHANGE THIS ----
var HOST = "abcd1234.s1.eu.hivemq.cloud";
var USER = "web-user";
var PASS = "YOUR_WEB_PASSWORD";
var TOPIC_DATA = "robozz/yourname123/sensors";
// ---------------------
var client = mqtt.connect("wss://" + HOST + ":8884/mqtt", {
username: USER,
password: PASS,
clientId: "web-" + Math.random().toString(16).slice(2, 10)
});
client.on("connect", function () {
document.getElementById("status").textContent = "Connected to the cloud broker";
client.subscribe(TOPIC_DATA);
});
client.on("close", function () {
document.getElementById("status").textContent = "Disconnected, trying again...";
});
client.on("error", function (e) {
document.getElementById("status").textContent = "Error: " + e.message;
});
client.on("message", function (topic, payload) {
if (topic !== TOPIC_DATA) return;
var d = JSON.parse(payload.toString());
document.getElementById("temp").textContent = d.temp;
document.getElementById("hum").textContent = d.hum;
document.getElementById("light").textContent = d.light;
document.getElementById("time").textContent = new Date().toLocaleTimeString();
});
</script>
</body>
</html>Double-click the file to open it in your browser. Within a few seconds the numbers should appear and change when the ESP32 sends new data.
Step 7: Put the website on Netlify
- 1Create an accountGo to netlify.com and sign up for free with your email or GitHub account.
- 2Add a new siteIn the dashboard choose Add new site, then Deploy manually (the drag and drop option).
- 3Drop the folderDrag your
esp32-dashboardfolder into the box. Netlify uploads it and gives you a link likerandom-name.netlify.app. - 4Rename the siteIn Site settings you can change the name to something nicer, for example
yourname-iot-dashboard.netlify.app. - 5Share the linkOpen the link on your phone. As long as the ESP32 is powered and on Wi-Fi, the numbers update live.
A word on security
- Use a separate website user, and give it only the permissions it needs if your broker allows it
- Use a long, unique topic name so that strangers do not stumble on your data
- If a password leaks, change it in the broker and update the page
- For a serious product, add a login and a small backend, so that the browser never holds a broker password
Part 2: Control a relay from the website
Now we add a button. The page will publish ON or OFF to a relay topic, and the ESP32 will subscribe to it and switch the relay. The ESP32 also reports the relay state back, so the page always shows the true state.
ESP32 code with the relay (final version)
This is the complete sketch. It keeps the sensors from Part 1 and adds the relay. New topics are relay (commands) and relay/state (status).
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
#include <DHT.h>
// ---- CHANGE THIS ----
const char* WIFI_SSID = "YOUR_WIFI_NAME";
const char* WIFI_PASS = "YOUR_WIFI_PASSWORD";
const char* MQTT_HOST = "abcd1234.s1.eu.hivemq.cloud";
const char* MQTT_USER = "esp32-device";
const char* MQTT_PASS = "YOUR_DEVICE_PASSWORD";
const char* TOPIC_DATA = "robozz/yourname123/sensors";
const char* TOPIC_RELAY = "robozz/yourname123/relay";
const char* TOPIC_STATE = "robozz/yourname123/relay/state";
// ---------------------
const int MQTT_PORT = 8883;
#define DHT_PIN 4
#define LDR_PIN 34
#define RELAY_PIN 26
DHT dht(DHT_PIN, DHT11);
WiFiClientSecure secureClient;
PubSubClient mqtt(secureClient);
unsigned long lastSend = 0;
// Runs whenever a message arrives on a topic we subscribed to
void onMessage(char* topic, byte* payload, unsigned int length) {
String msg;
for (unsigned int i = 0; i < length; i++) msg += (char)payload[i];
if (String(topic) == TOPIC_RELAY) {
bool on = (msg == "ON");
digitalWrite(RELAY_PIN, on ? LOW : HIGH); // active LOW relay board
mqtt.publish(TOPIC_STATE, on ? "ON" : "OFF", true); // report the state back
}
}
void connectWifi() {
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
}
void connectMqtt() {
while (!mqtt.connected()) {
Serial.print("Connecting to MQTT... ");
String clientId = "esp32-" + String((uint32_t)ESP.getEfuseMac(), HEX);
if (mqtt.connect(clientId.c_str(), MQTT_USER, MQTT_PASS)) {
Serial.println("connected");
mqtt.subscribe(TOPIC_RELAY);
} else {
Serial.print("failed, state = ");
Serial.println(mqtt.state());
delay(3000);
}
}
}
void setup() {
Serial.begin(115200);
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN, HIGH); // relay OFF at start
dht.begin();
connectWifi();
secureClient.setInsecure();
mqtt.setServer(MQTT_HOST, MQTT_PORT);
mqtt.setCallback(onMessage);
}
void loop() {
if (WiFi.status() != WL_CONNECTED) connectWifi();
if (!mqtt.connected()) connectMqtt();
mqtt.loop();
if (millis() - lastSend > 5000) {
lastSend = millis();
float t = dht.readTemperature();
float h = dht.readHumidity();
int light = analogRead(LDR_PIN);
if (isnan(t) || isnan(h)) return;
char msg[100];
snprintf(msg, sizeof(msg), "{\"temp\":%.1f,\"hum\":%.1f,\"light\":%d}", t, h, light);
mqtt.publish(TOPIC_DATA, msg);
Serial.println(msg);
}
}Website with the ON/OFF button (final version)
Replace your index.html with this. The new parts are the two buttons, the relay status line and the extra topics. Upload the folder to Netlify again.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ESP32 Live Dashboard</title>
<style>
body { font-family: Arial, sans-serif; background: #f4f6f5; margin: 0; padding: 20px; color: #1c1c1a; }
h1 { font-size: 1.4rem; }
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; max-width: 600px; }
.card { background: #fff; border-radius: 12px; padding: 16px; box-shadow: 0 1px 4px rgba(0,0,0,.1); }
.value { font-size: 2rem; font-weight: bold; color: #2a7560; }
.label { color: #6e6e69; font-size: .85rem; }
#status { margin: 12px 0; font-size: .9rem; }
button { font-size: 1rem; padding: 10px 18px; border: 0; border-radius: 8px; color: #fff; cursor: pointer; margin-right: 8px; }
#btnOn { background: #2a7560; }
#btnOff { background: #b42318; }
</style>
</head>
<body>
<h1>ESP32 Live Dashboard</h1>
<div id="status">Connecting...</div>
<div class="grid">
<div class="card"><div class="label">Temperature</div><div class="value"><span id="temp">--</span> °C</div></div>
<div class="card"><div class="label">Humidity</div><div class="value"><span id="hum">--</span> %</div></div>
<div class="card"><div class="label">Light (0 to 4095)</div><div class="value"><span id="light">--</span></div></div>
</div>
<p class="label">Last update: <span id="time">never</span></p>
<h2>Relay</h2>
<button id="btnOn">Turn ON</button>
<button id="btnOff">Turn OFF</button>
<p>Relay state: <strong id="relay">unknown</strong></p>
<script src="https://unpkg.com/mqtt@5/dist/mqtt.min.js"></script>
<script>
// ---- CHANGE THIS ----
var HOST = "abcd1234.s1.eu.hivemq.cloud";
var USER = "web-user";
var PASS = "YOUR_WEB_PASSWORD";
var TOPIC_DATA = "robozz/yourname123/sensors";
var TOPIC_RELAY = "robozz/yourname123/relay";
var TOPIC_STATE = "robozz/yourname123/relay/state";
// ---------------------
var client = mqtt.connect("wss://" + HOST + ":8884/mqtt", {
username: USER,
password: PASS,
clientId: "web-" + Math.random().toString(16).slice(2, 10)
});
client.on("connect", function () {
document.getElementById("status").textContent = "Connected to the cloud broker";
client.subscribe([TOPIC_DATA, TOPIC_STATE]);
});
client.on("close", function () {
document.getElementById("status").textContent = "Disconnected, trying again...";
});
client.on("error", function (e) {
document.getElementById("status").textContent = "Error: " + e.message;
});
client.on("message", function (topic, payload) {
var text = payload.toString();
if (topic === TOPIC_DATA) {
var d = JSON.parse(text);
document.getElementById("temp").textContent = d.temp;
document.getElementById("hum").textContent = d.hum;
document.getElementById("light").textContent = d.light;
document.getElementById("time").textContent = new Date().toLocaleTimeString();
} else if (topic === TOPIC_STATE) {
document.getElementById("relay").textContent = text;
}
});
document.getElementById("btnOn").onclick = function () {
client.publish(TOPIC_RELAY, "ON", { retain: true });
};
document.getElementById("btnOff").onclick = function () {
client.publish(TOPIC_RELAY, "OFF", { retain: true });
};
</script>
</body>
</html>If something does not work
When the ESP32 cannot connect, the Serial Monitor prints a state number. This table tells you what it means:
| State | Meaning | What to check |
|---|---|---|
| -2 | Connection failed | Wi-Fi, host name, port 8883, and that you used a 2.4 GHz network |
| -4 | Connection timeout | Slow or blocked network. Try a mobile hotspot |
| -3 | Connection lost | Weak Wi-Fi signal or power problems |
| 4 | Bad credentials | Username or password typed wrongly |
| 5 | Not authorised | The user has no permission for that topic |
- DHT11 read failed: check the DATA pin on GPIO 4 and the 3.3 V supply, and wait two seconds after power on
- The page says Connected but shows no data: the topic in the page and the sketch must match exactly, including capital letters
- The page cannot connect: use port 8884 with
wss://, and check the website user’s password - Nothing at all on the ESP32: use a USB cable that carries data, not a charge-only cable
Turn this into your college project
What you built is more than a demo. It is the complete skeleton of an IoT project: sensors, a microcontroller, a cloud connection, a live dashboard and remote control. A college project is this same skeleton, aimed at a real problem. Here is how to use it:

How to make it truly innovative
- Step 1Choose a real problem from your college, home or village, and write it in two lines. This is your problem statement
- Step 2List the sensors and the actuators that the problem needs, and draw a block diagram of the whole system
- Step 3Build it in phasesfirst the sensor, then the cloud, then the website, then the relay
- Step 4Add smart behaviour, for example a rule such asif the temperature is above 30 degrees, switch the fan relay on automatically
- Step 5Add history, a chart of the last hours of data, and alerts when a value crosses a limit
- Step 6Add a login and a mobile-friendly page, so that it feels like a real product
- Step 7Test it, measure how it performs and write down the results with photos and screenshots
What to put in your project report
- Problem statement and objectives
- Block diagram, circuit diagram and flow chart
- Components used and why you chose each one
- Working: how data goes from the sensor to the website and back to the relay
- Results with screenshots, and the limitations of your system
- Future scope, such as more sensors, a mobile app or machine learning on the data
Questions your examiner may ask
- Why did you choose MQTT instead of HTTP?
- What happens if the Wi-Fi goes down? How does your system recover?
- What are topics, publish, subscribe and retain?
- How did you secure your system?
- How could your project be scaled to a hundred devices?
If you are looking for an idea, our Innovation project ideas page lists problem-based projects, and we can guide you from the problem statement to the viva. At Robozz Lab in Indore you build the circuit and the code yourself with a trainer beside you, so you can explain every part of it to your examiner.
Frequently asked questions
Can an ESP32 send data to a website?
Yes. The ESP32 can publish data to a cloud MQTT broker over Wi-Fi, and a web page can subscribe to the same broker and display the data live. You can also use HTTP requests to a web service.
Do I need my own server for this?
No. A cloud MQTT broker such as HiveMQ Cloud sits in the middle, and Netlify only hosts the static page, so you do not need to run a server.
Is HiveMQ Cloud free?
HiveMQ Cloud offers a free plan that is enough for learning and small projects. Free-plan limits can change, so check the HiveMQ pricing page.
Why use MQTT instead of HTTP for IoT?
MQTT is lighter, keeps a connection open and pushes data the moment it arrives. It also carries commands back to the device easily, which suits sensors and relays.
Is it safe to put the MQTT password in the website code?
Anyone can read it using View Source. Use a separate user with limited permissions for the website, and add a login and a backend for a serious product.
Can I control a relay from my phone with this?
Yes. Open your Netlify link on a phone, and the ON and OFF buttons publish commands that the ESP32 turns into relay switching.
Which ESP32 pins should I avoid?
Avoid the pins used for the flash memory (GPIO 6 to 11), and remember that GPIO 34 to 39 are input only. The pins used in this guide are safe choices.
Have a question? Message us on WhatsApp.
Talk to the Robozz Lab team directly about projects, school labs, training or internships.


