Skip to content

Set Session API ​

Overview ​

The set-session.post.ts endpoint securely stores the authentication token in an HTTP-only cookie. HTTP-only cookies cannot be accessed via JavaScript (document.cookie), providing protection against XSS attacks.

Endpoint ​

Path: POST /api/auth/set-session

File: server/api/auth/set-session.post.ts

Request Body ​

typescript
{
  token: string        // JWT access token (required)
  user?: object        // Optional user data for SSR
}

Response ​

typescript
{
  success: boolean
  message?: string     // "Session created successfully"
  error?: string      // Error message if validation fails
}

Features ​

  • Token stored in HTTP-only cookie (auth_token)
  • Cookie not accessible to client JavaScript
  • Prevents XSS token theft
typescript
{
  httpOnly: true,           // Not accessible to JavaScript
  secure: isProduction,    // HTTPS only in production
  sameSite: 'lax',         // CSRF protection
  path: '/',                // Available site-wide
  maxAge: 60 * 60 * 24 * 7 // 7 days
}

If user data is provided, a minimal user cookie is also set:

  • Cookie Name: auth_user
  • Not HTTP-Only: Client can read for SSR
  • Size Limit: Only set if < 3KB
  • Minimal Data: Only essential fields included

Allowed User Fields:

  • id, email, name
  • workspace_id, instance_id
  • brand_name, url
  • is_slider, is_backend_user, dealer_user_id
  • accessibleInstances (first instance only, minimal fields)

Error Handling ​

Validation Errors ​

typescript
// Missing token
{
  success: false,
  error: 'Token is required'
}

// Invalid request body
{
  success: false,
  error: 'Invalid request body'
}

If user data exceeds 3KB, a warning is logged but the request still succeeds (auth_token is the important cookie).

Usage ​

typescript
const { $api } = useNuxtApp()

// After successful login
const response = await $api('/api/auth/set-session', {
  method: 'POST',
  body: {
    token: accessToken,
    user: {
      id: user.id,
      email: user.email,
      name: user.name,
      workspace_id: user.workspace_id,
      // ... other minimal fields
    }
  }
})

if (response.success) {
  // Session created successfully
  // Token is now stored in HTTP-only cookie
}

Security Considerations ​

  1. XSS Protection: HTTP-only cookies prevent JavaScript access
  2. HTTPS Only: Secure flag enabled in production
  3. CSRF Protection: SameSite=lax prevents cross-site requests
  4. Token Validation: Token should be validated before calling this endpoint
  5. Minimal User Data: Only essential user data stored in cookie