The thoughts of Matthew Crist, a designer in Boston.

Feb 14, 2015

How-to: 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 () {
  browserSync({
    notify: false,
    port: 6543,
    server: {
      baseDir: config.dest,
      middleware: function (req, res, next) {
        res.setHeader('Access-Control-Allow-Origin', '*');
        next();
      }
    }
  });
});

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.