requireServerSession()
requireServerSession reads the ThunderID session from the current H3 event and returns the decoded <ProductName />SessionPayload. If no valid session exists, it throws an H3 error with status code 401.
Signature
requireServerSession(event: H3Event): Promise<ThunderIDSessionPayload>
Import
import { requireServerSession } from '@thunderid/nuxt/server'
Usage
In a Nuxt API Route
server/api/account.get.ts
import { requireServerSession } from '@thunderid/nuxt/server'
export default defineEventHandler(async (event) => {
const session = await requireServerSession(event)
// session is guaranteed to be defined here
return { sub: session.sub }
})
Fetching Data on Behalf of the User
server/api/orders.get.ts
import { requireServerSession } from '@thunderid/nuxt/server'
export default defineEventHandler(async (event) => {
const session = await requireServerSession(event)
const orders = await $fetch('https://api.example.com/orders', {
headers: { Authorization: `Bearer ${session.accessToken}` },
})
return orders
})
Return Value
Returns a Promise<ThunderIDSessionPayload>. See useServerSession() for the full payload shape.
Error Behavior
When no valid session is found, throws:
createError({ statusCode: 401, statusMessage: 'Unauthorized' })
Notes
- Use
useServerSession()when you want to handle the unauthenticated case yourself instead of throwing automatically. - If the access token in the session may be expired, use
getValidAccessToken()after callingrequireServerSessionto ensure you have a fresh token.