Ditch REST: How React + SQL + WebSockets Can Power Real-Time Apps Without the Overhead
Tired of polling? Hate Redux overload? Want snappy real-time updates without diving into Firebase lock-in? Here's a bold new way to build full-duplex apps with SQL + React + WebSockets that actually scales.
Weโve been building web apps the โRESTfulโ way for the last two decades: client requests -> server responds. While it works for a lot of CRUD-style apps, the internet is changing. Take a look at:
Polling every few seconds is a waste of resources and bad UX. You might consider Firebase, Hasura, or GraphQL subscriptions โ but what if you could get real-time capabilities with tools you already know?
Enter React + SQL + WebSockets.
We'll build a basic chat app (yes, revolutionary ๐) but the idea scales:
Before diving in, make sure youโve got:
Letโs enable PostgreSQL to notify our backend when new data comes in.
-- Create messages table
CREATE TABLE messages (
id SERIAL PRIMARY KEY,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
-- Function to notify
CREATE OR REPLACE FUNCTION notify_new_message()
RETURNS trigger AS $$
DECLARE
BEGIN
PERFORM pg_notify('new_message', row_to_json(NEW)::text);
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- Trigger
CREATE TRIGGER trigger_new_message
AFTER INSERT ON messages
FOR EACH ROW EXECUTE FUNCTION notify_new_message();
Now, every time you INSERT a message, PostgreSQL sends a NOTIFY event.
Letโs write the backend that pipes SQL NOTIFY messages to WebSocket clients.
const express = require('express');
const { Pool } = require('pg');
const WebSocket = require('ws');
const http = require('http');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
const pgPool = new Pool({
connectionString: process.env.DATABASE_URL // or use config
});
(async () => {
const client = await pgPool.connect();
await client.query('LISTEN new_message');
client.on('notification', msg => {
const payload = JSON.parse(msg.payload);
console.log('๐ฌ New message:', payload);
wss.clients.forEach(ws => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(payload));
}
});
});
})();
app.use(express.json());
app.post('/messages', async (req, res) => {
const { content } = req.body;
const { rows } = await pgPool.query(
'INSERT INTO messages (content) VALUES ($1) RETURNING *',
[content]
);
res.json(rows[0]);
});
server.listen(3001, () => console.log('๐ Server listening on port 3001'));
Now the server acts like a bridge from PostgreSQL -> WebSocket.
On the React side, we set up a WebSocket hook to connect to the backend and render messages.
import React, { useEffect, useRef, useState } from 'react';
function useWebSocketMessages(url) {
const [messages, setMessages] = useState([]);
const ws = useRef(null);
useEffect(() => {
ws.current = new WebSocket(url);
ws.current.onmessage = (e) => {
const data = JSON.parse(e.data);
setMessages((prev) => [...prev, data]);
};
return () => ws.current.close();
}, [url]);
return messages;
}
function Chat() {
const messages = useWebSocketMessages('ws://localhost:3001');
return (
<div>
<h2>Real-time Chat</h2>
<ul>
{messages.map((msg, idx) => (
<li key={idx}>{msg.content}</li>
))}
</ul>
</div>
);
}
export default Chat;
This architecture is surprisingly powerful:
This pattern isnโt limited to a chat app. You can extend it to:
Bonus: Add authentication, debounce updates, or event sourcing with PostgreSQL logical replication.
Imagine a future where:
With a small upgrade to your architecture, you can get real-time SQL in the browser โ and you didnโt even need Firebase.
REST is slow. GraphQL is heavy. WebSockets + SQL is underrated.
Try it.
๐ Resources:
๐ง If you enjoyed this article, follow the blog for deeper real-time explorations, async patterns, and minimalist web architectures that scale.
Happy hacking ๐
๐ If you need this done โ we offer fullstack-development services.
Information