Enable CORS in BrowserSync

BrowserSync is a great tool for front end development. On a recent project, I ran into a situation where I needed to enable CORS within BrowserSync as we were serving some files from different hosts and ran into cross domain issues.

Getting CORS enabled involves setting some headers in BrowserSync’s middleware.

gulp.task('browser-sync', function () {
    notify: false,
    port: 6543,
    server: {
      baseDir: config.dest,
      middleware: function (req, res, next) {
        res.setHeader('Access-Control-Allow-Origin', '*');

For this project, we’re using Gulp. In the BrowserSync configuration, I’m setting the Access-Control-Allow-Origin header in the response. You can set the * to any domain you might want to allow.

There was an error submitting your subscription. Please try again.
Get my latest posts and links about development and moonlighting delivered every Sunday at 8pm.