Yes, you can achieve this using Server-Sent Events (SSE). Here's a simple way to trigger a page refresh from the server side in a Node.js HTTP server:
Step 1: Server-Side Code (Node.js)
const http = require('http');
let sseResponse = null; // Store the SSE connection
const server = http.createServer((req, res) => {
if (req.url === '/events') {
// Handle SSE connection
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
sseResponse = res;
} else {
// Serve the main HTML page
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`
<html>
<body>
<h1>Page Content</h1>
<script>
// Client-side code to listen for the refresh event
const eventSource = new EventSource('/events');
eventSource.addEventListener('refresh', (event) => {
location.reload();
});
</script>
</body>
</html>
`);
}
});
// Function to trigger a refresh from the server
function triggerRefresh() {
if (sseResponse) {
// Send the "refresh" event via SSE
sseResponse.write('event: refresh\n\n');
}
}
// Example: Trigger a refresh after 5 seconds
setTimeout(triggerRefresh, 5000);
server.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
Step 2: How It Works
- SSE Endpoint: The server creates an
/events endpoint for Server-Sent Events.
- Client Connection: The HTML page automatically connects to
/events via JavaScript.
- Server Sends Event: When you call
triggerRefresh(), the server sends an event: refresh message to the client.
- Client Refreshes: The client detects the
refresh event and triggers a page reload.
Usage
- Run the server:
node server.js.
- Open
http://localhost:3000 in your browser.
- The page will refresh automatically after 5 seconds (or whenever
triggerRefresh() is called).
Notes
- No Dependencies: Uses only Node.js's built-in
http module.
- Single Client: Works best for a single client (like local development). For multiple clients, track all active connections in an array.
- SSE Limitations: The connection must stay open. If the page is closed, reconnect manually.
This is the simplest way to trigger a refresh from the server side without extra libraries!