Skip to main content
Manages ephemeral token generation and refresh. Usually you don’t need this directly—useAssistant uses it internally.

Import

import { useAssistantToken } from "modifywithai"

Usage

const {
    token,
    expiresAt,
    isLoading,
    error,
    fetchToken,
} = useAssistantToken({
    tokenEndpoint: "/api/mwai/token",
    endUserId: "user_123",
    availableActions: [...],
})

Options

OptionTypeRequiredDefaultDescription
tokenEndpointstringNo/api/mwai/tokenToken generation endpoint
endUserIdstringNoAuto-generatedUser identifier
availableActionsActionDefinition[]YesAvailable actions
autoFetchbooleanNotrueFetch token on mount
refreshBuffernumberNo30000Refresh before expiry (ms)

Return Value

PropertyTypeDescription
tokenstring | nullCurrent ephemeral token
expiresAtDate | nullToken expiration time
isLoadingbooleanFetching token
errorError | nullFetch error
fetchToken() => Promise<void>Manually fetch token

Token Lifecycle

  1. Initial fetch — Token fetched on mount (if autoFetch: true)
  2. Auto refresh — New token fetched refreshBuffer ms before expiry
  3. Manual refresh — Call fetchToken() to force refresh

Example

function TokenStatus() {
    const { token, expiresAt, isLoading, error, fetchToken } = useAssistantToken({
        tokenEndpoint: "/api/mwai/token",
        availableActions: myActions,
    })

    if (isLoading) return <div>Loading...</div>
    if (error) return <div>Error: {error.message}</div>

    return (
        <div>
            <p>Token: {token ? "Active" : "None"}</p>
            <p>Expires: {expiresAt?.toLocaleTimeString()}</p>
            <button onClick={fetchToken}>Refresh</button>
        </div>
    )
}

When to Use

Use useAssistantToken directly when you need:
  • Token state without the chat interface
  • Custom token refresh logic
  • Multiple assistant instances sharing a token
For most cases, use useAssistant instead—it handles tokens automatically.