Raspberry Pi Web Server with WebSocket

Below is a complete and easy-to-follow guide on building a Raspberry Pi Web Server with WebSocket using Node.js. This lets you control GPIO pins or read sensor data in real-time through a browser.


🚀 Node.js + Raspberry Pi WebServer with WebSocket

This project will create:

✔ A Node.js backend running on Raspberry Pi
✔ A WebSocket server (using ws)
✔ A webpage that updates instantly without refreshing
✔ Real-time communication with GPIO (LED ON/OFF or sensor reading)


1. Install Required Packages

Install Node.js on Raspberry Pi

sudo apt update
sudo apt install nodejs npm -y

Create project folder

mkdir pi-websocket
cd pi-websocket

Install dependencies

npm install express ws onoff
  • express → web server

  • ws → WebSocket server

  • onoff → GPIO control


2. Create server.js

This program:

  • Starts an Express server

  • Hosts an HTML webpage

  • Creates a WebSocket server

  • Toggles GPIO (LED on GPIO 17)

  • Sends messages to the client in real-time

Create the file:

nano server.js

Paste this code:


 

Save & exit: CTRL + X → Y → Enter


3. Create Simple Webpage (index.html)

nano index.html

Paste:


 

Save & exit.


🔥 4. Start the WebSocket Webserver

node server.js

Output:

Server running at http://localhost:3000

🌐 5. Open in Browser

On any device in your network:

👉 http://<YOUR-RPI-IP>:3000

Example:

http://192.168.1.25:3000

You will see:

  • LED ON button

  • LED OFF button

  • Status updates instantly (WebSocket)


💡 6. Wiring the LED

Use GPIO17 (Pin 11) → LED → 330Ω resistor → GND

GPIO17 (Pin 11) ---- LED ---- 330Ω ---- GND

🚀 Bonus Upgrade Ideas

You can extend this project to:

✅ Real-time sensor dashboard (DHT11 / MQ135 / Ultrasonic)
✅ Live camera feed + WebSocket events
✅ Smart Home dashboard
✅ IoT home automation system
✅ Multiple GPIO controls
✅ Raspberry Pi robot controller

You may also like...