<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: SubGame</title>
    <description>The latest articles on DEV Community by SubGame (@subgame).</description>
    <link>https://dev.to/subgame</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Forganization%2Fprofile_image%2F11624%2Fb184e417-7d38-4abb-b581-6af92457aeec.png</url>
      <title>DEV Community: SubGame</title>
      <link>https://dev.to/subgame</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/subgame"/>
    <language>en</language>
    <item>
      <title>Implementing JWT Authentication with FastAPI and Next.js</title>
      <dc:creator>SubGame</dc:creator>
      <pubDate>Wed, 24 Sep 2025 08:30:19 +0000</pubDate>
      <link>https://dev.to/subgame/implementing-jwt-authentication-with-fastapi-and-nextjs-50ni</link>
      <guid>https://dev.to/subgame/implementing-jwt-authentication-with-fastapi-and-nextjs-50ni</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Authentication is one of the most important aspects of modern web applications. Whether you’re building a small personal project or a large-scale marketplace, you need a secure and scalable way to handle user login, registration, and session management.&lt;/p&gt;

&lt;p&gt;In this article, I’ll share my experience implementing JWT-based authentication using FastAPI for the backend and Next.js for the frontend&lt;/p&gt;

&lt;h2&gt;
  
  
  Why JWT?
&lt;/h2&gt;

&lt;p&gt;JWT (JSON Web Token) is widely used because:&lt;br&gt;
It’s stateless (no need to store sessions in the backend).&lt;br&gt;
It works perfectly with APIs and SPAs.&lt;br&gt;
It can securely store claims about the user (like user ID, roles, permissions)&lt;/p&gt;
&lt;h2&gt;
  
  
  Backend: FastAPI Setup
&lt;/h2&gt;

&lt;p&gt;First, let’s create a simple FastAPI app with JWT authentication.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from datetime import datetime, timedelta

app = FastAPI()

SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

def create_access_token(data: dict, expires_delta: timedelta | None = None):
    to_encode = data.copy()
    expire = datetime.utcnow() + (expires_delta or timedelta(minutes=15))
    to_encode.update({"exp": expire})
    return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This function creates a JWT with an expiration time.&lt;/p&gt;

&lt;h2&gt;
  
  
  Frontend: Next.js Integration
&lt;/h2&gt;

&lt;p&gt;On the frontend, we’ll store the JWT securely and send it with each request.&lt;/p&gt;

&lt;p&gt;Here’s a simple example using fetch:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async function fetchUserProfile(token) {
  const res = await fetch("http://localhost:8000/users/me", {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  });

  if (!res.ok) {
    throw new Error("Failed to fetch user profile");
  }

  return res.json();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Best Practices
&lt;/h2&gt;

&lt;p&gt;Don’t store JWT in localStorage – use HTTP-only cookies when possible.&lt;br&gt;
Use refresh tokens for longer sessions.&lt;br&gt;
Rotate tokens regularly for better security.&lt;br&gt;
Handle expiration gracefully on the frontend.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Implementing JWT authentication with FastAPI and Next.js is straightforward, but security best practices must always be followed. By combining a fast Python backend with a modern React-based frontend, you can build secure and scalable applications with ease.&lt;/p&gt;

</description>
      <category>programming</category>
      <category>webdev</category>
      <category>fastapi</category>
      <category>nextjs</category>
    </item>
  </channel>
</rss>
