title: How should I handle nuxt cookies expiration and workflow?
body: <p>I have made an authentication workflow for a project using a Nuxt frontend(universal mode) and an Apollo endpoint as backend.</p>
  
  <p>It is a mix of several examples I found and, with SSR, and since I do not fully anticipate what could go wrong, I wanted to make sure there is no red flag about how I proceed.</p>
  
  <p>On the backend, I use an express middleware to sign JWT auth tokens, check them, and return them in the Authorization header. Here is the middleware: </p>
  
  <pre class="lang-js prettyprint-override"><code>import jwt from 'jsonwebtoken';
  import { AuthenticationError } from 'apollo-server-express';
  
  export const getToken = payload =&gt; {
      return jwt.sign(payload, process.env.SEED, { expiresIn: process.env.EXPTOKEN });
  }
  export const checkToken = (req, res, next) =&gt; {
      const rawToken = req.headers["authorization"]
      if (rawToken) {
          try {
              const token = rawToken.substring(7)
              // Verify that the token is validated
              const { user, role } = jwt.verify(token, process.env.SEED);
  
              const newToken = getToken({ user, role });
  
              req.user = user;
              req.role = role;
              res.header("Access-Control-Allow-Origin", "*");
              res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
              res.set("Access-Control-Expose-Headers", "authorization");
              res.set("authorization", newToken);
  
          } catch (error) {
              if (error.name === "TokenExpiredError") {
                  res.set("Access-Control-Expose-Headers", "authorization");
                  res.set("authorization", false);
              }
              console.log("invalid token", error);
              return new AuthenticationError
              // Invalid Token
          }
      }
  
      next();
  }
  </code></pre>
  
  <p>Since there is a <a href="https://github.com/nuxt-community/apollo-module" rel="nofollow noreferrer">Nuxt-Apollo module</a>, I used its methods <a href="https://github.com/nuxt-community/apollo-module#authentication" rel="nofollow noreferrer">onLogin, onLogout and getToken</a> to store the JWT string in a cookie. As I understand it, SSR apps don't have the serverside local storage matching the client so they have to use cookies. Correct?</p>
  
  <p>Here is my nuxt middleware where I check the users credentials before allowing them to visit an auth route. Is is quite messy but it gets the job done, except for the commented part.</p>
  
  <pre class="lang-js prettyprint-override"><code>export default function ({ app, route, error, redirect }) {
    const hasToken = !!app.$apolloHelpers.getToken()
  
    // this part does not work
    /*   const tokenExpireDateTime = app.$cookies.nodeCookie.parse('cookie-name', 'expires')
      if (hasToken &amp;&amp; tokenExpireDateTime &lt; 0) {
        error({ statusCode: 403, message: 'Permission denied', description: 'Sorry, you are forbidden from accessing this page.' })
        app.$apolloHelpers.onLogout()
        return redirect('/login')
      }
     */
    if (!hasToken) {
      if (route.name === 'welcome-key') {
        // enrollment link route
      } else {
        if (route.name === 'home') {
          error({ errorCode: 403, message: 'You are not allowed to see this' })
  
          return redirect('/showcase')
        }
        if (!['login', 'forgot_password', 'reset_password-key'].includes(route.name)) {
          error({ errorCode: 403, message: 'You are not allowed to see this' })
  
          return redirect('/login')
        }
      }
    } else {
      if (['login', 'forgot_password', 'reset_password-key'].includes(route.name)) {
  
        redirect('/')
      }
    }
  }
  </code></pre>
  
  <p>I have one issue and several points of confusion.</p>
  
  <p>My issue is that I can't get the cookie <code>expires</code> value to redirect in the above nuxt middlware if it is necessary to login again because the JWT is expired. I used the piece of code mentioned <a href="https://github.com/nuxt-community/apollo-module/issues/302" rel="nofollow noreferrer">in this issue</a> as reference.</p>
  
  <p>With this issue, my confusion is about:</p>
  
  <ul>
  <li><p>The expires date on the cookie is set by the Nuxt-Apollo module, I expect, and I have to make it match the duration set on server (i.e. <code>process.env.EXPTOKEN</code> in the server middleware mentioned above), correct?</p></li>
  <li><p>That expiration time alone can easily be tempered with and the real security is the lack of a valid token in headers when a request is handled by my server middleware. Its use is for client-side detection and redirect of an expired token/cookie, and serverside prefetch of user related data during SSR. Right?</p></li>
  <li><p>The new token emitted by my express backend middleware is not taken into account in my frontend: it is not updating the cookie stored JWT and <code>expires</code> value client side. I mean that I can see the autorization header JWT string being updated in the response, but the cookie isn't. The following request still use the first JWT string. Am I supposed to update it at each roundtrip? What am I missing with the approach of the express middleware (that, as you can guess, I didn't write)</p></li>
  </ul>
  
  <p>Please help me understand better this workflow and how I could improve it. It tried to avoid as much as possible to make this question too broad, but if I can narrow it down more, feel free to suggest an edit.</p>