3. Auto Refresh
You can auto-refresh the browser when your server-side code changes in Express.js or Node.js — There are two approaches.
1. BrowserSync
You’ll use:
nodemon
– watches server files and restarts the serverbrowser-sync
– acts as a proxy and auto-refreshes the browserconcurrently
– runs both at once
1.1 🔧 Install Required Packages
npm install --save-dev nodemon browser-sync concurrently
1.2 🗂 Fix the Directory Structure
project/├── public/│ └── index.html├── app.js├── bs-config.js├── package.json
1.2 📄 Your Express App
const express = require('express');const path = require('path');const app = express();
// [Optional] Serve static files from public directoryapp.use(express.static('public'));
app.get('/', (req, res) => { res.sendFile(path.join(__dirname, 'public/index.html'));});
app.listen(3001, () => { console.log('Server is running on http://localhost:3001');});
1.3 ⚙️ BrowserSync Config
module.exports = { proxy: "http://localhost:3001", // proxy Your Express server port: 3000, // BrowserSync UI port, BrowserSync serves here files: ["public/**/*.*", "index.js"], // Watch public + backend files reloadDelay: 500 // Wait a bit for nodemon to restart};
1.4 📝 Update package.json
Scripts
"scripts": { "dev": "nodemon app.js", "sync": "browser-sync start --config bs-config.js", "start": "concurrently \"npm:dev\" \"npm:sync\""}
1.5 ▶️ Run the Server + Auto Reload
npm start
- Visit http://localhost:3000
- Change any file in
public/
orapp.js
- Browser auto-refreshes
- Server auto-restarts
1.6 🔧 Serving EJS with BrowserSync
EJS is rendered server-side, not just static HTML. So to use BrowserSync effectively with EJS, you need to set it up to proxy your Express server — just like you would for any dynamic backend.
const express = require('express');const path = require('path');const app = express();
app.set('view engine', 'ejs');app.set('views', path.join(__dirname, 'views'));
app.get('/', (req, res) => { res.render('index', { title: "BrowserSync with EJS" });});
app.listen(3001, () => { console.log("Express server on http://localhost:3001");});
module.exports = { proxy: "http://localhost:3001", // proxy your Express server port: 3000, // BrowserSync serves here files: [ "views/**/*.ejs", // watch for EJS changes "index.js", // backend files "public/**/*.*" // and any public files ], reloadDelay: 500};
Key Takeaways
- Edit
.ejs
files → browser reloads automatically - Express server is proxied through BrowserSync
- Live reload works even with server-rendered views
1.7 How does BrowserSync Proxy Work?
Content coming soon
2. Live Reload Method
Content coming soon