title: How to store jwt in cookie and pass it to authentication function when redirecting a page?
body: <p>I have a node.js express backend built with Postman and tested with Jest. I wrote a front end with hbs and the next step is to stitch them. However I still keep getting "please authenticate" error message that's from my auth function, which I guess is because I'm not successfully passing my jwt token. </p>
  
  <p>So on login page (users/login) I want to login with email and password then I want to redirect to me page(users/me) where I can perform other stuff that belongs to this user. </p>
  
  <p>Front-end
  login page code:</p>
  
  <pre><code>&lt;section class="login-bg"&gt;
          &lt;div class="login-form"&gt;
              &lt;p&gt;Welcome to Task Manager, please log in!&lt;/p&gt;
              &lt;form class="input-group" action="/users/login" method="POST"&gt;
                  &lt;label&gt;Email:&lt;/label&gt;
                  &lt;input type="email" name="email" placeholder="type your email" value="{‌{user.email}}" required &gt;
                  &lt;label&gt;Password:&lt;/label&gt;
                  &lt;input type="password" name="password" placeholder="type your password" value="{‌{user.password}}" required&gt;
  
                  &lt;button class="button" type="submit"&gt;Log In&lt;/button&gt;
              &lt;/form&gt;
          &lt;/div&gt;
      &lt;/section&gt;
  </code></pre>
  
  <p>Back-end</p>
  
  <p>in middleware/auth.js</p>
  
  <pre><code>const jwt = require('jsonwebtoken')
  const User = require('../models/user')
  
  const auth = async (req, res, next) =&gt; {
      try {
          const token = req.header('Authorization').replace('Bearer ', '')
          const decoded = jwt.verify(token, process.env.JWT_SECRET)
          const user = await User.findOne({_id: decoded._id, 'tokens.token': token})
  
          if (!user) {
              throw new Error()
          }
  
          req.token = token
          req.user = user
          next()
  
      } catch (error) {
          res.status(401).send({error: 'Please authenticate.'})
      }
  }
  
  module.exports = auth
  </code></pre>
  
  <p>in src/routers/users.js</p>
  
  <pre><code>router.post('/login', async (req, res) =&gt; {
      try {
          const user = await User.findByCredentials(req.body.email, req.body.password)
          const token = await user.generateAuthToken()
          res.cookie('jwt',token, { httpOnly: true, secure: true, maxAge: 3600000 })
          res.redirect('/users/me')
      } catch (error) {
          res.status(400).send()
      }
  })
  </code></pre>
  
  <p>However, when I do console.log(document.cookie) in users/me it says undefined.</p>
  
  <p>Then I have the cookie-parser installed and import to app.js, and try to write this part in src/routers/users.js:</p>
  
  <pre><code>router.get('/me', auth, async (req, res) =&gt; {
      console.log('Cookies: ', req.cookies)
      try {
          res.render('me', {name: user.name})
      } catch (error) {
          res.status(500).send()
      }
  })
  </code></pre>
  
  <p>but this console doesn't print anything, probably cos I am getting error from auth.</p>
  
  <p>I also have a a js file attached to me page but I have no clue if I could write this way, probably wrong:</p>
  
  <pre><code>const userToken = document.cookie.jwt.token
  
  fetch('/users/me', {
      method: 'POST',
      headers: {
       'Authorization': 'Bearer ' + userToken
      }
  })
  .then(res =&gt; res.json())
  .then(data =&gt; { console.log(data) })
  .catch(err =&gt; { console.log(err) })
  </code></pre>
  
  <p>then in the Network / Headers, I have</p>
  
  <p>Request URL:</p>
  
  <p><a href="http://localhost:3000/users/login" rel="noreferrer">http://localhost:3000/users/login</a></p>
  
  <p>Request Method:</p>
  
  <p>POST</p>
  
  <p>Status Code:</p>
  
  <p>302 Found</p>
  
  <p>Remote Address:</p>
  
  <p>Referrer Policy:</p>
  
  <p>no-referrer-when-downgrade</p>
  
  <p>Response Headers</p>
  
  <p>Connection:</p>
  
  <p>keep-alive</p>
  
  <p>Content-Length:</p>
  
  <p>62</p>
  
  <p>Content-Type:</p>
  
  <p>text/html; charset=utf-8</p>
  
  <p>Date:</p>
  
  <p>Fri, 07 Jun 2019 18:41:47 GMT</p>
  
  <p>Location:</p>
  
  <p>/users/me</p>
  
  <p>Set-Cookie:</p>
  
  <p>jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1Y2Y2NjNlMTQwMTQyYjE0MzhmZTJjNDMiLCJpYXQiOjE1NTk5MzI5MDd9.T_P8O-j98cs9gtahTzspJjx1qNMSe3M5OAySyeH25fs; Max-Age=3600; Path=/; Expires=Fri, 07 Jun 2019 19:41:47 GMT; HttpOnly; Secure</p>
  
  <p>Vary:</p>
  
  <p>Accept</p>
  
  <p>X-Powered-By:</p>
  
  <p>Express</p>
  
  <p>There is no request cookies, only response cookies. I am not sure what those means...@_@</p>
  
  <p>I want to pass the jwt to successfully login and render the me page properly, how could I do that?</p>