Skip to main content
Create server endpoints that generate ephemeral tokens for the assistant.

Framework Handlers

import { createAssistantTokenHandler } from "modifywithai/nextjs"

export const POST = createAssistantTokenHandler(options)

Options

CreateAssistantTokenHandlerOptions

OptionTypeRequiredDefaultDescription
appIdstringYesYour app ID from the dashboard
apiKeystringNoprocess.env.MWAI_API_KEYYour API key
apiUrlstringNohttps://api.modifywithai.comAPI endpoint
getEndUserId(request: Request) => Promise<string | null>NoAuto-generateFunction to get user ID

Request Body

The handler expects a POST request with JSON body:
interface TokenRequest {
    endUserId?: string        // Optional if getEndUserId is defined
    availableActions: ActionDefinition[]
    context?: object
}

Response

Success (200):
{
    "token": "ephemeral_token_here",
    "expiresAt": "2024-01-15T12:00:00Z"
}
Error (400/401/500):
{
    "error": "Error message"
}

Examples

Basic

import { createAssistantTokenHandler } from "modifywithai/nextjs"

export const POST = createAssistantTokenHandler({
    appId: "app_abc123",
})

With Authentication

import { createAssistantTokenHandler } from "modifywithai/nextjs"
import { auth } from "@/lib/auth"

export const POST = createAssistantTokenHandler({
    appId: "app_abc123",
    getEndUserId: async (request) => {
        const session = await auth()
        if (!session?.user?.id) {
            return null // Will auto-generate anonymous ID
        }
        return session.user.id
    },
})

Custom API URL

export const POST = createAssistantTokenHandler({
    appId: "app_abc123",
    apiUrl: "https://custom.api.endpoint.com",
})

User ID Handling

The handler determines the user ID in this order:
  1. getEndUserId function — If provided, calls it with the request
  2. Request body — Uses endUserId from the POST body
  3. Auto-generate — Creates an anonymous ID prefixed with autogen_
// Priority 1: getEndUserId function
getEndUserId: async (request) => {
    const session = await auth()
    return session?.user?.id ?? null
}

// Priority 2: Request body
// POST /api/mwai/token
// { "endUserId": "user_123", ... }

// Priority 3: Auto-generated
// "autogen_abc123xyz..."

Error Handling

The handler returns appropriate HTTP status codes:
StatusCause
200Success
400Invalid request body
401Invalid API key
500Server configuration error or API failure

Security

  • API key stays server-side — Never exposed to the browser
  • Tokens are short-lived — Expire in minutes
  • Tokens are scoped — Only valid for the specified app and user