Sometimes, we want to implement login authentication in Node.js.
In this article, we’ll look at how to implement login authentication in Node.js.
How to implement login authentication in Node.js?
To implement login authentication in Node.js, we can add our own middleware to check the session object before calling the route handler.
For instance, we write
const checkAuth = (req, res, next) => {
if (!req.session.userId) {
res.send('You are not authorized');
} else {
next();
}
}
app.get('/my_secret_page', checkAuth, (req, res) => {
res.send('You are logged in');
});
app.post('/login', (req, res) => {
const post = req.body;
if (post.user === 'john' && post.password === 'johnspassword') {
req.session.userId = johnsUserId;
res.redirect('/my_secret_page');
} else {
res.send('Bad user/pass');
}
})
app.get('/logout', (req, res) => {
delete req.session.userId;
res.redirect('/login');
});
to define the checkAuth
middleware function that checks if req.session.userId
is present.
We set req.session.userId
in the /login
route when login is successful.
If req.session.userId
isn’t set, we call res.send
with a 'You are not authorized'
.
Otherwise, we call next
to call the route middleware.
Next, we add the endpoints with app.get
and app.post
.
We add checkAuth
as an argument in /my_secret_page
to run checkAuth
to check for presence of userId
before running the route.
In the /login
route handler, we check the user
and password
from the req.body
request body object.
And if they both match, we call res.redirect
to redirect to /my_secret_page
since login is successful.
In /logout
, we delete req.session.userId
to remove the current user info and call res.redirect
to redirect to /login
.
Conclusion
To implement login authentication in Node.js, we can add our own middleware to check the session object before calling the route handler.