How do I refresh browser from server-side with node.js?

Issue

I want to reload page when my html files are changed (while development) because of HMR bug in html-webpack-plugin and webpack-dev-middleware (webpack-hot-middleware) interop.

Here are two repositories where I got this problem, there are issues in both.


How can I reload page using this tools?

  • Node.js
  • Express
  • webpack-dev-middleware

Solution

There are a few ways to refresh a client’s browser from the server.

Server-Sent Events:

One simple method that works across browsers and servers uses server-sent events. The minimal process is:

  1. client sends a subscription request to server with EventSource():
var evtSource = new EventSource("<server_URL>/subscribe");
  1. client sets up a listener for incoming messages:
evtSource.onmessage = function () { myPageRefresh() };

On the server side, set up a handler for GET /subscribe requests and keep track of the subscribed client:

const express = require('express');
const app = express();

var client = null;

app.get('/subscribe', (req, res) => {
  // send headers to keep connection alive
  const headers = {
    'Content-Type': 'text/event-stream',
    'Connection': 'keep-alive',
    'Cache-Control': 'no-cache'
  };
  res.writeHead(200, headers);

  // send client a simple response
  res.write('you are subscribed');

  // store `res` of client to let us send events at will
  client = res;

  // listen for client 'close' requests
  req.on('close', () => { client = null; }
});

// send refresh event (must start with 'data: ')
function sendRefresh() {
  client.write('data: refresh');
}

Now the server can send a refresh event at any time by simply calling sendRefresh().

lite-server:

If you are running the server locally on your development computer, refreshing the browser is trivially easy. lite-server is a module that will refresh the browser whenever it detects a change to source files. It’s very handy.

Answered By – terrymorse

Answer Checked By – Dawn Plyler (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.