인사이트
2025-07-06
This post walks through a clean and effective way to integrate Keycloak with Auth.js in a Next.js app, focusing on keeping session data up-to-date using jwt-decode and unstable_update.
Session Update on Auth.js(v5) with Keycloak
by
김김동현
1. Overview
When using Keycloak with Auth.js, there are times you need to update the session — for example, after updating a user profile or when you want to fetch user attributes stored in Keycloak that apply across all devices.
However, reloading user information in Auth.js isn’t straightforward. Even if you enable token refresh using the Auth.js guide Integrating with third-party backends, the session update process doesn't work out-of-the-box. The Keycloak token refresh endpoint only returns tokens and token's info, not full profile info.
Let’s walk through a simple solution using the jwt-decode
package to seamlessly update session data.
2. auth.ts
Here is the jwt
callback setup in my Auth.js configuration:
Here, when trigger === "update"
, we manually invoke a token refresh using the refreshAccessToken
helper.
The actual token refresh logic:
By decoding the new id_token
or access_token
using jwt-decode
, we can extract all claims (including updated user attributes) and merge them into the token.
3. Triggering an Update
While you could use the update
function from the useSession
hook on the client, we’ll demonstrate a more universal approach using a simple route handler(especially in Auth.js v5):
Place this route at /api/user/update
. Now you can trigger a refresh from anywhere:
No extra parameters or type definitions needed — it just works. The new token will be reloaded with fresh data from Keycloak.
4. Conclusion
This lightweight approach makes it simple to tightly integrate Keycloak with Auth.js while keeping session data in sync. By refreshing the token and decoding it with jwt-decode
, we gain full control over when and how session data is updated — both client-side and server-side.
Use this pattern to ensure your app always reflects the latest user state from Keycloak — securely, reliably, and with minimal code.
- Keycloak token refresh
- Auth.js session update
- NextAuth Keycloak integration
- jwt-decode
- refresh access token
- Keycloak user attributes
- OAuth2 OIDC
- session sync
글 공유하기