How to reload the browser window when you save a file
By Flavio Copes
Learn how to automatically reload the browser whenever you save a file in a plain HTML and JS project, by running browser-sync with npx.
The quickest way I found to reload the browser every time you save a file is browser-sync. You run a single command in your project folder, and the page refreshes on every change. No global install required.
I was working on a website in vanilla HTML + JS, and I missed one of the best features provided by those quick start packages: reloading the page when I saved a file in the code editor.
Older create-react-app / Vue CLI scaffolds did that, and so do current Vite scaffolds. In a plain HTML project, you have nothing. You edit, switch to the browser, hit reload, switch back. Dozens of times per hour. browser-sync removes that loop.
Setting up browser-sync
From the project folder, run it with npm’s npx:
npx browser-sync start --server --files "."
That downloads (or reuses) the latest browser-sync and starts it. No npm install -g needed.
If you use it often in one project, add it as a local dependency instead:
npm install --save-dev browser-sync
npx browser-sync start --server --files "."
--server starts a static web server on port 3000, serving the current folder. --files "." tells it what to watch for changes: everything in the current folder and all subfolders.
The command also opens a browser window pointing to http://localhost:3000. Any time you change a file, the browser refreshes.
Very useful while prototyping!
How does the reload work?
browser-sync injects a small script into every HTML page it serves. That script opens a WebSocket connection back to the server. When a watched file changes, the server pushes a message and the script reloads the page.
CSS gets special treatment: browser-sync injects the new styles without a full page reload, so you keep your scroll position and page state.
Watching fewer files
Watching "." is fine for a small folder. But if your project contains a node_modules folder, every change in there triggers a reload too, and startup gets slower because there are thousands of files to watch.
You can pass specific patterns instead:
npx browser-sync start --server --files "*.html, css/*.css, js/*.js"
Now only your own files trigger the refresh.
One pitfall
The injected script needs a <body> tag to hook into. If you’re testing a bare HTML fragment without a proper <body>, browser-sync can’t inject its snippet and the page never auto-reloads. Add the tag and the reload starts working.
Want me to talk about your product? You can sponsor this site.
Related posts about platform: