A New Collection of Thoughtful Learning Apps — Now Available on iOS & Android

Image
I’m excited to share a set of mobile apps I’ve recently completed and published on both the Google Play Store and the Apple App Store. These apps are designed with a simple goal in mind: to make meaningful, structured content more accessible, whether you’re studying theology or improving your English vocabulary. 📱 Now Available on Both Platforms All apps are live and available for download: Google Play Developer Page: https://play.google.com/store/apps/dev?id=5835943159853189043 Apple App Store Developer Page: https://apps.apple.com/ca/developer/q-z-l-corp/id1888794100 📖 Theology & Confession Study Apps For those interested in Reformed theology and classical Christian teachings, I’ve developed a series of apps that present foundational texts in a clean, focused reading format: The Belgic Confession Canons of Dort Heidelberg Catechism Westminster Shorter Catechism Each app is designed to provide a distraction-free experience, making it easier to read, reflect, and revisit these im...

Next.js + NextAuth.js — Debugging SSO Authentication and Token Issues

Next.js + NextAuth.js — Debugging SSO Authentication and Token Issues

After integrating Keycloak with NextAuth.js and managing sessions and roles, the most common challenge is debugging SSO issues in a frontend application. In this post, we’ll show systematic ways to troubleshoot authentication, token, and redirect issues in Next.js.


1️⃣ Common frontend SSO issues

  • Redirect loops: caused by mismatched callback URLs or session misconfiguration
  • 401 Unauthorized: access token missing or expired
  • 403 Forbidden: roles not mapped correctly
  • Session not found: JWT or cookie not persisted properly

2️⃣ Inspecting session objects

Always log your session object to verify tokens and roles:



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

export default function Dashboard() {

  const { data: session } = useSession();

  console.log("Session:", session);

  if (!session) return <p>Access denied</p>;

  return <div>Welcome {session.user.name}</div>;

}

Server-side logging can be done using getServerSession():



import { getServerSession } from "next-auth/next";

import { authOptions } from "./[...nextauth]";

export async function handler(req, res) {

  const session = await getServerSession(req, res, authOptions);

  console.log("Server-side session:", session);

}


3️⃣ Token expiration and refresh

Expired access tokens cause 401 errors. Use JWT callbacks to refresh tokens automatically:



async jwt({ token, account }) {

  if (account) {

    token.accessToken = account.access_token;

    token.expires = Date.now() + account.expires_in * 1000;

  }

  if (Date.now() > token.expires) {

    const refreshedTokens = await refreshAccessToken(token);

    token.accessToken = refreshedTokens.accessToken;

    token.expires = refreshedTokens.expires;

  }

  return token;

}

> Always check both client-side and server-side token validity for API calls.


4️⃣ Callback URL and redirect loop issues

  • Ensure your NEXTAUTH_URL environment variable matches your frontend URL
  • Keycloak redirect URI must match /api/auth/callback/keycloak
  • Debug by opening the network tab in the browser and inspecting redirects

5️⃣ Role mapping issues

403 errors often indicate that roles are missing or not correctly mapped in session:

  • Verify Keycloak mappers for client/realm roles
  • Check NextAuth.js JWT callback adds role to token
  • Log session.user.role before protecting a page or API route

6️⃣ Systematic debugging workflow

  1. Check Keycloak logs for token issuance
  2. Verify token reaches the frontend session (use console.log)
  3. Log authentication object in client and server
  4. Inspect JWT for roles and expiration
  5. Check environment variables and redirect URLs
  6. Enable DEBUG logs for NextAuth.js

Final thoughts

  • Frontend SSO issues usually come from tokens, roles, or redirect mismatches
  • Systematic logging on both client and server is key
  • Once tokens, roles, and session callbacks are verified, SSO works seamlessly
  • This completes the Next.js Frontend SSO series

Part of the Next.js Frontend SSO Series

❤️ Support This Blog


If this post helped you, you can support my writing with a small donation. Thank you for reading.


Comments

Popular Posts

2026 Begins: Choosing to Stay on the Path as a Blogger

Health Checks and Scaling Strategies for Next.js in Kubernetes