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_URLenvironment 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.rolebefore protecting a page or API route
6️⃣ Systematic debugging workflow
- Check Keycloak logs for token issuance
- Verify token reaches the frontend session (use console.log)
- Log authentication object in client and server
- Inspect JWT for roles and expiration
- Check environment variables and redirect URLs
- 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
Post a Comment