Finglish
Finglish

Reputation: 9956

How to setup gulp browser-sync for a node / react project that uses dynamic url routing

I am trying to add BrowserSync to my react.js node project. My problem is that my project manages the url routing, listening port and mongoose connection through the server.js file so obviously when I run a browser-sync task and check the localhost url http://localhost:3000 I get a Cannot GET /.

Is there a way to force browser-sync to use my server.js file? Should I be using a secondary nodemon server or something (and if i do how can the cross-browser syncing work)? I am really lost and all the examples I have seen add more confusion. Help!!

gulp.task('browser-sync', function() {
    browserSync({
        server: {
            baseDir: "./"
        },
        files: [
            'static/**/*.*',
            '!static/js/bundle.js'
        ],
    });
});

Upvotes: 2

Views: 1966

Answers (1)

Ryan
Ryan

Reputation: 5973

We had a similar issue that we were able to fix by using proxy-middleware(https://www.npmjs.com/package/proxy-middleware). BrowserSync lets you add middleware so you can process each request. Here is a trimmed down example of what we were doing:

var proxy = require('proxy-middleware');
var url = require('url');

// the base url where to forward the requests
var proxyOptions = url.parse('https://appserver:8080/api');
// Which route browserSync should forward to the gateway
proxyOptions.route = '/api'

// so an ajax request to browserSync http://localhost:3000/api/users would be 
// sent via proxy to http://appserver:8080/api/users while letting any requests
// that don't have /api at the beginning of the path fall back to the default behavior.

browserSync({
    // other browserSync options
    // ....
    server: {
        middleware: [
            // proxy /api requests to api gateway
            proxy(proxyOptions)
        ]
    }
});

The cool thing about this is that you can change where the proxy is pointed, so you can test against different environments. One thing to note is that all of our routes start with /api which makes this approach a lot easier. It would be a little more tricky to pick and choose which routes to proxy but hopefully the example above will give you a good starting point.

The other option would be to use CORS, but if you aren't dealing with that in production it may not be worth messing with for your dev environment.

Upvotes: 3

Related Questions