Appearance
Get Session API ​
Overview ​
The session.get.ts endpoint returns the current session status without exposing the authentication token. It reads the HTTP-only auth_token cookie to check if the user is authenticated.
Endpoint ​
Path: GET /api/auth/session
File: server/api/auth/session.get.ts
Request ​
No request body or parameters required.
Response ​
Authenticated User ​
typescript
{
authenticated: true
user: object | null // Parsed user data from auth_user cookie
hasToken: true
}Unauthenticated User ​
typescript
{
authenticated: false
user: null
}Error Response ​
typescript
{
authenticated: false
user: null
error?: string // "Failed to read session"
}Features ​
Cookie Reading ​
- Reads
auth_tokencookie (HTTP-only, not accessible to client) - Reads
auth_usercookie (if available) - Safely parses user data from cookie
User Data Parsing ​
If auth_user cookie exists, it attempts to parse it:
typescript
try {
user = JSON.parse(userCookie)
} catch {
user = null // Gracefully handle parse errors
}Usage ​
typescript
const { $api } = useNuxtApp()
// Check session status
const session = await $api('/api/auth/session')
if (session.authenticated) {
console.log('User is authenticated:', session.user)
} else {
console.log('User is not authenticated')
// Redirect to login
}Use Cases ​
SSR Authentication Check ​
typescript
// In middleware or page setup
const session = await $api('/api/auth/session')
if (!session.authenticated) {
return navigateTo('/login')
}Client-Side Auth State ​
typescript
// Check auth state on page load
onMounted(async () => {
const session = await $api('/api/auth/session')
if (session.authenticated) {
// User is logged in
authStore.setUser(session.user)
}
})Error Handling ​
The endpoint includes error handling:
typescript
try {
// Read cookies and return session
} catch (error: any) {
console.error('[Server] session.get error:', error)
return {
authenticated: false,
user: null,
error: 'Failed to read session'
}
}Security Considerations ​
- No Token Exposure: Token is never returned in response
- HTTP-Only Cookie: Token read from HTTP-only cookie (server-side only)
- Safe Parsing: User data parsing is wrapped in try-catch
- Error Handling: Errors don't expose sensitive information
Related Documentation ​
- Set Session - Store authentication token
- Clear Session - Clear authentication cookies
- Refresh User - Refresh user data