useServerSession()
useServerSession reads the ThunderID session from the current H3 event and returns the decoded ThunderIDSessionPayload, or null if no valid session exists.
Signature
useServerSession(event: H3Event): Promise<ThunderIDSessionPayload | null>
Import
import { useServerSession } from '@thunderid/nuxt/server'
Usage
In a Nuxt API Route
server/api/profile.get.ts
import { useServerSession } from '@thunderid/nuxt/server'
export default defineEventHandler(async (event) => {
const session = await useServerSession(event)
if (!session) {
throw createError({ statusCode: 401, statusMessage: 'Unauthorized' })
}
return { sub: session.sub, scopes: session.scopes }
})
In a Server Middleware
server/middleware/log.ts
import { useServerSession } from '@thunderid/nuxt/server'
export default defineEventHandler(async (event) => {
const session = await useServerSession(event)
if (session) {
console.log('Authenticated request from:', session.sub)
}
})
Return Value
Returns a Promise<ThunderIDSessionPayload | null>. Returns null when:
- No session cookie is present on the request
- The session cookie cannot be verified (invalid signature or expired)
ThunderIDSessionPayload
| Property | Type | Description |
|---|---|---|
sub | string | The user's subject identifier |
sessionId | string | The internal session ID |
accessToken | string | The current access token |
accessTokenExpiresAt | number | undefined | Access token expiry as a Unix timestamp |
refreshToken | string | undefined | The refresh token, if issued |
idToken | string | undefined | The ID token, if issued |
scopes | string | Space-separated list of granted scopes |
organizationId | string | undefined | The active organization ID, if any |
exp | number | JWT expiry timestamp |
iat | number | JWT issued-at timestamp |
Notes
- Use
requireServerSession()to throw a401automatically instead of handlingnullmanually. - The session payload is also available synchronously via
getThunderIDContext()if the SSR plugin has already run.