Storing JWT in client side and putting tokens in all the future request I have started using NodeJS with Express JS and PassportJS and JWT for User Authentication. I am able to authenticate the user and generate JWT Token. I am using Bootstrap for my front-end.

By using Postman I am able to get the token and put it in the next request header and it is working fine.

But how do I do this in HTML Pages using JavaScript?


JavaScript to get response body or response headers
JavaScript to set request header with JWT Token


Here is the snippet to store data in SessionStorage:

sessionStorage.setItem('token', 'token-abcd1234');
var token = sessionStorage.getItem('token');


I have a mechanism to invalidate the token on logout by putting them in a DB.

Let me know if I am missing any pattern or missing anything.

Note: I am using login.html which has a form with a username and password. AJAX is not used.

Login Page

&lt;body&gt;
&lt;div class="container"&gt;
&lt;h3&gt;Login&lt;/h3&gt;
  &lt;div class="jumbotron col-sm-6"&gt;
    &lt;form class="form-horizontal" action="/login" method="POST"&gt;
    &lt;div class="form-group"&gt;
      &lt;label class="control-label col-md-2" for="email"&gt;Email:&lt;/label&gt;
      &lt;div class="col-md-4"&gt;
        &lt;input type="email" class="form-control" id="email" placeholder="Enter email" name="email"&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    &lt;div class="form-group"&gt;
      &lt;label class="control-label col-md-2" for="password"&gt;Password:&lt;/label&gt;
      &lt;div class="col-md-4"&gt;          
        &lt;input type="password" class="form-control" id="password" placeholder="Enter password" name="password"&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    &lt;div class="form-group"&gt;        
      &lt;div class="col-md-offset-2 col-md-10"&gt;
        &lt;button type="submit" class="btn btn-default"&gt;Submit&lt;/button&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    &lt;/form&gt;
  &lt;/div&gt;   
&lt;/div&gt;
&lt;/body&gt;


NodeJS Route

router.get('/login', function(req, res, next) {
  res.render('login');
});

router.post('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) {
      return next(err);
    }

    if (!user) {
      return res.status(401).json({
        err: info
      });
    }

    req.logIn(user, function(err) {
      if (err) {
        console.log(err);
        return res.status(500).json({
          err: 'Could not log in user'
        });
      }

      var token = Verify.getToken(user);
      res.status(200).json({
        status: 'Login successful!',
        success: true,
        token: token
      });
    });
  })(req,res,next);  
});
At the time of posting this question, I had no idea about Frontend Frameworks.
Later I choose Vue Js as my frontend framework, things are working great.

All I was missing a Frontend Framework.