Skip to content

Instantly share code, notes, and snippets.

@thelbouffi
Last active February 13, 2018 17:06
Show Gist options
  • Save thelbouffi/f4740dd2220f339dc58ec5fe3c754344 to your computer and use it in GitHub Desktop.
Save thelbouffi/f4740dd2220f339dc58ec5fe3c754344 to your computer and use it in GitHub Desktop.
express callback next callback (also how to protect a link for example /profile)
// in express we can pass a callback to another callback using next
// for example if we need to choose between two response (if condition is made res.send else res.send) to do that we need to pass next()
// callback to else in our middleware
// in the auth_middleware.js
let authenticated = false;
let requireLogin = (req, res, next) => {
if (!authenticated) {
res.send('not logged in'); // res.redirect('/login');
console.log('not logged');
} else {
next();
console.log('you are logged');
}
}
// in the router
let auth = require('../../auth_middleware.js');
router.get('/profile', auth.userLogged, (req, res) => {
res.send('helloooooo to your profile'); //or res.render('dashboard.pug');
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment