Skip to content

Instantly share code, notes, and snippets.

@Chris927
Last active November 25, 2015 14:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Chris927/5e19011ec4d46fb66d2e to your computer and use it in GitHub Desktop.
Save Chris927/5e19011ec4d46fb66d2e to your computer and use it in GitHub Desktop.
NodeJS Express, use middleware to protect routes
var express = require('express');
var app = express();
var port = 3100;
app.listen(port, function() {
console.log('listening on port ' + port);
});
/* public routes */
app.get('/', function(req, res, end) {
res.status(200).send('Hello, world');
})
app.get('/login', function(req, res, end) {
res.status(200).send('login here');
})
app.use(function(req, res, next) {
console.log('req.url', req.url);
if (req.session && req.session.user) {
return next();
}
res.redirect('/login');
});
/* routes protected by login */
app.get('/profile', function(req, res, end) {
res.status(200).send('my protected profile');
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment