title: How to show login page before showing index.html using express.static in node.js
body: <p>I'm using <code>app.use(express.static(path.join(__dirname,'public')));</code> to show login page before showing index.html in Node.js. </p>
  
  <p>However, it doesn't show login page before index.html...
  I tried to use <code>app.get('/', function (req,res) {res.redirect('/login');});</code> but it doesn't even go through that <code>app.get</code> and doesn't redirect when it connects to localhost:4000...</p>
  
  <p>my directory setup is shown below</p>
  
  <pre><code>myapp
    node_modules
    public
      images
      javascripts
      js
      stylesheets
      index.html
    routes
    views
      login
        login.ejs
      users
        new.ejs
      index.jade
      layout.jade
    app.js
    package.json
  </code></pre>
  
  <p>Also, I want to hold index.html in public folder and just want to display login page before that..
  Is there any ways to show that??</p>
  
  <p>Here is my whole code in app.js</p>
  
  <pre><code>var io = require('socket.io');
  var express = require('express');
  var app = express();
  var redis = require('redis');
  var sys = require('util');
  var fs = require('fs');
  //Added for connecting login session
  var http = require('http');
  var server = http.createServer(app);
  var path = require('path');
  var mongoose = require('mongoose');
  var passport = require('passport');
  var session = require('express-session');
  var flash = require('connect-flash');
  var async = require('async');
  var bodyParser = require('body-parser');
  var methodOverride = require('method-override');
  
  //connecting database
  mongoose.connect("my mongoDB private address");
  var db = mongoose.connection;
  db.once("open",function () {
    console.log("DB connected!");
  });
  db.on("error",function (err) {
    console.log("DB ERROR :", err);
  });
  
  var bcrypt = require("bcrypt-nodejs");
  var userSchema = mongoose.Schema({
    email: {type:String, required:true, unique:true},
    password: {type:String, required:true},
    createdAt: {type:Date, default:Date.now}
  });
  userSchema.pre("save", function (next){
    var user = this;
    if(!user.isModified("password")){
      return next();
    } else {
      user.password = bcrypt.hashSync(user.password);
      return next();
    }
  });
  userSchema.methods.authenticate = function (password) {
    var user = this;
    return bcrypt.compareSync(password,user.password);
  };
  
  var User = mongoose.model('user',userSchema);
  
  io = io.listen(server);
  
  app.set("view engine", 'ejs');
  
  app.use(express.static(path.join(__dirname, 'public')));
  
  //setting middleware for login
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({extended:true}));
  app.use(methodOverride("_method"));
  app.use(flash());
  
  app.use(session({secret:'MySecret', resave: true, saveUninitialized: true}));
  app.use(passport.initialize());
  app.use(passport.session());
  
  passport.serializeUser(function(user, done) {
    done(null, user.id);
  });
  passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
      done(err, user);
    });
  });
  
  var LocalStrategy = require('passport-local').Strategy;
  passport.use('local-login',
    new LocalStrategy({
        usernameField : 'email',
        passwordField : 'password',
        passReqToCallback : true
      },
      function(req, email, password, done) {
        User.findOne({ 'email' :  email }, function(err, user) {
          if (err) return done(err);
  
          if (!user){
              req.flash("email", req.body.email);
              return done(null, false, req.flash('loginError', 'No user found.'));
          }
          if (!user.authenticate(password)){
              req.flash("email", req.body.email);
              return done(null, false, req.flash('loginError', 'Password does not Match.'));
          }
          return done(null, user);
        });
      }
    )
  );
  //set home routes
  //var data_1 = {email:''};
  
  app.get('/', function (req,res) {
    res.redirect('/login');
    //req.url = '/login';
    //next();
  });
  app.get('/login', function (req,res) {
    res.render('login/login',{email:req.flash("email")[0], loginError:req.flash('loginError')});
  });
  app.post('/login', function(req, res, next) {
  passport.authenticate('local-login', function(err, user, info) {
    if (err) { return next(err); }
    if (!user) { return res.redirect('/login'); }
    return res.redirect('/?channel='+ req.body.email);
    })(req, res, next);
  });
  app.get('/logout', function(req, res) {
      req.logout();
      res.redirect('/login');
  });
  
  // set user routes
  app.get('/users/new', function(req,res){
    res.render('users/new', {
                              formData: req.flash('formData')[0],
                              emailError: req.flash('emailError')[0],
                              passwordError: req.flash('passwordError')[0]
                            }
    );
  }); // new
  app.post('/users', checkUserRegValidation, function(req,res,next){
    User.create(req.body.user, function (err,user) {
      if(err) return res.json({success:false, message:err});
      res.redirect('/login');
    });
  }); // create
  
  //functions
  function isLoggedIn(req, res, next) {
    if (req.isAuthenticated()){
      return next();
    }else{
      res.redirect('/login');
    }
    res.redirect('/');
  }
  
  function checkUserRegValidation(req, res, next) {
    var isValid = true;
  
    async.waterfall(
      [function(callback) {
        User.findOne({email: req.body.user.email, _id: {$ne: mongoose.Types.ObjectId(req.params.id)}},
          function(err,user){
            if(user){
              isValid = false;
              req.flash("emailError","- This email is already resistered.");
            }
            callback(null, isValid);
          }
        );
      }], function(err, isValid) {
        if(err) return res.json({success:"false", message:err});
        if(isValid){
          return next();
        } else {
          req.flash("formData",req.body.user);
          res.redirect("back");
        }
      }
    );
  }
  
  function handler(req,res){
      console.log(req);
          fs.readFile(__dirname + '/public/index.html', function(err,data){
                  if(err){
                          res.writeHead(500);
                          return res.end('Error loading index.html');
                  }
  
                  res.writeHead(200);
                  console.log("Listening on port 3000");
                  res.end(data);
          });
  
          fs.readFile(__dirname + '/public/style.css', function(err,data){
                  if(err){
                          res.writeHead(500);
                          return res.end('Error loading index.html');
                  }
  
                  res.writeHead(200);
                  console.log("Listening on port 3000");
                  res.end(data);
          });
  }
  
  io.sockets.addListener('connection', function(socket){
      console.log("connceted : " + socket.id);
  
      var subscriber = redis.createClient(6379, 'localhost');
      subscriber.psubscribe("*");
      subscriber.on("pmessage", function(pattern, channel, message) {
          //console.log(message);
          socket.emit(channel, message);
      });
  
      socket.on('disconnect', function () {
          console.log("disconnceted : " + socket.id);
          subscriber.quit();
      });
  
      socket.on('close', function() {
          console.log("close");
          subscriber.quit();
      });
  });
  
  app.listen(4000, function(){
    console.log('Server On!!!');
  });
  </code></pre>
  
  <p>Should I use another express to display login page? or what should I do here?
  I'm actually newbie in node.js.</p>
  
  <p>Can anybody please help me out here??</p>
  
  <p>Thank you..</p>
  
  <p><strong>EDIT:</strong> My whole code for app.js</p>
  
  <pre><code>var express = require('express');
  var app = express();
  
  //Added for connecting login session
  var http = require('http');
  var server = http.createServer(app);
  var path = require('path');
  var mongoose = require('mongoose');
  var passport = require('passport');
  var session = require('express-session');
  var flash = require('connect-flash');
  var async = require('async');
  var bodyParser = require('body-parser');
  var cookieParser = require('cookie-parser');
  var methodOverride = require('method-override');
  
  //connecting database
  mongoose.connect("private mongoDB address");
  var db = mongoose.connection;
  db.once("open",function () {
    console.log("DB connected!");
  });
  db.on("error",function (err) {
    console.log("DB ERROR :", err);
  });
  
  var bcrypt = require("bcrypt-nodejs");
  var userSchema = mongoose.Schema({
    email: {type:String, required:true, unique:true},
    password: {type:String, required:true},
    createdAt: {type:Date, default:Date.now}
  });
  userSchema.pre("save", function (next){
    var user = this;
    if(!user.isModified("password")){
      return next();
    } else {
      user.password = bcrypt.hashSync(user.password);
      return next();
    }
  });
  userSchema.methods.authenticate = function (password) {
    var user = this;
    return bcrypt.compareSync(password,user.password);
  };
  
  var User = mongoose.model('user',userSchema);
  
  app.set("view engine", 'ejs');
  app.use(express.static(path.join(__dirname, 'public')));
  //setting middleware for login
  app.use(cookieParser());
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({extended:true}));
  app.use(methodOverride("_method"));
  app.use(flash());
  
  app.use(session({secret:'MySecret', resave: true, saveUninitialized: true}));
  app.use(passport.initialize());
  app.use(passport.session());
  
  passport.serializeUser(function(user, done) {
    //console.log('serializeUser()', user);
    done(null, user.id);
  });
  passport.deserializeUser(function(id, done) {
    //console.log('deserializeUser()', user);
    User.findById(id, function(err, user) {
      done(err, user);
    });
  });
  var global_username = '';
  var LocalStrategy = require('passport-local').Strategy;
  passport.use('local-login',
    new LocalStrategy({
        usernameField : 'email',
        passwordField : 'password',
        passReqToCallback : true
      },
      function(req, email, password, done) {
        User.findOne({ 'email' :  email }, function(err, user) {
          if (err) return done(err);
          if (!user){
              req.flash("email", req.body.email);
              return done(null, false, req.flash('loginError', 'No user found.'));
          }
          if (!user.authenticate(password)){
              req.flash("email", req.body.email);
              return done(null, false, req.flash('loginError', 'Password does not Match.'));
          }
          var email_address = req.body.email;
          var username = email_address.substring(0, email_address.lastIndexOf("@"));
          global_username = username;
          return done(null, user);
        });
      }
    )
  );
  //set home routes
  app.get('*', loggedInCheck);   ------------------&gt;This is the code with loggedInCheck function. I created another one instead of isLoggedIn function
  app.get('/login', function (req,res) {
    res.render('login/login',{email:req.flash("email")[0], loginError:req.flash('loginError')});
  });
  
  app.post('/login',
    function (req,res,next){
      next();
    }, passport.authenticate('local-login', {
      successRedirect : '/posts',
      failureRedirect : '/login',
      failureFlash : true
    })
  );
  
  
  app.get('/logout', function(req, res) {
      req.logout();
      res.redirect('/login');
  });
  // set user routes
  app.get('/users/new', function(req,res){
    res.render('users/new', {
                              formData: req.flash('formData')[0],
                              emailError: req.flash('emailError')[0],
                              passwordError: req.flash('passwordError')[0]
                            }
    );
  }); // new
  app.post('/users', checkUserRegValidation, function(req,res,next){
    User.create(req.body.user, function (err,user) {
      if(err) return res.json({success:false, message:err});
      res.redirect('/login');
    });
  }); // create
  
  app.get('/posts', isLoggedIn, function(req, res){
    res.redirect('/status.html?channel=' + global_username);
  });
  
  //functions
  function isLoggedIn(req, res, next) {
    if (req.isAuthenticated()){
      console.log("Authenticated");
      console.log("Accessing to status.html");
      return next();
  
    }else{
      console.log("Unauthorized Attempt");
      res.redirect('/login');
  
    }
  }
  
  function loggedInCheck(req, res, next) {
    if (req.isAuthenticated()){
      res.redirect('/status.html?channel=' + global_username);
  
    }else{
      console.log("Unauthorized Attempt");
      res.redirect('/login');
  
    }
  }
  
  
  server.listen(5000);
  </code></pre>