# Building an ESP32 IoT Sensor Dashboard with MQTT and Next.js
Combining embedded hardware with a modern web frontend is one of the most satisfying projects you can build. Here's how I wired up an ESP32 temperature/humidity sensor to a live Next.js dashboard.
## Hardware
- ESP32 DevKit v1
- DHT22 temperature and humidity sensor
- Jumper wires
## ESP32 Firmware (Arduino IDE)
```cpp
#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
#define DHTPIN 4
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
WiFiClient espClient;
PubSubClient client(espClient);
void loop() {
float temp = dht.readTemperature();
float hum = dht.readHumidity();
String payload = "{\"temp\":" + String(temp) + ",\"hum\":" + String(hum) + "}";
client.publish("sensors/room1", payload.c_str());
delay(5000);
}
```
## MQTT Broker
I used HiveMQ Cloud (free tier). It gives you a WebSocket endpoint you can connect to directly from the browser — no backend needed for reading.
## Next.js Frontend
Install mqtt:
```bash
npm install mqtt
```
```tsx
'use client';
import mqtt from 'mqtt';
import { useEffect, useState } from 'react';
export default function Dashboard() {
const [data, setData] = useState({ temp: 0, hum: 0 });
useEffect(() => {
const client = mqtt.connect('wss://your-broker.hivemq.cloud:8884/mqtt', {
username: 'user',
password: 'pass',
});
client.on('connect', () => client.subscribe('sensors/room1'));
client.on('message', (_, msg) => setData(JSON.parse(msg.toString())));
return () => { client.end(); };
}, []);
return (
<div>
<p>Temperature: {data.temp}°C</p>
<p>Humidity: {data.hum}%</p>
</div>
);
}
```
## Result
Real-time updates every 5 seconds with no polling. The ESP32 runs on battery for days with deep sleep between publishes.
