Best way to store tokens in Next.js for authentication – Authentication

by
Ali Hasan
authorization csrf django-authentication jwt next.js

Quick Fix: Store tokens in the latest HTTP-only SameSite=strict cookies. Use a secondary CSRF token stored in memory or local storage for added security. Implement Content Security Policy to mitigate XSS vulnerabilities.

The Problem:

In a Next.js application, I want to securely store three tokens for authentication: accessToken (JWT with userId, email, and role), refreshToken (JWT with the same data), and csrfToken (32-digit random string). I’m considering storing the refreshToken in an HTTP-only cookie for protection against XSS attacks and storing the accessToken and csrfToken in a context provider for accessibility. Is this approach recommended, or are there better alternatives?

The Solutions:

Solution 1: Cookie-Based Storage

The suggested approach of storing the refreshToken in a secure HTTP-only cookie is recommended for the following reasons:

  • Protection from XSS attacks: HTTP-only cookies prevent JavaScript from accessing them, making them secure against XSS attacks.
  • Secure data retrieval: When the backend needs to access the refreshToken, it can retrieve it directly from the cookie.

For the accessToken and csrfToken, the use of a context provider to store them is acceptable, as it allows for easy accessibility across components and pages. However, it’s important to note that this approach stores the tokens in the client’s browser memory, which can be vulnerable to JavaScript-based attacks.

To mitigate these risks, consider implementing additional security measures, such as:

  • Enforce SameSite restrictions: Set the SameSite attribute on the HTTP-only cookie to "Strict" to prevent cross-site requests.
  • Secure the context provider: Ensure that the context provider is protected from XSS by following OWASP best practices, such as using a Content Security Policy (CSP).

Q&A

What is the best practice for storing tokens in Next.js for authentication?

HTTP-only SameSite=strict cookie for all OAuth tokens, secondary tokens in local storage.

Video Explanation:

The following video, titled "How to Manage Backend JWT Access Tokens in Next Auth and Next ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

In this video, we'll show you how to manage backend JWT in Next-auth and Next.js 13. We'll cover how to store and access backend JWT tokens ...