btmach btmach - 2 years ago 57
Javascript Question

Securing a specific route node.js

Hey I'm using basic auth for Node.JS to secure a route. I'm pretty new to Node.JS and don't understand what the next function does in this case. What I'm trying to do is to secure a the route:


Note: This is a project for learning purposes so the login part is not too serious and won't be used live.


var basicAuth = require('basic-auth');

exports.BasicAuthentication = function(request, response, next) {

function unauthorized(response) {
response.set('WWW-Authenticate', 'Basic realm=Authorization Required');
return response.send(401);

var user = basicAuth(request);

if (!user || ! || !user.pass) {
return unauthorized(response);

if ( === 'name' && user.pass === 'pass') {
return next();
} else {
return unauthorized(response);


and app.js where I imported the module authentication:

app.get('/admin/', authentication.BasicAuthentication, function(req, res){
console.log("hi u need to login");

So what I want to do is to route the user further if the authentication goes through.

Thanks in advance!

Answer Source


app.get('/admin/', authentication.BasicAuthentication);
app.get('/admin/', function(req, res) {});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download