Browser-sync can operate in two primary modes: as a static file server for serving files directly, or as a proxy server that sits in front of your existing application server. Both modes support middleware, custom routing, and HTTPS configuration.
Run browser-sync as a static file server with configurable base directories, index files, and routing.
interface ServerConfig {
/** Base directory or directories to serve files from */
baseDir: string | string[];
/** Index file name (default: "index.html") */
index?: string;
/** Enable directory browsing when no index file found */
directory?: boolean;
/** Custom route mappings */
routes?: { [route: string]: string };
/** Server middleware functions */
middleware?: Function | Function[] | MiddlewareConfig | MiddlewareConfig[];
/** Options passed to serve-static */
serveStaticOptions?: any;
}
interface MiddlewareConfig {
/** Route pattern for middleware */
route: string;
/** Optional middleware identifier */
id?: string;
/** Middleware function */
handle: Function;
}Usage Examples:
const browserSync = require('browser-sync');
// Basic static server
browserSync({
server: './dist'
});
// Multiple base directories
browserSync({
server: {
baseDir: ['./app', './temp'],
index: 'index.html'
}
});
// Custom routes
browserSync({
server: {
baseDir: './app',
routes: {
'/node_modules': './node_modules',
'/vendor': './bower_components'
}
}
});
// With middleware
browserSync({
server: {
baseDir: './app',
middleware: [
// Log all requests
function(req, res, next) {
console.log(`${req.method} ${req.url}`);
next();
},
// API mock
{
route: '/api',
handle: function(req, res, next) {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ status: 'ok' }));
}
}
]
}
});Use browser-sync as a proxy to your existing application server with websocket support and request/response modification.
interface ProxyConfig {
/** Target server URL to proxy */
target: string;
/** Enable websocket proxying */
ws?: boolean;
/** Proxy middleware functions */
middleware?: Function | Function[] | MiddlewareConfig | MiddlewareConfig[];
/** Request header modifications */
reqHeaders?: Function;
/** Proxy request transformations */
proxyReq?: Function[];
/** Proxy response transformations */
proxyRes?: Function[];
}Usage Examples:
const browserSync = require('browser-sync');
// Basic proxy
browserSync({
proxy: 'localhost:3000'
});
// Advanced proxy configuration
browserSync({
proxy: {
target: 'localhost:8080',
ws: true, // Enable websocket proxying
middleware: [
// Add custom headers
function(req, res, next) {
res.setHeader('X-Proxied-By', 'BrowserSync');
next();
}
]
}
});
// Proxy with HTTPS target
browserSync({
proxy: {
target: 'https://localhost:3443',
ws: true
},
// Override HTTPS for browser-sync server
https: false
});Serve additional static directories alongside your main server or proxy configuration.
/**
* Additional static file directories to serve
*/
serveStatic?: Array<{
route: string;
dir: string | string[];
}>;Usage Examples:
const browserSync = require('browser-sync');
// Server mode with additional static directories
browserSync({
server: './app',
serveStatic: [
{
route: '/assets',
dir: './build/assets'
},
{
route: '/docs',
dir: ['./documentation', './api-docs']
}
]
});
// Proxy mode with static assets
browserSync({
proxy: 'localhost:3000',
serveStatic: [
{
route: '/static',
dir: './public'
}
]
});Enable HTTPS for local development with custom certificates or auto-generated certificates.
interface HttpsConfig {
/** Path to SSL key file */
key?: string;
/** Path to SSL certificate file */
cert?: string;
/** Path to SSL certificate authority file */
ca?: string;
/** Passphrase for SSL key */
passphrase?: string;
}Usage Examples:
const browserSync = require('browser-sync');
// Auto-generated HTTPS certificates
browserSync({
server: './app',
https: true
});
// Custom SSL certificates
browserSync({
server: './app',
https: {
key: './ssl/server.key',
cert: './ssl/server.crt'
}
});
// HTTPS proxy
browserSync({
proxy: 'localhost:3000',
https: {
key: './certs/localhost-key.pem',
cert: './certs/localhost.pem'
}
});Configure host, port, and network binding options for the browser-sync server.
interface NetworkConfig {
/** Server port (default: 3000) */
port?: number;
/** Host to bind to */
host?: string;
/** Specific hostname to bind to (overrides host) */
listen?: string;
/** Use HTTP/2 module */
httpModule?: string;
}Usage Examples:
const browserSync = require('browser-sync');
// Custom port
browserSync({
server: './app',
port: 8080
});
// Bind to specific host
browserSync({
server: './app',
host: '0.0.0.0', // Allow external connections
port: 3000
});
// Use specific hostname
browserSync({
proxy: 'localhost:8000',
listen: 'dev.local'
});
// HTTP/2 support
browserSync({
server: './app',
https: true,
httpModule: 'http2'
});Custom middleware functions for request processing, authentication, API mocking, and more.
/**
* Middleware function signature
* @param req - HTTP request object
* @param res - HTTP response object
* @param next - Next middleware function
*/
type MiddlewareFunction = (req: any, res: any, next: Function) => void;Usage Examples:
const browserSync = require('browser-sync');
const compression = require('compression');
const history = require('connect-history-api-fallback');
browserSync({
server: './dist',
middleware: [
// Gzip compression
compression(),
// SPA fallback routing
history({
rewrites: [
{ from: /^\/api\/.*$/, to: function(context) {
return context.parsedUrl.pathname;
}}
]
}),
// Custom API routes
{
route: '/api/users',
handle: function(req, res, next) {
if (req.method === 'GET') {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify([
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' }
]));
} else {
next();
}
}
},
// Request logging
function(req, res, next) {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next();
}
]
});Enable Cross-Origin Resource Sharing (CORS) headers for API development and testing.
/**
* Enable CORS headers (default: false)
*/
cors?: boolean;Usage Examples:
const browserSync = require('browser-sync');
// Enable CORS for API development
browserSync({
server: './app',
cors: true,
middleware: [
{
route: '/api',
handle: function(req, res, next) {
// Additional CORS headers if needed
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (req.method === 'OPTIONS') {
res.end();
return;
}
next();
}
}
]
});