Hello World, Today we are going to discuss that how we can perform login logout with nodejs and express. In this tutorial we will learn how we can use express-session for login user and logout user with nodejs and express. We will also learn about express-generator in this article.
I have divided this tutorial in following parts:
- Introduction of Nodejs and Express
- Setup Project
- Creating Login Form
- Create Code for Login and Logout
- Test Whole Concept
Introduction of Nodejs and Express
Here i will not going to explain everything about nodejs and express. Because i have already wrote an article for this purpose. You can read the following article to create basic website with nodejs and express.
- Create simple static website with nodejs,express and jade
- Create Dynamic Website with Nodejs and MongoDB
In this tutorial we will not use simple express but we will use express-generator. This is also a npm’s package like other packages. This helps us to create the skeleton of the project with just one command. You can read about express-generator from this link.
Setup Project
- Open command prompt and add the following code.
npm install -g express-generator
- The above command will install express-generator globally. Now run the following command to create the skeleton of the project.
express --css less login
- The above command will create login folder with some basic files and folder. Following is the screenshot created folder.
- Go to the login folder and run the following command to install the all dependencies.
npm install
- After installing the all dependencies run the following command to run the server.
npm start
- Open http://localhost:3000 in your browser and you will the following screen.
- In command prompt, you will see the console log like following.
This console log is generator by the logger. Main benefit of express-generator is that it will install basic things for us like logger, error-handler, view engine etc.
- Install express-session with following command.
npm install express-session --save
Now we have successfully settled up our server.
Create Login Form
In this part we will create login form view in our project. Please Remember one thing that we are not using here any database so we will perform login and logout action at static values.
- Add express-session dependency with npm install.
- Create login.jade file in views folder and add the following code.
extends layout block content h1= title hr form(action="post",method="post") label(for="username") Username br input(type="text",name="username") br br label(for="password") Password br input(type="password",name="password") br br input(type="submit",value="Login")
- Add the following before this line app.use(‘/’,index)
// Login Work Start var session=require('express-session'); app.use(session({secret:'app',cookie:{maxAge:6000}})); var checkUser=function(req,res,next){ if(req.session.loggedIn){ next(); }else{ res.render('login',{title:"Login Here"}); } }; // Login Work Start End
- Run the server npm start. You will see the following screenshot.
Create code for login and logout
- Open app.js file and replace the following code with previous one.
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var lessMiddleware = require('less-middleware'); var session=require('express-session'); var index = require('./routes/index'); var users = require('./routes/users'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(lessMiddleware(path.join(__dirname, 'public'))); app.use(express.static(path.join(__dirname, 'public'))); // Login Work Start app.use(session({secret:'secret-code',cookie:{maxAge:6000}})); var checkUser=function(req,res,next){ if(req.session.loggedIn){ next(); }else{ var admin="admin", password="admin"; if(req.body.username===admin && req.body.password===password){ req.session.loggedIn=true; res.redirect('/'); }else{ res.render('login',{title:"Login Here"}); } } }; var logout=function(req,res,next){ req.session.loggedIn=false; res.redirect('/'); }; app.use('/',checkUser, index); // Login Work Start End app.use('/users', users); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); module.exports = app;
- Open index.jade file and following code in the end.
a(href="/logout") Logout
Test the whole concept
- Run the server and open localhost:3000
- Fill the form admin, admin value and you will successfully redirect on index page with logout link.
- Click on logout link and you will redirect on login form.
Here we have created login logout with nodejs and express.