Browser-sync: Change default url from localhost:port to mydomainname:port

Created on 27 May 2015  路  32Comments  路  Source: BrowserSync/browser-sync

I'm using a Vagrant VM which servers my project on a specific domain name (not locahost)
what's the easiest way to get BrowserSync working? Also, the examples a bit confusing, how do I add the browsersync task to my global watch task? Can't I have both?
(I use Gulp)

Most helpful comment

@itjustwerks if you have custom domain locally like that ( project.dev ) and need to open ( project.dev:port ) when launching the browser you can do that :

gulp.task('browserSync', function() {
      browserSync.init({
          open: 'external',
          host: 'project.dev',
          proxy: 'project.dev', // or project.dev/app/
          port: 3000
    });
});

this worked fine with me which i created this custom .dev domain depend on ( Anvil )

All 32 comments

if the IP address used to access your website running via vagrant was http://192.12.344.45:3000 then this should work.

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

bs.init({
    proxy: 'http://192.12.344.45:3000'
});

RE: your second question about gulp - not sure exactly what you mean... something like

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

gulp.task('watch', function () {

    bs.init({
        proxy: 'http://192.12.344.45:3000'
    });

    gulp.watch('app/scss/*.scss', ['sass']);
    gulp.watch('app/**/*.html').on('change', bs.reload);
});

closing as this is a question rather than an issue, feel to continue the conversation here though :)

@shakyShane Thanks for the quick reply, but I can't get it to work.

This is my gulp file (only the part related to browser sync):

gulp.task('browser-sync', function() {
    browserSync.init({
        proxy: 'http://corporate.fp:3000'
    });
});

running gulp:

16:53 $ gulp browser-sync
[16:53:06] Using gulpfile ~/Development/vagrant-dev/data/corporate/gulpfile.js
[16:53:06] Starting 'browser-sync'...
[16:53:06] Finished 'browser-sync' after 7.53 ms
[BS] Proxying: http://corporate.fp:3000
[BS] Access URLs:
 -------------------------------------
       Local: http://localhost:3000
    External: http://172.28.128.1:3000
 -------------------------------------
          UI: http://localhost:3001
 UI External: http://172.28.128.1:3001
 -------------------------------------

I visit http://corporate.fp:3000 , I get not found. I visit http://corporate.fp , no browser refresh..

Do I need .init? In this recipe, it's not used: https://github.com/Browsersync/recipes/tree/master/recipes/gulp.sass

You need to visit http://localhost:3000

@gkatsanos were you able to get it working? I notice that, unfortunately, none of the other suggestions in here work for me either.

Sorry for the spam, but to simplify what is being ask in here (at least from my perspective) is that instead of getting this:

[BS] Access URLs:
-------------------------------------
Local: http://localhost:3000
External: http://172.28.128.1:3000
-------------------------------------
UI: http://localhost:3001
UI External: http://172.28.128.1:3001
-------------------------------------

We can get this other output:

[BS] Access URLs:
-------------------------------------
Local: http://something.localhost.com:3000
External: http://172.28.128.1:3000
-------------------------------------
UI: http://something.localhost.com:3001
UI External: http://172.28.128.1:3001
-------------------------------------

I did notice that we can use attribute "port" to change 3000 into whatever other number.
However, I was unable to change "localhost" into some other string like "something.localhost.com"

+1 ... I'd like this too. Have an app with a REST service that has CORS "Allow Origin" header set to a specific domain. I'd like to be able to dev locally with a HOSTS entry to point that domain to my local code. Allowing "localhost" in CORS doesn't sit right with me. The HOSTS entry does work to connect with BrowserSync, but I'd like to have that URL open automatically instead of the localhost:port.

@itjustwerks if you have custom domain locally like that ( project.dev ) and need to open ( project.dev:port ) when launching the browser you can do that :

gulp.task('browserSync', function() {
      browserSync.init({
          open: 'external',
          host: 'project.dev',
          proxy: 'project.dev', // or project.dev/app/
          port: 3000
    });
});

this worked fine with me which i created this custom .dev domain depend on ( Anvil )

Using External doesn't work unfortunately. From searching around this seems like a common problem and definitely something worth taking a look at. Changing the proxied domain to be 'localhost:8000' can result in security/path issues as the domain no longer matches. Ideally you should be able to proxy something like "example.dev:8080" and it still uses the "example.dev:8080" domain name.

Live Reload seems to support this, but I really don't want to have to switch back as I much prefer BrowserSync.

I'm also running into this issue. Shame this issue remains closed. :disappointed:

If anyone here needs to access their original domain whilst using Browsersync, just omit the proxy option and use the snippet that will be given on the command line

+1 same problem here trying to set this up for CORS reasons. It's a pity this issue is closed.

re: the options posted by @mohamdio, I'm using those with Grunt and it's working great

                options: {
                    watchTask: true,
                    open: 'external',
                    host: 'example.dev',
                    proxy: "example.dev",
                    port: 3000,
                }

For Mamp, the below settings work:

Default Apache port: 80

open: 'external',
host: 'domain.dev',
proxy: "domain.dev",
port: 8080,

just as a note, I had a similar issue. hoping this helps someone. my setup is that there is a vagrant vm with nginx that everything goes through locally. so the dev url is something to the tune of http://www.[something].dev.

I wanted browsersync to stay at localhost and request from localhost, while setting CORS headers. I didn't want it to touch the dev domain at all.

I wrote a small script to do it:

var bs = require("browser-sync").create()

bs.init({
  ui: false,
  port: 8989,
  files: 'build/account/public/style/*.css',
  reloadDebounce: 1000,
  host: 'localhost',
  socket: {
    domain: 'localhost:8989'
  },
  middleware: function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*')
    next()
  }
})

I'm using the technique @alexanderlperez and @mohamdio suggested and I'm able to use my local secure domain with grunt.

options: {
open: 'external',
host: 'mydoman.com',
proxy: {
target: "https:mydomain.com:8989",
},
port: 3000
}

this not working for me, anyone can help me please. Here is the detail of my MAMP Configuration:

Apache Port for http: 80
Apache Port for https: 443
MySQL Port: 3306

var gulp        = require('gulp'),
    browserSync = require('browser-sync').create();

gulp.task('serve', function() {

    browserSync.init({
          open: 'external',
          host: 'proejdct.dev',
          proxy: 'proejdct.dev', // or project.dev/app/
          port: 8080
    });

    gulp.watch("./themes/proejdct/*.htm").on('change', browserSync.reload);
    // gulp.watch("themes/amalia/*.less").on('change', browserSync.reload);
});

gulp.task('default', ['serve']);

@muhammad-ihsan Are you using HTTPS locally? If so, I think you need to set "proxy" to "https://proejdct.dev".

Little late to the party, I had problems with this also. Answer from @mohamdio works but you have to run browsersync from Vagrant. And then it works as expected.

@partounian Can't you use the exsiitng database as "external"? I mean you could run code on local and it will connect to the external server with the current database.

How to change the defualt ip ?

image

External: http://192.168.56.1:3000/

I just can access the local network http://192.168.1.* with the home wifi!

so, how can I get this ?

External: http://192.168.1.56:3000/

How do I omit the :3000 port number

//live browser reload gulp.task('browserSync', function() { browserSync.init({ open: 'external', host: 'localhost/wppro/', port: '', server: { baseDir: 'project-name' }, }) })

leaving it blank is not working

Well. I guess you can always map localhost to the ip your app is served on
Just edit your hosts file

I would like to use the external with the Laravel Homestead, but I still can't.

Could anyone help?

I use Windows 10 + Vagrant + Homestead.

Same problem here cannot set url and port:

'use strict';
// Project configuration
var url         = 'htmlsandbox.sites.dev';

//Load PLugins
var browserSync = require('browser-sync').create('HTML Sandbox'),
    del = require('del'),
    gulp = require('gulp'),
    autoprefixer = require('gulp-autoprefixer'),
    cache = require('gulp-cache'),
    cssBase64 = require('gulp-css-base64'),
    imagemin = require('gulp-imagemin'),
    inlinesource = require('gulp-inline-source'),
    notify = require('gulp-notify'),
    sass = require('gulp-sass'),
    sourcemaps = require('gulp-sourcemaps'),
    uglify = require('gulp-uglify'),
    path = require('path'),
    runSequence = require('run-sequence');

// Task to compile SCSS
gulp.task('sass', function () {
  return gulp.src('./src/scss/styles.scss')
    .pipe(sourcemaps.init())
    .pipe(sass({
      outputStyle: 'nested', // Accepted values: nested, expanded, compact, compressed
      errLogToConsole: false,
      paths: [path.join(__dirname, 'scss', 'includes')]
    })
      .on("error", notify.onError(function (error) {
        return "Failed to Compile SCSS: " + error.message;
      })))
    .pipe(cssBase64())
    .pipe(autoprefixer())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./src/css/'))
    .pipe(gulp.dest('./dist/css/'))
    .pipe(browserSync.stream())
    .pipe(notify({
      message: "SCSS Compiled Successfully :)",
      onLast: true
    }));
});

// Task to Minify JS
gulp.task('jsmin', function () {
  return gulp.src('./src/js/**/*.js')
    .pipe(uglify())
    .pipe(gulp.dest('./dist/js/'));
});

// Minify Images
gulp.task('imagemin', function () {
  return gulp.src('./src/img/**/*.+(png|jpg|jpeg|gif|svg)')
    // Caching images that run through imagemin
    .pipe(cache(imagemin({
      interlaced: true
    })))
    .pipe(gulp.dest('./dist/img/'));
});

// BrowserSync Task (Live reload)
gulp.task('browserSync', function () {
  browserSync.init({
      server: {
                baseDir: "./src/",
                host: url,
                proxy: url,
                port: 8080,
                tunnel: "htmlsandbox" // Attempt to use the URL "http://htmlsandbox.localtunnel.me"
            }
  });
});

// Gulp Inline Source Task
// Embed scripts, CSS or images inline (make sure to add an inline attribute to the linked files)
// Eg: <script src="default.js" inline></script>
// Will compile all inline within the html file (less http requests - woot!)
gulp.task('inlinesource', function () {
  return gulp.src('./src/**/*.html')
    .pipe(inlinesource())
    .pipe(gulp.dest('./dist/'));
});

// Gulp Watch Task
gulp.task('watch', ['browserSync'], function () {
  gulp.watch('./src/scss/**/*', ['sass']);
  gulp.watch('./src/**/*.html').on('change', browserSync.reload);
});

// Gulp Clean Up Task
gulp.task('clean', function () {
  return del('dist');
});

// Gulp Default Task
gulp.task('default', ['watch']);

// Gulp Build Task
gulp.task('build', function (callback) {
  runSequence('clean', 'sass', 'imagemin', 'jsmin', 'inlinesource', callback);
});

There's any way to configure localhost without port? I need run this in http://localhost or http://project.local as configured in hosts.

Some of all this great info should be worked into the documentation https://browsersync.io/docs/options/#option-proxy.

I'm not sure why everyone missed @shakyShane comment. Remove the proxy field and when running 'gulp' it'll show you a snippet that you need to inject into your website.

I don't think it's technically possible for browsersync to inject code without redirecting. The other possibility is to pipe the generated javascript through your gulp build.

Just followed @shakyShane & @omarabid 's recommendation and it worked for me. Thank you both!

gulpfile.babel.js

const bs = browserSync.create();

export const server = (done) => {
  bs.init();
  done();
};

export const reload = done => {
  bs.reload();
  done();
};

The command line suggested to do the following:

Copy the following snippet into your website, just before the closing body tag

<script id="__bs_script__">//<![CDATA[
  document.write("<script async src='http://HOST:3000/browser-sync/browser-sync-client.js?v=2.26.7'><\/script>".replace("HOST", location.hostname));
//]]></script> 

So I pasted that snippet to the footer of my website.

I AM GETTING BELOW ERROR CAN ANY ONE PLZ HELP ME???

C:>browser-sync start --server --directory --files "*/"
events.js:287
throw er; // Unhandled 'error' event
^

Error: EPERM: operation not permitted, watch 'C:Documents and Settings'
at FSWatcher.start (internal/fs/watchers.js:169:26)
at Object.watch (fs.js:1339:11)
at createFsWatchInstance (C:UserssainaveenAppDataRoamingnpmnode_modulesbrowser-syncnode_moduleschokidarlibnodefs-handler.js:38:15)
at setFsWatchListener (C:UserssainaveenAppDataRoamingnpmnode_modulesbrowser-syncnode_moduleschokidarlibnodefs-handler.js:81:15)
at FSWatcher.NodeFsHandler._watchWithNodeFs (C:UserssainaveenAppDataRoamingnpmnode_modulesbrowser-syncnode_moduleschokidarlibnodefs-handler.js:233:14)
at FSWatcher.NodeFsHandler._handleDir (C:UserssainaveenAppDataRoamingnpmnode_modulesbrowser-syncnode_moduleschokidarlibnodefs-handler.js:429:19)
at FSWatcher. (C:UserssainaveenAppDataRoamingnpmnode_modulesbrowser-syncnode_moduleschokidarlibnodefs-handler.js:477:19)
at FSWatcher. (C:UserssainaveenAppDataRoamingnpmnode_modulesbrowser-syncnode_moduleschokidarlibnodefs-handler.js:482:16)
at FSReqCallback.oncomplete (fs.js:168:5)
Emitted 'error' event on FSWatcher instance at:
at FSWatcher._handleError (C:UserssainaveenAppDataRoamingnpmnode_modulesbrowser-syncnode_moduleschokidarindex.js:260:10)
at createFsWatchInstance (C:UserssainaveenAppDataRoamingnpmnode_modulesbrowser-syncnode_moduleschokidarlibnodefs-handler.js:40:5)
at setFsWatchListener (C:UserssainaveenAppDataRoamingnpmnode_modulesbrowser-syncnode_moduleschokidarlibnodefs-handler.js:81:15)
[... lines matching original stack trace ...]
at FSReqCallback.oncomplete (fs.js:168:5) {
errno: -4048,
syscall: 'watch',
code: 'EPERM',
path: 'C:\Documents and Settings',
filename: 'C:\Documents and Settings'

Was this page helpful?
0 / 5 - 0 ratings

Related issues

danielverejan picture danielverejan  路  3Comments

ericmorand picture ericmorand  路  3Comments

jitendravyas picture jitendravyas  路  4Comments

zewa666 picture zewa666  路  3Comments

codeofsumit picture codeofsumit  路  3Comments