Skip to content

Instantly share code, notes, and snippets.

@soltrinox
Forked from timaschew/gulp-task.js
Created November 24, 2021 02:38
Show Gist options
  • Save soltrinox/cea5b3af55091746918e80f86cee9572 to your computer and use it in GitHub Desktop.
Save soltrinox/cea5b3af55091746918e80f86cee9572 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