title: How to save a token in a local storage (or cookie)?
body: <p>I am trying to implement a login function in an app. Currently, I could register a login, generate a jwt token. However, I do not know how to store this token in a cookie (or local storage). I have a middleware that would require a user to send a token in each request which is private. In postman, I could put 'x-auth-token' and a token in a header. Many of the tutorials use passport, cookie-parser which seemed kinda complicated. Are there any other easier ways? I saw in the express document that there were <code>res.cookie('x-auth-token', token);</code> available too, I tried it but it didn't work. I also tried <code>window.localStorage.setItem('x-auth-token', token);</code>, still didn't work.</p>
  
  <p>I have tried something super simple which is to simply put a token in a localStorage. <code>window.localStorage.setItem('x-auth token', token);</code> However, it didn't work.</p>
  
  <p>auth</p>
  
  <pre><code>const jwt = require('jsonwebtoken');
  const config = require('config');
  
  // middleware function, next so it moves on to the next middlware
  module.exports = function(req, res, next) {
    //get the token from header
    const token = req.header('x-auth-token');
  
    //Check if not token
    if (!token) {
      return res.status(401).json({ msg: 'No token, authorization denied' });
    }
  
    //Verify token if exist
    try {
      const decoded = jwt.verify(token, config.get('jwtSecret'));
      req.user = decoded.user;
      next();
    } catch (err) {
      res.status(401).json({ msg: 'Token is not valid' });
    }
  };
  
  </code></pre>
  
  <p>posts.js</p>
  
  <pre><code>// @ route    POST api/users
  // @desc      Register User
  // @access    Public
  router.post(
    '/',
    [
      check('name', 'Name is required')
        .not()
        .isEmpty(),
      check('email', 'Please include a valid email').isEmail(),
      check(
        'password',
        ' Please enter a password with 6 or more characters'
      ).isLength({ min: 6 })
    ],
    async (req, res) =&gt; {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          errors: errors.array()
        });
      }
      const { name, email, password } = req.body;
  
      try {
        // See if user exists, have to be unique
        let user = await User.findOne({ email });
        if (user) {
          return res
            .status(400)
            .json({ errors: [{ msg: 'User already exists' }] });
        }
        // Get users gravatar
        const avatar = gravatar.url(email, {
          s: '200',
          r: 'pg',
          d: 'mm'
        });
        user = new User({
          name,
          email,
          avatar,
          password
        });
  
        //encrypt password
        const salt = await bcrypt.genSalt(10);
  
        user.password = await bcrypt.hash(password, salt);
        // anything that return a promise, we have to put await !!
        await user.save();
        //return jsonwebtoken
        const payload = {
          user: {
            id: user.id
          }
        };
  
        jwt.sign(
          payload,
          config.get('jwtSecret'),
          { expiresIn: 60 * 60 * 100 },
          (err, token) =&gt; {
            // window.localStorage.setItem('x-auth-token', token);
            res.json({ token });
            res.cookie('x-auth-token', token);
            // req.flash('You seccessfully registered your account');
            // res.redirect('/user/login');
          }
        );
      } catch (err) {
        console.error(err.message);
        res.status(500).send('Server error');
      }
    }
  );
  </code></pre>
  
  <p>main.handlebars</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html lang="en"&gt;
  
  &lt;head&gt;
      &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
      &lt;link rel="stylesheet" href="/css/main.css"&gt;
      &lt;link rel="stylesheet" href="/css/register.css"&gt;
      &lt;link href="https://fonts.googleapis.com/css?family=Roboto&amp;display=swap" rel="stylesheet"&gt;
      &lt;script src="https://use.fontawesome.com/804afe4c6e.js"&gt;&lt;/script&gt;
  
      {{!-- for auto-reload --}}
      &lt;script src="/reload/reload.js"&gt;&lt;/script&gt;
      &lt;script src="/javascript/main.js"&gt;&lt;/script&gt;
  
  
      &lt;title&gt;Idea Share&lt;/title&gt;
  &lt;/head&gt;
  
  &lt;body&gt;
  
      &lt;nav class="navbar bg-dark"&gt;
          &lt;h1&gt;&lt;a href="/"&gt;Idea Share&lt;/a&gt;&lt;/h1&gt;
          &lt;ul&gt;
              &lt;a href="/signup"&gt;
                  &lt;li&gt;Sign up&lt;/li&gt;
              &lt;/a&gt;
              &lt;a href="/signup"&gt;
                  &lt;li&gt;Log in&lt;/li&gt;
              &lt;/a&gt;
          &lt;/ul&gt;
      &lt;/nav&gt;
      &lt;div class="container"&gt;
          {{{body}}}
      &lt;/div&gt;
  &lt;/body&gt;
  
  &lt;/html&gt;
  </code></pre>
  
  <p>register.handlebars</p>
  
  <pre><code>&lt;div class="height-container"&gt;
      &lt;div class="vertical-align"&gt;
          &lt;div class="register-form"&gt;
              &lt;h1&gt;Create your account&lt;/h1&gt;
              &lt;form class="form" action="/api/users" method="post"&gt;
                  &lt;div class="form-group"&gt;
                      &lt;input name="name" type="text" placeholder="Name" requried&gt;
                  &lt;/div&gt;
  
                  &lt;div class="form-group"&gt;
                      &lt;input name="email" type="email" placeholder="E-mail"&gt;
                  &lt;/div&gt;  
  
                  &lt;div class="form-group"&gt;
                      &lt;input name="password" type="text" placeholder="Password" minlength="6"&gt;
                  &lt;/div&gt;
                  &lt;input onclick="loginUser()" type="submit" value="Create account" class="button green-button" /&gt;
              &lt;/form&gt;
              &lt;p&gt;Already have an account? &lt;a href="/signin"&gt;Sign in&lt;/a&gt;&lt;/p&gt;
          &lt;/div&gt;
      &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>post.handlebars</p>
  
  <pre><code>&lt;div class="height-container"&gt;
      &lt;div class="vertical-align"&gt;
          &lt;div class="idea-form"&gt;
              &lt;h1&gt;Share your idea&lt;/h1&gt;
              &lt;form class="form" action="/api/posts" method="post"&gt;
                  &lt;div class="form-group"&gt;
                      &lt;input type="text" placeholder="What is your idea?" name="title" requried&gt;
                  &lt;/div&gt;
  
                  &lt;div class="form-group"&gt;
                      &lt;input type="text" placeholder="Let us know more detail. What is the story. How did you come up with it? 
  Why do you think people would need it etc" name="body"&gt;
                  &lt;/div&gt;
                  &lt;input "type=" submit" value="Post" class="button green-button" /&gt;
  
              &lt;/form&gt;
          &lt;/div&gt;
      &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>