skip to Main Content

I am facing an issue with storing a JWT token in Next.js 14. I want to load a page using SSR, but localStorage is not supported in server-side components. My scenario is as follows: after logging in, the backend responds with a JWT token, which I currently store in localStorage. However, localStorage is not accessible in server-side components. How can I properly store the JWT token in this case.

I trying to using cookies to store it.

3

Answers


  1. Yes, you should use the cookies as you can have access to them in a server side environment but you should be aware with it’s security flaws on cross-site-scripting attacks, so consider using the http only property on your cookie so the client side of JavaScript can’t access it, and there is another solution with higher security you can use session cookies to store an id referencing the access token on the server so in that case you should take the id stored in the cookie and query the actual token in this way your tokens are secured even if the id was stolen.

    Login or Signup to reply.
  2. For your purposes, I suggest you use the next-auth npm package. NextAuth.js is a complete open-source authentication solution for Next.js applications. It provides a way to integrate authentication mechanisms into Next.js apps, supporting various providers and strategies.

    It also has SSR and CSR access for the JWTs.

    https://www.youtube.com/watch?v=bMYZSi_LZ2w&pp=ygUJbmV4dC1hdXRo good video to watch.

    using this, you won’t have to worry about handling the auth flows manually.

    Login or Signup to reply.
  3. The first question you should ask is how customizable do I need my auth solution to be? Do I need to self host? Do I want it to be managed? Am I using a big cloud provider that already has an auth service. This chart will help you choose:

    A flow chart for choosing an auth solution

    However, If you still think you need custom auth, the best way to store JWTs is by using cookies in layout.tsx .

    
    const checkAuth = () => {
       if(cookies.get("jwt")) {
          return jwtVerify(cookies.get("jwt"))
       }
       return false;
    }
    
    export default Layout({children}: {children: React.ReactNode}) {
       return (
          <main>
            {isSignedIn ? children : <p>Please sign in...</p>}
          </main>
       )
    }
    

    The above example doesn’t use any particular library it is just a reference for how to implement such functionality.

    But to reiterate it is almost always better to use a third party auth solution.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search