Browsersync options

These are all the options that you can configure when using Browsersync. Create a single object and pass it as the first argument (for GulpJS and normal API usage). If you're using Grunt, you can still use all of these options, but you need to provide them as detailed in the Browsersync Grunt Documentation

  • Type: Object

Note: requires at least version 2.0.0

Browsersync includes a user-interface that is accessed via a separate port. The UI allows to controls all devices, push sync updates and much more.

// Change the default port
ui: {
    port: 8080
}

// Change the default weinre port
ui: {
    port: 8080,
    weinre: {
        port: 9090
    }
}

// Disable UI completely
ui: false
  • Type: Array | String
  • Default: false

Browsersync can watch your files as you work. Changes you make will either be injected into the page (CSS & images) or will cause all browsers to do a full-page refresh.

// single file
browserSync({
    files: "app/css/style.css"
});

// multiple files
browserSync({
    files: ["app/css/style.css", "app/js/*.js"]
});

// patterns + 1 with custom callback
// since 2.6.0
browserSync({
    files: [
        "wp-content/themes/**/*.css",
        {
            match: ["wp-content/themes/**/*.php"],
            fn:    function (event, file) {
                /** Custom event handler **/
            }
        }
    ]
});
  • Type: Array
  • Default: ["change"]

Note: requires at least version 2.18.8

Specify which file events to respond to. Available events: add, change, unlink, addDir, unlinkDir

  • Type: Boolean
  • Default: false

Note: requires at least version 2.23.0

Watch files automatically - this should be used as an alternative to the files option. When this option is used, some directories will be ignored automatically such as node_modules bower_components .sass-cache .vscode .git .idea

var browserSync = require("browser-sync").create();

/**
 * This example will serve files from the './app' directory
 * and will automatically watch for html/css/js changes
 */
browserSync.init({
    watch: true,
    server: "./app"
});
  • Type: Array
  • Default: []

Note: requires at least version 2.23.0

Patterns for any watchers to ignore. Anything provided here will end up inside watchOptions.ignored

  • Type: Boolean
  • Default: false

Note: requires at least version 2.23.0

Serve an index.html file for all non-asset routes. Useful when using client-routers

  • Type: Object
  • Default: undefined

Note: requires at least version 2.6.0

File watching options that get passed along to Chokidar. Check their docs for available options

const bs = require('browser-sync').create();

// Options passed to Chokidar
bs.init({
    watchOptions: {
        ignoreInitial: true,
        ignored: '*.txt'
    },
    files: ['./app']
});

// options for chokidar with custom callback
// since 2.6.0
bs.init({
    files: [
        {
            match: ["wp-content/themes/**/*.php"],
            fn: function (event, file) {
                /** Custom event handler **/
            },
            options: {
                ignored: '*.txt'
            }
        }
    ]
});

// NOTE: the .watch() method will not receive
// these options automatically, so you must provide
// them manually in the following way
bs.watch(['app/*.css'], {ignored: '*.map.css'});
  • Type: Object | Boolean
  • Default: false

Use the built-in static server for basic HTML/JS/CSS websites.

// Serve files from the app directory
server: "app"

// Serve files from the current directory
server: true

// Serve files from the app directory with directory listing
server: {
    baseDir: "app",
    directory: true
}

// Multiple base directories
server: ["app", "dist"]

// Serve files from the app directory, with a specific index filename
server: {
    baseDir: "app",
    index: "index.htm"
}

// The static file server is based on expressjs/serve-static, 
// so we inherit all of their options, like trying a default extension
// when one isn't specified
// https://github.com/expressjs/serve-static
server: {
    baseDir: "app",
    serveStaticOptions: {
        extensions: ["html"]
    }
}

// Since version 1.2.1
// The key is the url to match
// The value is which folder to serve (relative to your current working directory)
server: {
    baseDir: "app",
    routes: {
        "/bower_components": "bower_components"
    }
}
  • Type: String | Object | Boolean

Proxy an EXISTING vhost. Browsersync will wrap your vhost with a proxy URL to view your site.

// Using a vhost-based url
proxy: "local.dev"

// Using a localhost address with a port
proxy: "localhost:8888"

// Using localhost sub directories
proxy: "localhost/site1"

// When your app also uses web sockets
// NOTE: requires 2.8.1 or above
proxy: {
    target: "http://yourlocal.dev",
    ws: true
}

proxy: {
    target: "http://yourlocal.dev",
}

// Modify the server request before it hits your application
// NOTE: requires v2.12.1
proxy: {
    target: "http://yourlocal.dev",
    proxyReq: [
        function(proxyReq) {
            proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
        }
    ]
}

// Modify the server response after it's returned from the proxy
proxy: {
    target: "http://yourlocal.dev",
    proxyRes: [
        function(proxyRes, req, res) {
            console.log(proxyRes.headers);
        }
    ]
}
  • Type: Number
  • Default: 3000
// Use a specific port (instead of the one auto-detected by Browsersync)
port: 8080
  • Type: Function | Array
  • Default: false
// Multiple Global Middlewares
middleware: [
    function (req, res, next) {
        /** First middleware handler **/
    },
    function (req, res, next) {
        /** Second middleware handler **/
    }
]

// Per-route middleware
// NOTE: requires v2.12.1
middleware: [
    {
        route: "/api",
        handle: function (req, res, next) {
            // handle any requests at /api
        }
    }
]

// Per-route + global middleware
// NOTE: requires v2.12.1
middleware: [
    require("compression")(), // global
    {
        route: "/api", // per-route
        handle: function (req, res, next) {
            // handle any requests at /api
        }
    }
]
  • Type: Array
  • Default: []

Note: requires at least version 2.8.0

Add additional directories from which static files should be served. Should only be used in proxy or snippet mode.

var bs = require('browser-sync').create();

// Run in proxy mode with static files also served
// from current directory + ./app/css
bs.init({
    proxy: "http://www.bbc.co.uk",
    serveStatic: ['.', './app/css']
});

// Run in proxy mode where files under /assets will be served
// from a local ./tmp directory
// NOTE: requires 2.17.0
bs.init({
    proxy: "http://www.bbc.co.uk",
    serveStatic: [{
        route: '/assets',
        dir: 'tmp'
    }]
});

// Run in proxy mode where files under /assets + /content will be served
// from a local ./tmp directory
// NOTE: requires 2.17.0
bs.init({
    proxy: "http://www.bbc.co.uk",
    serveStatic: [{
        route: ['/assets', '/content'],
        dir: 'tmp'
    }]
});

// Run in proxy mode where files under /assets will be served
// from either the ./tmp or ./app directory
// NOTE: requires 2.17.0
bs.init({
    proxy: "http://www.bbc.co.uk",
    serveStatic: [{
        route: '/assets',
        dir: ['./tmp', './app']
    }]
});
  • Type: Object
  • Default:

Note: requires at least version 2.17.0

Options that are passed to the serve-static middleware when you use the string[] syntax: eg: serveStatic: ['./app']. Please see serve-static for details

var bs = require('browser-sync').create();

// Serve files from 3 directories with serve-static options
bs.init({
    serveStatic: ['.', './app', './temp'],
    serveStaticOptions: {
        extensions: ['html'] // pretty urls
    }
});
  • Type: Boolean
  • Default: undefined

Note: requires at least version 1.3.0

Enable https for localhost development. Note - this is not needed for proxy option as it will be inferred from your target url.

// Enable HTTPS for static file server
browserSync({
    server: "./app",
    https: true
});

// Enable HTTPS for snippet mode
browserSync({
    https: true
});

// Enable HTTPS mode with custom certificates
browserSync({
    server: "./app",
    https: {
        key: "path-to-custom.key",
        cert: "path-to-custom.crt"
    }
});
  • Type: string
  • Default: undefined

Note: requires at least version 2.18.0

Override http module to allow using 3rd party server modules (such as http2) Note: these modules are not included in the Browsersync package - you need to 'npm install' any that you'd like to use.

// First run: npm install browser-sync http2
const bs = require('browser-sync').create();

bs.init({
    server: './app',
    httpModule: 'http2',
    https: true
});
  • Type: String
  • Default:

Note: requires at least version 2.23.0

Current working directory

  • Type: Object

Register callbacks via a regular option - this can be used to get access the Browsersync instance in situations where you cannot provide a callback via the normal API (for example, in a Gruntfile)

Note: Only the ready callback is currently supported here.

var browserSync = require("browser-sync").create();

browserSync.init({
    watch: true,
    server: "./app",
    callbacks: {
        /**
         * This 'ready' callback can be used
         * to access the Browsersync instance
         */
        ready: function(err, bs) {

            // example of accessing URLS
            console.log(bs.options.get('urls'));

            // example of adding a middleware at the end
            // of the stack after Browsersync is running
            bs.addMiddleware("*", function (req, res) {
                res.writeHead(302, {
                    location: "404.html"
                });
                res.end("Redirecting!");
            });
        }
    }
});
  • Type: Object

Clicks, Scrolls & Form inputs on any device will be mirrored to all others.

// Here you can disable/enable each feature individually
ghostMode: {
    clicks: true,
    forms: true,
    scroll: false
}

// Or switch them all off in one go
ghostMode: false
  • Type: String
  • Default: info

Can be either "info", "debug", "warn", or "silent"

// Show me additional info about the process
logLevel: "debug"

// Just show basic info
logLevel: "info"

// output NOTHING to the commandline
logLevel: "silent"
  • Type: String
  • Default: Browsersync

Note: requires at least version 1.5.1

Change the console logging prefix. Useful if you're creating your own project based on Browsersync

logPrefix: "My Awesome Project"

// [My Awesome Project] Local URL: http://localhost:3000
// [My Awesome Project] Watching files....
// [My Awesome Project] File changed: "index.html"
  • Type: Boolean
  • Default: false
// Log connections
logConnections: true

// Don't log connections
logConnections: false
  • Type: Boolean
  • Default: true
// Log information about changed files
logFileChanges: true

// Don't log file changes
logFileChanges: false
  • Type: : Boolean
  • Default: true

Note: requires at least version 1.5.2

Log the snippet to the console when you're in snippet mode (no proxy/server)

// Don't ever log the snippet
logSnippet: false
  • Type: Boolean
  • Default: undefined

You can prevent Browsersync from injecting the connection snippet by passing snippet: false.

// CLI
browser-sync ./app -w --no-snippet

// API
const bs = require('browser-sync').create();
bs.init({
    watch: true,
    server: "./app",
    snippet: false
})
  • Type: Object

Note: requires at least version 2.0.0

You can control how the snippet is injected onto each page via a custom regex + function. You can also provide patterns for certain urls that should be ignored from the snippet injection.

// Customise the placement of the snippet
// and ignore certain paths
snippetOptions: {

    // Ignore all HTML files within the templates folder
    ignorePaths: "templates/*.html",

    // Provide a custom Regex for inserting the snippet.
    rule: {
        match: /<\/body>/i,
        fn: function (snippet, match) {
            return snippet + match;
        }
    }
}
  • Type: Array
  • Default: false

Note: requires at least version 2.4.0

Add additional HTML rewriting rules.

// Replace every occurrence of the word Browsersync with 'kittenz'
rewriteRules: [
    {
        match: /Browsersync/g,
        fn: function (req, res, match) {
            return 'kittenz';
        }
    }
]

// Also accepts a string as a replacement
rewriteRules: [
    {
        match: /(cats|kitten[sz]) are mediocre/g,
        replace: "$1 are excellent"
    }
]
  • Type: String | Boolean
  • Default: null
// Tunnel the Browsersync server through a random Public URL
// -> http://randomstring23232.localtunnel.me
tunnel: true

// Attempt to use the URL "http://my-private-site.localtunnel.me"
tunnel: "my-private-site"
  • Type: Boolean
  • Default: undefined

Some features of Browsersync (such as xip & tunnel) require an internet connection, but if you're working offline, you can reduce start-up time by setting this option to false

// Will not attempt to determine your network status, assumes you're ONLINE.
online: true

// Will not attempt to determine your network status, assumes you're OFFLINE
online: false
  • Type: Boolean | String
  • Default: true

Decide which URL to open automatically when Browsersync starts. Defaults to "local" if none set. Can be true, local, external, ui, ui-external, tunnel or false

// Stop the browser from automatically opening
open: false

// Open the localhost URL
open: "local"

// Open the external URL - must be online.
open: "external"

// Open the UI - since 2.0.0
open: "ui"

// Open the tunnel URL - must also set the `tunnel` option
open: "tunnel"
  • Type: String | Array
  • Default: default
// Open the site in Chrome
browser: "google chrome"

// Open the site in Chrome & Firefox
browser: ["google chrome", "firefox"]
  • Type: boolean
  • Default: false

Note: requires at least version 2.16.0

Add HTTP access control (CORS) headers to assets served by Browsersync.

  • Type: Boolean
  • Default: false

Requires an internet connection - useful for services such as Typekit as it allows you to configure domains such as *.xip.io in your kit settings

// Append '.xip.io' to the hostname. (eg: http://192.168.0.4.xip.io:3002)
xip: true
  • Type: Boolean
  • Default: false

Reload each browser when Browsersync is restarted.

// don't auto-reload all browsers following a Browsersync reload
reloadOnRestart: false
  • Type: Boolean
  • Default: true

The small pop-over notifications in the browser are not always needed/wanted.

// Don't show any notifications in the browser.
notify: false
  • Type: Boolean
  • Default: true
scrollProportionally: false // Sync viewports to TOP position
  • Type: Number
  • Default: 0
scrollThrottle: 100 // only send scroll events every 100 milliseconds
  • Type: String
  • Default: 'window.name'

Decide which technique should be used to restore scroll position following a reload. Can be window.name or cookie

  • Type: Array
  • Default: []

Note: requires at least version 2.9.0

Sync the scroll position of any element on the page. Add any amount of CSS selectors

// Sync the scrollTop position of the element .scroller
// in addition to the window scroll
scrollElements: ['.scroller']
  • Type: Array
  • Default: []

Note: requires at least version 2.9.0

Sync the scroll position of any element on the page - where any scrolled element will cause all others to match scroll position. This is helpful when a breakpoint alters which element is actually scrolling

// Sync the scrollTop position between different elements
// useful if your scroll container changes based on a breakpoint
scrollElementMapping: ['.scroller-mobile', '.scroller']
  • Type: Number
  • Default: 0

Time, in milliseconds, to wait before instructing the browser to reload/inject following a file change event

// Wait for 2 seconds before any browsers should try to inject/reload a file.
reloadDelay: 2000
  • Type: Number
  • Default: 0

Note: requires at least version 2.6.0

Wait for a specified window of event-silence before sending any reload events.

// Wait 2 seconds after a reload event before allowing more.
reloadDebounce: 2000
  • Type: Number
  • Default: 0

Note: requires at least version 2.13.0

Emit only the first event during sequential time windows of a specified duration.

  • Type: Array
  • Default: []

Note: requires at least version 2.6.0

User provided plugins

// First run `npm install bs-html-injector`
// Then provide the module name
plugins: ["bs-html-injector"]

// If the plugin you are using requires options
// just as bs-snippet-injector requires a 'file' option,
// you can pass an object instead like this.
plugins: [
    {
        module: "bs-snippet-injector",
        options: {
            file: "./app/index.php"
        }
    }
]

// Shorthand for bs-html-injector + files: ["*.html"] option
// NOTE: requires v2.12.1
plugins: ["bs-html-injector?files[]=*.html"]
  • Type: Boolean
  • Default: true
// Inject CSS changes
injectChanges: true,

// Don't try to inject, just do a page refresh
injectChanges: false,
  • Type: String | Null
  • Default: null
// Open the first browser window at URL + "/info.php"
startPath: "/info.php"
  • Type: Boolean
  • Default: true

Whether to minify client script, or not.

// Don't minify the client-side JS
minify: false
  • Type: String
  • Default: null
// Override host detection if you know the correct IP to use
host: "192.168.1.1"
  • Type: String
  • Default: undefined

Specify a host to listen on. Use this if you want to prevent binding to all interfaces.

Note: When you specify this option, it overrides the 'host' option

  • Type: Boolean
  • Default: false

Note: requires at least version 2.14.0

Support environments where dynamic hostnames are not required (ie: electron)

// For use in electron development
const bs = require('browser-sync');
bs.init({
    localOnly: true
});
  • Type: Boolean
  • Default: true
// Don't send any file-change events to browsers
codeSync: false
  • Type: Boolean
  • Default: true
// Don't append timestamps to injected files
timestamps: false
  • Type: Function
  • Default: undefined

Note: requires at least version 1.5.0

Alter the script path for complete control over where the Browsersync Javascript is served from. Whatever you return from this function will be used as the script path.

// This will result in something like
// http://localhost:3002/browser-sync/browser-sync-client.1.6.0.js
scriptPath: function (path, port, options) {
    return options.getIn(['urls', 'local']) + path;
}
  • Type: Object

Note: requires at least version 1.6.2

Configure the Socket.IO path and namespace & domain to avoid collisions.

// To change the namespace used by Browsersync
socket: {
    namespace: '/someothername'
}

// By default, Browsersync is configured to use the domain
// of your page in order to connect to socket.io
// eg: location.host + '/browser-sync
// but, should you need to change that, provide the `domain` property
socket: {
    domain: 'localhost:3000'
}
  • Type: Object

Note: requires at least version 2.14.0

Configure the script domain