Skip to content
  • My account
  • Cart
  • Forums
  • Sell
  • LICENSES

If you face any issue, please send email at projectsplaza@gmail.com

  • Projects
    • Django
    • Laravel
    • Codeigniter
    • Core php
    • Bootstrap 4
  • Learn Php
    • Php
    • Laravel
    • Codeigniter
  • Learn Python
    • Python
    • Django
    • Flask
  • Javascript
    • Jquery
    • ReactJs
    • Ajax
    • AngularJs
    • React Native
  • Nodejs
    • Express
    • Jade
    • Handlebars
    • MongoDB
  • Projects
    • Django
    • Laravel
    • Codeigniter
    • Core php
    • Bootstrap 4
  • Learn Php
    • Php
    • Laravel
    • Codeigniter
  • Learn Python
    • Python
    • Django
    • Flask
  • Javascript
    • Jquery
    • ReactJs
    • Ajax
    • AngularJs
    • React Native
  • Nodejs
    • Express
    • Jade
    • Handlebars
    • MongoDB

Login Logout with Nodejs and Express

  • by Projects Plaza
  • March 8, 2018March 8, 2018
login-logout-with-nodejs-express

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.

folder-structure

  • 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.

console-log

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.

login-form


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.

Like this:

Like Loading...

Related

Tags:Express TutorialsHow to login logout with nodejsHow to login logout with nodejs and expressJavaScript TutorialsLearning AngularLearning ExpressLearning JavaScriptLearning NodejsLogin example in nodejsLogin example with nodejs and expressLogin logout in nodejs expressLogin logout nodejs expressLogin logout with express nodejsLogin logout with nodejsLogin logout with nodejs and expressMean TutorialsNodejs TutorialsSimple login with nodejs

Leave a Reply Cancel reply

More posts from this category

  • Create simple static website w...
  • Create Dynamic Website with No...
  • Upload Image with Nodejs and E...
  • Create website with nodejs exp...
  • Create single page website wit...
  • Login Logout with Nodejs and E...
  • Fetch data from database with...
  • Create a hello world app with...
  • Create a single page applicati...
  • Create a dynamic single page a...
  • How to work with ajax in larav...
  • create reactjs application wit...
  • Create comment system with jqu...

Post Categories

  • Ajax
  • AngularJs
  • APIs
  • Codeigniter
  • Codeigniter Tutorial Series
  • Django
  • Django 3
  • Django Database
  • Django Frontend
  • Express
  • Flask
  • Handlebars
  • Jade
  • Javascript
  • Javascript Frameworks
  • Jquery
  • Laravel
  • Laravel 5
  • Laravel 7
  • Learn python with example
  • Matplotlib
  • Mobile Development
  • MongoDB
  • Mongoose
  • Nodejs
  • npm
  • Php
  • Php Framework
  • Programming
  • Python
  • Python Exercie
  • Python Web Framework
  • React Native
  • ReactJs
  • Uncategorized
  • Web Development
  • WordPress

Post Tags

codeigniter 3 codeigniter 3 from scratch codeigniter 3 tutorials Codeigniter Example Code Codeigniter Tutorial codeigniter tutorials Codeigniter tutorial series create project from scratch with django 2 django tutorials how to create blog app with django laravel 5 tutorials laravel practise example laravel scripts Laravel tutorial laravel tutorial blog laravel tutorials Laravel tutorial series Learn Codeigniter Learn Codeigniter From scratch Learn Codeigniter with example learn django learn django 2 learn django framework learn django from scratch learn django with example learn django with example code learning codeigniter from scratch learning codeigniterphp framework learning learning php framework learning php frameworks learning python Learn laravel learn laravel 5 Learn laravel from scratch Learn laravel with example learn php learn python 3 php codeigniter 3 tutorials php codeigniter tutorials php framework tutorials php mvc php mvc tutorials php scripts projectsplaza web development

Follow Us

  • Facebook
  • Twitter
  • Tumblr
  • YouTube
  • GitHub
  • Pinterest
  • Reddit
  • Support
  • Terms and conditions

Maintained By ProjectsPlaza[dot]com

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish.Accept Read More
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary
Always Enabled

Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.

Non-necessary

Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.

  • USD $
    USD dollar
  • INR ₹
    Indian Rupee
  • Projects
    • Django
    • Laravel
    • Codeigniter
    • Core php
    • Bootstrap 4
  • Learn Php
    • Php
    • Laravel
    • Codeigniter
  • Learn Python
    • Python
    • Django
    • Flask
  • Javascript
    • Jquery
    • ReactJs
    • Ajax
    • AngularJs
    • React Native
  • Nodejs
    • Express
    • Jade
    • Handlebars
    • MongoDB
%d bloggers like this: