title: How to implement authentication in Next.js
body: <p>I am new to Next.js and I am struggling with the authentication system using jwt token. I want to know what is the best / standard way to store the jwt token and routing with the authentication system. I have been trying different approaches, from different tutorials/articles, but do not quite understand it. Here are what I have tried.</p>
  <ol>
  <li><p>When the user login, it sends username/password to a <strong>separated</strong> API server (ex. new project that handles backend stuff), the server will respond with the <code>access-token</code>, then in Next.js project, I set the cookie with that received token. In Next.js project, protected routes will be wrapped with a <code>withAuth</code> hoc, which will check for the token in a cookie. The problem with this approach is that it is vulnerable to XSS because the cookie has no httpOnly flag.</p>
  </li>
  <li><p>This is similar to 1.) but using <code>localStorage</code>, the problem is <code>access-token</code> could not be sent to the server on the first request. (This one I'm not sure, but in my understanding, in every HTTP request, I must stick my <code>access-token</code> manually, so what about requests that I have no control over? ex. first request or using <code>&lt;a&gt;</code> tag).</p>
  </li>
  <li><p>I wrote authentication backend inside Next.js server (custom express server). When the user login, the server will validate it and then set an <strong>httpOnly</strong> cookie. Then the problem is, with client-side routing (go to URL using Next.js Router), it could not check for token. For example, if a page is wrapped with <code>withAuth</code> hoc, but it cannot access the token inside cookies with javascript.</p>
  </li>
  </ol>
  <p>And I've seen a lot of people, in <code>getInitialProps</code> of the protected route, they only check for existence token in cookie / localStorage, then what if the token is being revoked or blacklisted, how do they handle it because they did not send the token to the server? Or do I have to send the token to the server in every client-side page change?</p>