Next.js course ยท Module 7: Authentication and Authorization

User sessions and token management

16 min read ยท
In this lesson14

In previous modules, we covered the basics of authentication in Next.js and the implementation of login with external providers. Now we will delve into a key aspect of every authentication system: managing user sessions and tokens. Understanding these mechanisms is essential for building secure and efficient web applications.

Session management basics

A user session is a mechanism that allows the application to "remember" a logged-in user during navigation between pages and requests. In modern web applications, sessions are implemented in two main ways:

  1. Server-side sessions - the session identifier is stored in a cookie, and the session data on the server
  2. Stateless sessions (e.g. JWT) - all necessary information stored in the token, often in a cookie

In Next.js, especially in combination with NextAuth.js, we have access to both approaches.

Sessions in NextAuth.js

NextAuth.js offers two main session management strategies:

1. JWT strategy (default)

In this strategy, all session information is stored in a JWT (JSON Web Token) that is saved in a cookie:

// JWT strategy configuration in NextAuth.js
export const authOptions = {
  providers: [
    // Provider configuration...
  ],
  session: {
    strategy: "jwt",
    maxAge: 30 * 24 * 60 * 60, // 30 days in seconds
    updateAge: 24 * 60 * 60,    // 24 hours in seconds
  },
  jwt: {
    secret: process.env.NEXTAUTH_SECRET,
    // You can also use private/public keys instead of a simple secret
    // encryption: true, // Enables JWT encryption
    // signingKey: process.env.JWT_SIGNING_PRIVATE_KEY,
    // encryptionKey: process.env.JWT_ENCRYPTION_KEY,
  }
};

Pros:

  • Better scalability - the server does not need to store session data
  • Works well in a serverless environment
  • Simpler to implement

Cons:

  • Limited data size (tokens should not be too large)
  • More difficult to invalidate a token before expiration
  • Sensitive data is stored in the token (although encrypted)

2. Database strategy

In this strategy, only the session identifier is stored in the cookie, and the rest of the session data is stored in the database:

// Database strategy configuration in NextAuth.js
import { PrismaAdapter } from "@auth/prisma-adapter";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export const authOptions = {
  providers: [
    // Provider configuration...
  ],
  adapter: PrismaAdapter(prisma),
  session: {
    strategy: "database",
    maxAge: 30 * 24 * 60 * 60, // 30 days in seconds
    updateAge: 24 * 60 * 60,    // 24 hours in seconds
  }
};

Pros:

  • Easier session invalidation (can remove the entry from the database)
  • No limits on data amount
  • Safer for sensitive data

Cons:

  • Requires database access on every request
  • Slightly more difficult scalability
  • A database adapter is needed

JWT token structure in NextAuth.js

When we use the JWT strategy, NextAuth.js creates a token containing basic user information:

{
  "name": "John Doe",
  "email": "john@example.com",
  "sub": "cl5ab1gxk0001t8kgxs4t8j1h", // user identifier
  "iat": 1658309600, // token issued time
  "exp": 1660901600, // token expiration time
  "jti": "4b32c6a4-d2c5-4f1a-a2b3-5c84c1d94208" // unique token identifier
}

We can extend the token with additional data using the callback jwt:

export const authOptions = {
  //
  callbacks: {
    async jwt({ token, user, account }) {
      // On first login we have access to the user object
      if (user) {
        token.role = user.role;
        token.userId = user.id;
        token.provider = account?.provider;
      }

      // Here we can add token refresh logic
      // e.g. checking if the OAuth access token has not expired

      return token;
    },

    async session({ session, token }) {
      // Add data from the token to the session object (available on the client)
      if (session.user) {
        session.user.role = token.role;
        session.user.id = token.userId;
        session.user.provider = token.provider;
      }

      return session;
    }
  }
};

Configuring session cookies

By default, NextAuth.js configures session cookies according to best security practices, but we can customize these settings:

export const authOptions = {
  //
  cookies: {
    sessionToken: {
      name: `__Secure-next-auth.session-token`,
      options: {
        httpOnly: true,
        sameSite: "lax",
        path: "/",
        secure: true,  // Set to false during local testing without HTTPS
        maxAge: 30 * 24 * 60 * 60, // 30 days in seconds
      },
    },
    // You can also configure other cookies used by NextAuth.js
    callbackUrl: {
      name: `__Secure-next-auth.callback-url`,
      options: { /* ... */ },
    },
    csrfToken: {
      name: `__Host-next-auth.csrf-token`,
      options: { /* ... */ },
    },
  },
};

Client-side session management

In client components we can use the hook useSession to access session data and its status:

'use client';

import { useSession } from 'next-auth/react';

export default function ProfileComponent() {
  const { data: session, status } = useSession();

  if (status === 'loading') {
    return <p>Loading...</p>;
  }

  if (status === 'unauthenticated') {
    return <p>Access only for logged-in users</p>;
  }

  return (
    <div>
      <h1>Profile</h1>
      <p>Hello, {session.user.name}!</p>
      <p>Email: {session.user.email}</p>
      {session.user.role === 'admin' && (
        <p>You have administrator permissions</p>
      )}
    </div>
  );
}

We can also require a session using the option required:

'use client';

import { useSession } from 'next-auth/react';
import { redirect } from 'next/navigation';

export default function ProtectedComponent() {
  const { data: session, status } = useSession({
    required: true,
    onUnauthenticated() {
      redirect('/auth/login?callbackUrl=/profile');
    },
  });

  // When required is set, we don't need to check 'unauthenticated' status
  if (status === 'loading') {
    return <p>Loading...</p>;
  }

  return (
    <div>
      <h1>Protected content</h1>
      <p>This page is visible only to logged-in users.</p>
    </div>
  );
}

Server-side session management

In server components or Route Handlers we can use getServerSession to access session data:

// Server Component
import { getServerSession } from "next-auth/next";
import { redirect } from "next/navigation";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";

export default async function ServerProfilePage() {
  const session = await getServerSession(authOptions);

  if (!session) {
    redirect('/auth/login?callbackUrl=/profile');
  }

  return (
    <div>
      <h1>Profile (rendered on the server)</h1>
      <p>Hello, {session.user.name}!</p>
      <p>Email: {session.user.email}</p>
      {/* Content visible only to logged-in users */}
    </div>
  );
}

// Route Handler (API Route)
import { getServerSession } from "next-auth/next";
import { NextResponse } from "next/server";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";

export async function GET() {
  const session = await getServerSession(authOptions);

  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  // Fetch data specific to the logged-in user
  const userData = await fetchUserData(session.user.id);

  return NextResponse.json(userData);
}

Refresh tokens and OAuth access management

If we use OAuth providers, we may want to store and refresh access tokens to use the providers' APIs:

export const authOptions = {
  //
  callbacks: {
    async jwt({ token, user, account }) {
      // On first login, save access/refresh tokens
      if (account && user) {
        token.accessToken = account.access_token;
        token.refreshToken = account.refresh_token;
        token.accessTokenExpires = account.expires_at * 1000; // Convert to milliseconds
        token.userId = user.id;
        return token;
      }

      // If the access token has not expired, return it
      if (Date.now() < token.accessTokenExpires) {
        return token;
      }

      // If the access token has expired, refresh it
      return refreshAccessToken(token);
    },

    async session({ session, token }) {
      // Pass the access token to the client (but not the refresh token!)
      session.accessToken = token.accessToken;
      session.user.id = token.userId;

      return session;
    },
  },
};

async function refreshAccessToken(token) {
  try {
    // Example of refreshing a Google OAuth token
    const url = "https://oauth2.googleapis.com/token";
    const response = await fetch(url, {
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      method: "POST",
      body: new URLSearchParams({
        client_id: process.env.GOOGLE_CLIENT_ID,
        client_secret: process.env.GOOGLE_CLIENT_SECRET,
        grant_type: "refresh_token",
        refresh_token: token.refreshToken,
      }),
    });

    const refreshedTokens = await response.json();

    if (!response.ok) {
      throw refreshedTokens;
    }

    return {
      ...token,
      accessToken: refreshedTokens.access_token,
      accessTokenExpires: Date.now() + refreshedTokens.expires_in * 1000,
      // Keep the refresh token unless we received a new one
      refreshToken: refreshedTokens.refresh_token ?? token.refreshToken,
    };
  } catch (error) {
    console.error("Error refreshing access token", error);
    // The refresh token may have expired, the user will need to log in again
    return {
      ...token,
      error: "RefreshAccessTokenError",
    };
  }
}

Logging out and session invalidation

NextAuth.js provides the function signOut() for logging out:

'use client';

import { signOut } from 'next-auth/react';

export function LogoutButton() {
  return (
    <button
      onClick={() => signOut({ callbackUrl: '/' })}
      className="bg-red-500 text-white px-4 py-2 rounded"
    >
      Log out
    </button>
  );
}

In the case of the database-based strategy, we can manually invalidate a session by removing it from the database:

// app/api/auth/invalidate-sessions/route.ts
import { NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { prisma } from "@/lib/prisma";

export async function POST(request: Request) {
  const session = await getServerSession(authOptions);

  if (!session || session.user.role !== 'admin') {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { userId } = await request.json();

  // Remove all sessions of a user with the given ID
  await prisma.session.deleteMany({
    where: {
      userId,
    },
  });

  return NextResponse.json({ success: true });
}

In the case of the JWT strategy, this is more difficult because tokens are self-contained. However, we can implement a token "blacklist" or a secret rotation mechanism:

// Blacklist implementation for the JWT token
const revokedTokens = new Set();

export const authOptions = {
  //
  callbacks: {
    async jwt({ token }) {
      // Check if the token is on the blacklist
      if (revokedTokens.has(token.jti)) {
        return null; // Token invalidated
      }
      return token;
    },
  },
  events: {
    async signOut({ token }) {
      // Add the token to the blacklist on logout
      if (token?.jti) {
        revokedTokens.add(token.jti);
      }
    },
  },
};

This simple solution only works for a single server. For multiple servers or serverless solutions, we would need to use a shared data store (e.g. Redis) to store the list of invalidated tokens.

Inactivity detection and automatic logout

We can implement a mechanism to detect user inactivity and automatic logout:

'use client';

import { useSession, signOut } from 'next-auth/react';
import { useEffect, useState } from 'react';

export function InactivityDetector({ timeoutMinutes = 30 }) {
  const { data: session } = useSession();

  useEffect(() => {
    if (!session) return;

    let timeout;
    const timeoutMs = timeoutMinutes * 60 * 1000;

    const resetTimeout = () => {
      if (timeout) clearTimeout(timeout);
      timeout = setTimeout(() => {
        signOut({ callbackUrl: '/auth/login?timeout=true' });
      }, timeoutMs);
    };

    // Reset the timer on every user activity
    const events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'];

    // Set the initial timer
    resetTimeout();

    // Add event listeners
    events.forEach(event => {
      window.addEventListener(event, resetTimeout);
    });

    return () => {
      // Clear timer and listeners on unmount
      if (timeout) clearTimeout(timeout);
      events.forEach(event => {
        window.removeEventListener(event, resetTimeout);
      });
    };
  }, [session, timeoutMinutes]);

  // The component does not render anything visible
  return null;
}

Then you can add this component to the main application layout:

// app/layout.tsx
import { Providers } from "./providers";
import { InactivityDetector } from "@/components/InactivityDetector";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="pl">
      <body>
        <Providers>
          {children}
          <InactivityDetector timeoutMinutes={30} />
        </Providers>
      </body>
    </html>
  );
}

Handling multiple devices and sessions

If we use the database-based strategy, we can implement management of multiple sessions for the same user, allowing them to review active sessions and log out from specific devices:

// app/settings/sessions/page.tsx
import { getServerSession } from "next-auth/next";
import { redirect } from "next/navigation";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { prisma } from "@/lib/prisma";
import { SessionList } from "./SessionList";

export default async function SessionsPage() {
  const session = await getServerSession(authOptions);

  if (!session) {
    redirect('/auth/login?callbackUrl=/settings/sessions');
  }

  // Fetch all active user sessions
  const userSessions = await prisma.session.findMany({
    where: {
      userId: session.user.id,
      expires: {
        gt: new Date(), // Only active sessions
      },
    },
    orderBy: {
      expires: 'desc',
    },
  });

  // Mark the current session
  const currentSessionToken = session.user.sessionToken; // You must adjust to have access to the token
  const enhancedSessions = userSessions.map(s => ({
    ...s,
    isCurrent: s.sessionToken === currentSessionToken,
  }));

  return (
    <div className="max-w-4xl mx-auto p-6">
      <h1 className="text-2xl font-bold mb-6">Active sessions</h1>
      <SessionList sessions={enhancedSessions} currentSessionId={session.user.id} />
    </div>
  );
}

// app/settings/sessions/SessionList.tsx (client component)
'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';

export function SessionList({ sessions, currentSessionId }) {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
  const router = useRouter();

  const handleRevokeSession = async (sessionToken) => {
    if (confirm('Are you sure you want to log out this device?')) {
      setIsLoading(true);
      setError('');

      try {
        const response = await fetch('/api/auth/revoke-session', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ sessionToken }),
        });

        if (!response.ok) {
          throw new Error('Failed to invalidate session');
        }

        // Refresh the page
        router.refresh();
      } catch (e) {
        setError(e.message);
      } finally {
        setIsLoading(false);
      }
    }
  };

  const formatDate = (dateString) => {
    return new Date(dateString).toLocaleString();
  };

  return (
    <div>
      {error && (
        <div className="p-4 mb-4 text-sm text-red-700 bg-red-100 rounded-lg">
          {error}
        </div>
      )}

      <div className="overflow-x-auto">
        <table className="min-w-full divide-y divide-gray-200">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Device</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Last activity</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Expires</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
            </tr>
          </thead>
          <tbody className="bg-white divide-y divide-gray-200">
            {sessions.map((session) => (
              <tr key={session.id}>
                <td className="px-6 py-4 whitespace-nowrap">
                  <div className="flex items-center">
                    <div className="ml-4">
                      <div className="text-sm font-medium text-gray-900">
                        {session.isCurrent ? 'Current device' : 'Other device'}
                      </div>
                    </div>
                  </div>
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <div className="text-sm text-gray-900">{formatDate(session.updatedAt)}</div>
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <div className="text-sm text-gray-900">{formatDate(session.expires)}</div>
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                  <button
                    onClick={() => handleRevokeSession(session.sessionToken)}
                    disabled={isLoading || session.isCurrent}
                    className={`text-red-600 hover:text-red-900 ${(isLoading || session.isCurrent) ? 'opacity-50 cursor-not-allowed' : ''}`}
                  >
                    {session.isCurrent ? 'Current session' : 'Log out'}
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// app/api/auth/revoke-session/route.ts
import { NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { prisma } from "@/lib/prisma";

export async function POST(request: Request) {
  const session = await getServerSession(authOptions);

  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { sessionToken } = await request.json();

  // Find the session, making sure it belongs to the logged-in user
  const sessionToRevoke = await prisma.session.findFirst({
    where: {
      sessionToken,
      userId: session.user.id,
    },
  });

  if (!sessionToRevoke) {
    return NextResponse.json(
      { error: "Session not found or not owned by current user" },
      { status: 404 }
    );
  }

  // Remove the session
  await prisma.session.delete({
    where: {
      id: sessionToRevoke.id,
    },
  });

  return NextResponse.json({ success: true });
}

Token and session security

When implementing session and token management, keep in mind several key security aspects:

  1. Use strong secrets - ensure that NEXTAUTH_SECRET is a long, random string of characters

  2. Secure cookies - use flags:

    • HttpOnly: prevents JavaScript access to the cookie
    • Secure: requires HTTPS
    • SameSite: protects against CSRF attacks
  3. Set appropriate lifetime - tokens/sessions should not be valid for too long a period

  4. Limit data in the token - the JWT token should contain minimum necessary information

  5. Implement session revocation - allow users to log out from all devices

  6. Monitor suspicious activity - detect repeated login attempts and unusual access patterns

  7. Secret rotation - periodically change secrets used to sign tokens

Session and token tests

Tests are a key element in ensuring the reliability of session and token mechanisms. Here is an example unit test for token refresh functionality:

// __tests__/refreshToken.test.ts
import { refreshAccessToken } from '@/lib/auth';
import fetchMock from 'jest-fetch-mock';

fetchMock.enableMocks();

beforeEach(() => {
  fetchMock.resetMocks();
});

describe('refreshAccessToken', () => {
  it('should refresh the token successfully', async () => {
    // Prepare a mock response from the OAuth server
    fetchMock.mockResponseOnce(JSON.stringify({
      access_token: 'new_access_token',
      expires_in: 3600
    }));

    const originalToken = {
      accessToken: 'old_access_token',
      refreshToken: 'refresh_token',
      accessTokenExpires: Date.now() - 1000, // Expired token
    };

    const refreshedToken = await refreshAccessToken(originalToken);

    expect(refreshedToken.accessToken).toBe('new_access_token');
    expect(refreshedToken.refreshToken).toBe('refresh_token'); // Should keep the old refresh token
    expect(refreshedToken.accessTokenExpires).toBeGreaterThan(Date.now());
    expect(fetchMock).toHaveBeenCalledTimes(1);
  });

  it('should handle refresh token errors', async () => {
    // Simulate refresh error
    fetchMock.mockRejectOnce(new Error('Failed to refresh token'));

    const originalToken = {
      accessToken: 'old_access_token',
      refreshToken: 'refresh_token',
      accessTokenExpires: Date.now() - 1000,
    };

    const result = await refreshAccessToken(originalToken);

    expect(result.error).toBe('RefreshAccessTokenError');
    expect(result.accessToken).toBe('old_access_token'); // Should keep the old token
  });
});

Good practices in the context of Next.js App Router

In the Next.js App Router architecture, it is important to follow these principles when implementing authentication:

  1. Use middleware to protect entire directories or route groups:
// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getToken } from "next-auth/jwt";

export async function middleware(request: NextRequest) {
  const token = await getToken({ req: request });

  // Check if the user has access to the requested page
  if (!token) {
    const url = new URL('/auth/login', request.url);
    url.searchParams.set('callbackUrl', request.nextUrl.pathname);
    return NextResponse.redirect(url);
  }

  // Checking permissions based on path and role
  if (request.nextUrl.pathname.startsWith('/admin') && token.role !== 'admin') {
    return NextResponse.redirect(new URL('/dashboard', request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: [
    '/dashboard/:path*',
    '/settings/:path*',
    '/admin/:path*',
    '/api/protected/:path*'
  ],
};
  1. Use Server Components where possible, to reduce the amount of client-side JavaScript code and improve the security of sensitive operations:
// app/admin/dashboard/page.tsx (Server Component)
import { getServerSession } from "next-auth/next";
import { redirect } from "next/navigation";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";

export default async function AdminDashboard() {
  const session = await getServerSession(authOptions);

  if (!session || session.user.role !== 'admin') {
    redirect('/');
  }

  // Fetch administrative data directly on the server
  // without exposing API keys or other sensitive information to the client
  const adminData = await fetchAdminData();

  return (
    <div>
      <h1>Administrator panel</h1>
      {/* Render administrator data */}
    </div>
  );
}
  1. Use Route Handlers to secure API:
// app/api/protected/user-data/route.ts
import { getServerSession } from "next-auth/next";
import { NextResponse } from "next/server";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";

export async function GET() {
  const session = await getServerSession(authOptions);

  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  // Perform protected operations
  const userData = await fetchUserData(session.user.id);

  // Return data without sensitive information
  const sanitizedData = sanitizeUserData(userData);

  return NextResponse.json(sanitizedData);
}

Summary

In this module, we discussed in detail how to manage user sessions and tokens in Next.js applications:

  1. We learned about different session strategies in NextAuth.js - JWT and database-based
  2. We learned how to extend tokens and sessions with our own data
  3. We understood how to secure cookies and configure session parameters
  4. We learned about token refresh mechanisms for OAuth providers
  5. We implemented multi-session management and logout from specific devices
  6. We discussed best security practices for tokens and sessions

Proper session and token management is a key aspect of web application security. A well-designed authentication system not only protects user data but also ensures a good user experience, allowing easy login, logout, and access management from different devices.

In the next module, we will deal with implementing a system of roles and permissions that will allow for more granular management of user access to different application features.

Code for this lesson: App.tsx
import React, { useState, useEffect } from 'react';

// Demo: User sessions and token management
interface SessionInfo {
  id: string;
  createdAt: string;
  ipAddress: string;
  userAgent: string;
}

function SessionTokenDemo() {
  const [activeTab, setActiveTab] = useState<'session' | 'jwt' | 'refresh'>('session');
  const [sessions, setSessions] = useState<SessionInfo[]>([]);
  const [jwtPayload, setJwtPayload] = useState<any>(null);
  const [tokenExpiry, setTokenExpiry] = useState(100);
  const [isRefreshing, setIsRefreshing] = useState(false);

  useEffect(() => {
    if (jwtPayload && tokenExpiry > 0) {
      const timer = setInterval(() => {
        setTokenExpiry(prev => prev <= 1 ? 0 : prev - 1);
      }, 100);
      return () => clearInterval(timer);
    }
  }, [jwtPayload, tokenExpiry]);

  const createSession = () => {
    const session: SessionInfo = {
      id: 'ses_' + Math.random().toString(36).substr(2, 9),
      createdAt: new Date().toLocaleTimeString(),
      ipAddress: '192.168.1.' + Math.floor(Math.random() * 255),
      userAgent: ['Chrome/120', 'Firefox/121', 'Safari/17'][Math.floor(Math.random() * 3)],
    };
    setSessions(prev => [...prev, session]);
  };

  const generateJWT = () => {
    const now = Math.floor(Date.now() / 1000);
    setJwtPayload({ sub: 'user_001', email: 'jan@quantum.city', role: 'admin', iat: now, exp: now + 3600 });
    setTokenExpiry(100);
  };

  const refreshToken = async () => {
    setIsRefreshing(true);
    await new Promise(r => setTimeout(r, 800));
    const now = Math.floor(Date.now() / 1000);
    setJwtPayload((prev: any) => prev ? { ...prev, iat: now, exp: now + 3600 } : null);
    setTokenExpiry(100);
    setIsRefreshing(false);
  };

  return (
    <div style={{ background: '#0f0f23', minHeight: '100vh', padding: '20px', color: '#e0e0e0', fontFamily: 'system-ui' }}>
      <h1 style={{ color: '#64ffda', marginBottom: '8px' }}>Sessions and Tokens</h1>
      <p style={{ color: '#8892b0', marginBottom: '24px' }}>Managing user sessions and JWT tokens</p>

      <div style={{ display: 'flex', gap: '8px', marginBottom: '24px' }}>
        {[{ id: 'session' as const, label: 'Sessions' }, { id: 'jwt' as const, label: 'JWT' }, { id: 'refresh' as const, label: 'Refresh' }].map(tab => (
          <button key={tab.id} onClick={() => setActiveTab(tab.id)} style={{
            padding: '10px 20px', borderRadius: '8px', border: 'none', cursor: 'pointer',
            background: activeTab === tab.id ? '#64ffda' : '#1a1a2e', color: activeTab === tab.id ? '#0f0f23' : '#8892b0', fontWeight: 'bold',
          }}>
            {tab.label}
          </button>
        ))}
      </div>

      {activeTab === 'session' && (
        <div>
          <button onClick={createSession} style={{ padding: '10px 20px', borderRadius: '8px', background: '#7c3aed', color: '#fff', border: 'none', cursor: 'pointer', marginBottom: '16px' }}>+ Create session</button>
          {sessions.map(s => (
            <div key={s.id} style={{ background: '#1a1a2e', padding: '12px', borderRadius: '8px', border: '1px solid #333', marginBottom: '8px', display: 'flex', justifyContent: 'space-between' }}>
              <div>
                <code style={{ color: '#64ffda' }}>{s.id}</code>
                <div style={{ fontSize: '12px', color: '#8892b0' }}>IP: {s.ipAddress} | UA: {s.userAgent} | {s.createdAt}</div>
              </div>
              <button onClick={() => setSessions(prev => prev.filter(x => x.id !== s.id))} style={{ background: '#ef4444', color: '#fff', border: 'none', borderRadius: '4px', padding: '4px 8px', cursor: 'pointer', fontSize: '12px' }}>Revoke</button>
            </div>
          ))}
          {sessions.length === 0 && <p style={{ color: '#555' }}>No sessions</p>}
        </div>
      )}

      {activeTab === 'jwt' && (
        <div>
          <button onClick={generateJWT} style={{ padding: '10px 20px', borderRadius: '8px', background: '#f59e0b', color: '#0f0f23', border: 'none', cursor: 'pointer', marginBottom: '16px', fontWeight: 'bold' }}>Generate JWT</button>
          {jwtPayload && (
            <div style={{ background: '#1a1a2e', padding: '16px', borderRadius: '8px', border: '1px solid #333' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px' }}>
                <span>Token:</span>
                <div style={{ flex: 1, height: '8px', background: '#333', borderRadius: '4px', overflow: 'hidden' }}>
                  <div style={{ width: tokenExpiry + '%', height: '100%', background: tokenExpiry > 30 ? '#10b981' : tokenExpiry > 10 ? '#f59e0b' : '#ef4444', transition: 'width 0.1s' }} />
                </div>
                <span style={{ color: tokenExpiry > 30 ? '#10b981' : '#ef4444' }}>{tokenExpiry}%</span>
              </div>
              {tokenExpiry === 0 && <div style={{ color: '#ef4444', fontWeight: 'bold', marginBottom: '8px' }}>Token expired!</div>}
              <pre style={{ background: '#0f0f23', padding: '12px', borderRadius: '6px', fontSize: '13px', overflow: 'auto' }}>{JSON.stringify(jwtPayload, null, 2)}</pre>
            </div>
          )}
        </div>
      )}

      {activeTab === 'refresh' && (
        <div style={{ background: '#1a1a2e', padding: '24px', borderRadius: '8px', border: '1px solid #333' }}>
          <h3 style={{ color: '#64ffda', marginTop: 0 }}>Refresh Token Flow</h3>
          {['Access token expires', 'Client sends refresh token', 'Server verifies refresh token', 'New access + refresh token'].map((step, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '12px' }}>
              <div style={{ width: '32px', height: '32px', borderRadius: '50%', background: '#7c3aed', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '14px', fontWeight: 'bold', flexShrink: 0 }}>{i + 1}</div>
              <span>{step}</span>
            </div>
          ))}
          <button onClick={refreshToken} disabled={isRefreshing} style={{ marginTop: '12px', padding: '10px 20px', borderRadius: '8px', background: isRefreshing ? '#333' : '#7c3aed', color: '#fff', border: 'none', cursor: isRefreshing ? 'default' : 'pointer' }}>
            {isRefreshing ? 'Refreshing...' : 'Simulate Refresh'}
          </button>
        </div>
      )}
    </div>
  );
}

export default SessionTokenDemo;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. OAuth 2.0 is:

  2. 2. PKCE (Proof Key for Code Exchange) is used in:

Hands-on tasks in the game

  • Code editor

    Create a ProtectedRoute component using useSession to guard against unauthorized access

  • Code editor

    Create a credentials provider in NextAuth with email/password authentication and bcrypt hashing

  1. QuestionOAuth 2.0 is:
  2. QuestionPKCE (Proof Key for Code Exchange) is used in:
  3. Coding taskPractice: Create a ProtectedRoute component using
  4. Coding taskPractice: Create a credentials provider in NextAuth with

Useful articles