Skip to content

Instantly share code, notes, and snippets.

@timaschew
Last active December 4, 2021 18:34
Show Gist options
  • Save timaschew/00ba49d3a39bc3dfbe8f to your computer and use it in GitHub Desktop.
Save timaschew/00ba49d3a39bc3dfbe8f to your computer and use it in GitHub Desktop.
proxy browser-sync server with express and secure everything with basic auth
// just add pass server as your task function
// Start a server with LiveReload to preview the site in
const OUTPUT_PARENT = 'dist'
const OUTPUT_DIRECTORY = OUTPUT_PARENT + '/browser-sync'
function server(done) {
browser.init({
server: {
directory: true,
baseDir: OUTPUT_PARENT
},
port: 5000,
open: false,
});
done();
}
const express = require('express')
const proxy = require('express-http-proxy')
const basicAuth = require('basic-auth')
var auth = function (req, res, next) {
function unauthorized(res) {
res.set('WWW-Authenticate', 'Basic realm=Authorization Required')
return res.sendStatus(401)
}
var user = basicAuth(req)
if (!user || !user.name || !user.pass) {
return unauthorized(res)
}
if (user.name === 'user' && user.pass === 'pass') {
return next()
} else {
return unauthorized(res)
}
}
const app = express()
const server = require('http').createServer(app)
server.on('upgrade', function (req, socket, head) {
proxy.ws(req, socket, head)
})
app.use('/browser-sync', auth, proxy('localhost:5000', {
forwardPath: function(req, res) {
return '/browser-sync' + require('url').parse(req.url).path
}
}))
// proxy HTTP GET / POST
app.get('/browser-sync/socket.io/*', function(req, res) {
console.log("proxying GET request", req.url)
proxy.web(req, res, { target: 'http://localhost:5000'})
})
app.post('/browser-sync/socket.io/*', function(req, res) {
console.log("proxying POST request", req.url)
proxy.web(req, res, { target: 'http://localhost:5000'})
})
const PORT = process.env.PORT || 5001
app.listen(PORT)
console.log('server started on ' + PORT)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment