Back to blog
Apr 21, 2025
2 min read

JWT Auth with Next.js SSR and React Query

Securely handle JWT in Next.js SSR app router with React Query

Table of Contents

Introduction

In this article, I will show you how to implement JWT authentication in a Next.js application using server-side rendering (SSR) and React Query. We will create a simple login page, a protected page, and handle JWT tokens securely.

And we won’t use any authentication libraries like NextAuth.js or Auth0. Instead, we will create our own authentication system using JWT. This will give us more control over the authentication process and allow us to customize it to our needs also can be used in any other framework like Express.js, FastAPI, etc.

Setting Up the Project

First, we need to set up a new Next.js project. You can do this using the Next.js CLI. If you don’t have it installed, you can do so by running the following command:

pnpm dlx create-next-app@latest next-jwt-ssr

Next, navigate to the project directory:

cd next-jwt-ssr

Now, we need to install the required dependencies. We will be using

pnpm add @tanstack/react-query axios