Skip to content

SDK Reference

Generated from src/index.ts.

All exports (alphabetical)
ExportKindSourceDescription
ApiErrorclasssrc/api/error.tsHTTP error thrown by Snapshot API clients for non-success responses.
AssetRefinterfacesrc/community/types.tsReference to an uploaded asset (image, audio, video, file).
AUTH_QUERY_KEYvariablesrc/routing/loaders.tsStable query key under which useUser() and the route guards cache the authenticated user. Exported so apps can invalidate, seed, or read the cache directly (e.g. after a profile update or server-side state change that should force a refresh).
AuthContractinterfacesrc/auth/contract.tsFull auth contract used by createSnapshot() to build auth URLs and requests.
AuthContractConfiginterfacesrc/auth/contract.tsPartial auth contract overrides.
AuthEndpointsinterfacesrc/auth/contract.tsRelative auth endpoint paths used by Snapshot’s built-in auth hooks.
AuthErrorConfiginterfacesrc/types.tsOptional configuration for auth error formatting.
AuthErrorContexttypealiassrc/types.tsAuth UI contexts that can provide custom error messaging.
AuthHeadersinterfacesrc/auth/contract.tsHeader names Snapshot sends for session and CSRF-aware auth requests.
AuthUserinterfacesrc/types.tsMinimal authenticated user shape returned by Snapshot auth hooks.
BanBodyinterfacesrc/community/types.tsRequest body for creating a user ban.
BanCheckResponseinterfacesrc/community/types.tsResult returned when checking whether a user is banned.
BanResponseinterfacesrc/community/types.tsBan record returned by moderation endpoints.
communityContractvariablesrc/community/contract.tsBuilt-in route contract for Snapshot community APIs.
CommunityHookstypealiassrc/community/hooks.tsHook surface returned by createCommunityHooks().
communityKeysvariablesrc/community/hooks.tsQuery key helpers for the community API surface. SSR loaders can seed the QueryClient under these keys so loader-seeded keys and hook-read keys stay aligned.
CommunityNotificationinterfacesrc/types.tsNormalized notification shape used by useCommunityNotifications().
CommunityNotificationTypetypealiassrc/types.tsCommunity notification types surfaced by Snapshot’s notification helpers.
CommunitySearchParamsinterfacesrc/community/types.tsSearch parameters accepted by the community search hooks.
ContactDatainterfacesrc/community/types.tsContact card sidecar.
ContainerResponseinterfacesrc/community/types.tsCommunity container returned by the community API.
ContentFormattypealiassrc/community/types.tsStorage format hint for body text.
createAuthErrorFormatterfunctionsrc/auth/error-format.tsCreate a reusable auth error formatter with shared formatting rules.
CreateContainerBodyinterfacesrc/community/types.tsRequest body for creating a community container.
CreateReplyBodyinterfacesrc/community/types.tsRequest body for creating a reply.
CreateReplyBodyExtendedinterfacesrc/community/types.tsExtended create-reply body — accepts optional sidecar fields the server may overwrite with parsed content metadata.
createSnapshotfunctionsrc/create-snapshot.tsxCreate a per-instance Snapshot runtime from code-first bootstrap config. Builds per-instance API, auth, realtime, community, and webhook hooks from explicit TypeScript config.
CreateThreadBodyinterfacesrc/community/types.tsRequest body for creating a thread in a container.
CreateThreadBodyExtendedinterfacesrc/community/types.tsRequest body for creating a thread (extended). Optional sidecar fields can be set client-side; the server may overwrite them with parsed content metadata when its parseBody middleware runs. Treat client-supplied values as advisory.
CreateWebhookEndpointBodyinterfacesrc/webhooks/types.tsRequest body for creating a webhook endpoint.
defaultContractfunctionsrc/auth/contract.tsCreate the built-in auth contract for a given API base URL.
DeleteAccountBodyinterfacesrc/types.tsRequest body for deleting the current account.
EmbedDatainterfacesrc/community/types.tsResolved link-preview metadata for a URL referenced in content.
ForgotPasswordBodyinterfacesrc/types.tsRequest body for the forgot-password endpoint.
formatAuthErrorfunctionsrc/auth/error-format.tsFormat a raw auth ApiError into the message shown to application code.
getRegisteredClientfunctionsrc/api/client.tsLook up a previously registered custom client factory.
isMfaChallengefunctionsrc/types.tsNarrow a login result to the MFA challenge branch.
ListParamsinterfacesrc/community/types.tsShared page-based pagination parameters.
ListWebhookDeliveriesParamsinterfacesrc/webhooks/types.tsParameters for listing deliveries for a single webhook endpoint.
ListWebhookEndpointsParamsinterfacesrc/webhooks/types.tsPage-based pagination parameters for listing webhook endpoints.
LocationDatainterfacesrc/community/types.tsGeo coordinate sidecar.
LoginBodyinterfacesrc/types.tsCredentials posted to the login endpoint.
LoginResponseinterfacesrc/types.tsRaw login response shape from slingshot (includes MFA fields)
LoginResulttypealiassrc/types.tsuseLogin resolves to either a user or an MFA challenge
LoginVarstypealiassrc/types.tsLogin variables accepted by useLogin().
LogoutVarsinterfacesrc/types.tsLogout options accepted by useLogout().
mergeContractfunctionsrc/auth/contract.tsMerge a partial auth contract override with the built-in defaults.
MfaChallengeinterfacesrc/types.tsReturned by useLogin when mfaRequired is true
MfaDisableBodyinterfacesrc/types.tsRequest body for disabling MFA.
MfaEmailOtpDisableBodyinterfacesrc/types.tsRequest body for disabling email OTP MFA.
MfaEmailOtpEnableResponseinterfacesrc/types.tsResponse returned when email OTP MFA setup begins.
MfaEmailOtpVerifySetupBodyinterfacesrc/types.tsRequest body for confirming email OTP MFA setup.
MfaMethodtypealiassrc/types.tsMFA method identifiers supported by Snapshot’s auth contract.
MfaMethodsResponseinterfacesrc/types.tsResponse listing the enabled MFA methods for the current user.
MfaRecoveryCodesBodyinterfacesrc/types.tsRequest body for regenerating recovery codes.
MfaRecoveryCodesResponseinterfacesrc/types.tsRecovery codes returned by the auth API.
MfaResendBodyinterfacesrc/types.tsRequest body for resending an MFA challenge.
MfaSetupResponseinterfacesrc/types.tsSetup payload returned when provisioning TOTP MFA.
MfaVerifyBodyinterfacesrc/types.tsRequest body for verifying an MFA challenge.
MfaVerifySetupBodyinterfacesrc/types.tsVerification body for confirming an MFA setup flow.
MfaVerifySetupResponseinterfacesrc/types.tsResponse returned after successful MFA setup verification.
NotificationResponseinterfacesrc/community/types.tsNotification record returned by community notification endpoints.
OAuthExchangeBodyinterfacesrc/types.tsRequest body for exchanging an OAuth callback code.
OAuthExchangeResponseinterfacesrc/types.tsTokens returned after a successful OAuth exchange.
OAuthProvidertypealiassrc/types.tsOAuth provider identifier used by auth URL helpers and OAuth hooks.
PaginatedResponseinterfacesrc/community/types.tsType definition exported by the Snapshot UI runtime.
PasskeyLoginBodyinterfacesrc/types.tsRequest body for completing a passkey login.
PasskeyLoginOptionsBodyinterfacesrc/types.tsRequest body for retrieving passkey login options.
PasskeyLoginOptionsResponseinterfacesrc/types.tsResponse returned when beginning a passkey login flow.
PasskeyLoginVarstypealiassrc/types.tsPasskey login variables accepted by usePasskeyLogin().
PushStatetypealiassrc/push/hook.tsHigh-level browser push subscription state reported by usePushNotifications().
QuotePreviewinterfacesrc/community/types.tsSnapshot of a quoted message for inline display.
ReactionBodyinterfacesrc/community/types.tsRequest body for adding/removing an emoji reaction. Sent to POST /community/threads/:id/reactions, etc.
ReactionResponseinterfacesrc/community/types.tsReaction record returned by the read endpoints — full shape with userId, type, and createdAt. Mirrors the slingshot-community Reaction entity. The list hooks (useThreadReactions, useReplyReactions) return arrays of this type. Consumers gating UI on “is this MY reaction” read userId.
RefreshTokenBodyinterfacesrc/types.tsRequest body for refreshing auth tokens.
RefreshTokenResponseinterfacesrc/types.tsToken refresh response returned by the auth API.
RegisterBodyinterfacesrc/types.tsRegistration payload posted to the register endpoint.
registerClientfunctionsrc/api/client.tsRegister a named custom client factory.
RegisterVarstypealiassrc/types.tsRegistration variables accepted by useRegister().
ReplyListParamsinterfacesrc/community/types.tsList parameters for fetching replies in a specific thread.
ReplyResponseinterfacesrc/community/types.tsReply record returned by the community API. Fields mirror the slingshot-community Reply entity. JSON sidecars are typed against slingshot-core’s content types.
ReportBodyinterfacesrc/community/types.tsRequest body for filing a community moderation report.
ReportResponseinterfacesrc/community/types.tsReport record returned by moderation endpoints.
RequestOptionsinterfacesrc/types.tsOptional overrides for individual API client requests.
ResendVerificationBodyinterfacesrc/types.tsRequest body for sending a new verification email.
ResetPasswordBodyinterfacesrc/types.tsRequest body for completing a password reset flow.
ResolveReportBodyinterfacesrc/community/types.tsRequest body for resolving a moderation report.
SearchResponseinterfacesrc/community/types.tsSearch results returned by the thread and reply search endpoints.
SendResulttypealiassrc/ws/manager.tsOutcome of writing a frame. - "sent" — written to an OPEN socket this instant. - "queued" — the socket was not OPEN (connecting / reconnecting), so the frame was buffered and WILL be flushed, in order, the moment the socket opens. It has NOT reached the server yet. - "dropped" — the manager is destroyed, or the caller opted out of queueing (a frame that is reconstructed on reconnect anyway), so the frame was discarded. A caller that needs to know its write is not yet delivered (e.g. a game input that must not report “sent” until the server confirms) can read this — a "queued" result is an explicit “deferred, not delivered” signal. Note that even "sent" is not proof of delivery: a frame written to an OPEN socket can still be lost in a half-open connection. Only an application-level ack proves the server received it.
Sessioninterfacesrc/types.tsActive session metadata returned by session-management hooks.
SetPasswordBodyinterfacesrc/types.tsRequest body for setting or rotating an account password.
SnapshotAuthConfiginterfacesrc/types.tsCode-first auth configuration for createSnapshot().
SnapshotCacheConfiginterfacesrc/types.tsTanStack Query cache defaults used by Snapshot’s built-in hooks.
SnapshotConfiginterfacesrc/types.tsBootstrap configuration for createSnapshot().
SnapshotInstanceinterfacesrc/types.tsRuntime surface returned by createSnapshot().
SnapshotMfaConfiginterfacesrc/types.tsMFA settings forwarded to the MFA setup endpoint.
SnapshotOAuthProviderConfiginterfacesrc/types.tsOAuth provider settings used by getOAuthUrl() and getLinkUrl().
SnapshotSessionConfiginterfacesrc/types.tsUser-session storage settings for token auth mode.
SnapshotWebAuthnConfiginterfacesrc/types.tsWebAuthn relying-party settings forwarded to WebAuthn registration.
SnapshotWebSocketConfiginterfacesrc/types.tsWebSocket settings for Snapshot’s built-in realtime hooks.
SocketHookinterfacesrc/types.tsRealtime websocket control surface returned by useSocket().
SseConfiginterfacesrc/types.tsSSE configuration. Each key is an endpoint path that must start with /__sse/. The value is per-endpoint options. One EventSource is created per endpoint. reconnectOnLogin: whether to reconnect all endpoints on login success (default true).
SseConnectionStatustypealiassrc/sse/manager.tsLifecycle state of a managed SSE connection.
SseEndpointConfiginterfacesrc/types.tsPer-endpoint SSE behavior configuration.
SseEventHookResultinterfacesrc/types.tsReturn type of useSseEvent(endpoint, event)
SseHookResultinterfacesrc/types.tsReturn type of useSSE(endpoint)
SystemEventDatainterfacesrc/community/types.tsSystem message payload (room renames, member joins, etc.).
TestWebhookBodyinterfacesrc/webhooks/types.tsRequest body for sending a test delivery through a webhook endpoint.
ThreadListParamsinterfacesrc/community/types.tsList parameters for fetching threads in a specific container.
ThreadResponseinterfacesrc/community/types.tsThread record returned by the community API. Fields mirror the slingshot-community Thread entity. JSON sidecar fields (mentions, attachments, embeds, …) are typed against slingshot-core’s content types and re-exported above for direct use.
TokenStorageinterfacesrc/auth/storage.tsPer-instance token storage used by Snapshot auth flows.
UpdateContainerBodyinterfacesrc/community/types.tsRequest body for updating a community container.
UpdateReplyBodyinterfacesrc/community/types.tsRequest body for updating an existing reply.
UpdateThreadBodyinterfacesrc/community/types.tsRequest body for updating or moderating a thread. Field names match the entity (pinned / locked).
UpdateWebhookEndpointBodyinterfacesrc/webhooks/types.tsRequest body for updating a webhook endpoint.
UseCommunityNotificationsOptsinterfacesrc/types.tsOptions for the community notifications hook.
UseCommunityNotificationsResultinterfacesrc/types.tsReturn shape of useCommunityNotifications().
usePushNotificationsfunctionsrc/push/hook.tsStandalone hook for Web Push subscription management. No dependency on Snapshot’s SSE or auth infrastructure. CSRF: /__push/* routes are CSRF-exempt by design. No CSRF header is sent. Auth: requests use credentials: ‘include’ (cookie auth). Service worker setup: copy sw.js from node_modules/@lastshotlabs/snapshot/dist/sw.js to your project’s public/sw.js, OR use snapshot init which scaffolds it automatically.
UsePushNotificationsOptsinterfacesrc/push/hook.tsPush notification subscription options.
UsePushNotificationsResultinterfacesrc/push/hook.tsReturn shape of usePushNotifications().
VerifyEmailBodyinterfacesrc/types.tsRequest body for confirming email verification.
VoiceMetadatainterfacesrc/community/types.tsVoice-message-specific metadata (transcript, waveform peaks).
WebAuthnCredentialinterfacesrc/types.tsRegistered WebAuthn credential metadata.
WebAuthnRegisterBodyinterfacesrc/types.tsRequest body for registering a WebAuthn credential.
WebAuthnRegisterOptionsResponseinterfacesrc/types.tsResponse returned when requesting WebAuthn registration options.
WebhookDeliveryResponseinterfacesrc/webhooks/types.tsDelivery record returned for a webhook endpoint event attempt.
WebhookEndpointResponseinterfacesrc/webhooks/types.tsWebhook endpoint record returned by the webhook API.
WebhookHookstypealiassrc/webhooks/hooks.tsHook surface returned by createWebhookHooks().
webhooksContractvariablesrc/webhooks/contract.tsBuilt-in route contract for Snapshot webhook APIs.
WebSocketManagerclasssrc/ws/manager.tsPer-instance WebSocket connection manager.
ExportKindDescription
createSnapshotfunctionCreate a per-instance Snapshot runtime from code-first bootstrap config. Builds per-instance API, auth, realtime, community, and webhook hooks from explicit TypeScript config.

createSnapshot<TWSEvents extends Record<string, unknown> = Record<string, unknown>>(config: SnapshotConfig) => SnapshotInstance<TWSEvents>

Section titled “createSnapshot<TWSEvents extends Record<string, unknown> = Record<string, unknown>>(config: SnapshotConfig) => SnapshotInstance<TWSEvents>”

Create a per-instance Snapshot runtime from code-first bootstrap config.

Builds per-instance API, auth, realtime, community, and webhook hooks from explicit TypeScript config.

Parameters:

NameDescription
configCode-first Snapshot runtime config

Returns: A fully initialized snapshot instance

Example:

import { createSnapshot } from '@lastshotlabs/snapshot';
const snap = createSnapshot({
apiUrl: 'https://api.example.com',
});
// Use hooks in your React components
function App() {
const { user } = snap.useUser();
return user ? <div>Hello {user.email}</div> : <LoginForm />;
}

ExportKindDescription
ApiErrorclassHTTP error thrown by Snapshot API clients for non-success responses.
getRegisteredClientfunctionLook up a previously registered custom client factory.
registerClientfunctionRegister a named custom client factory.

getRegisteredClient(name: string) => ClientFactory | undefined

Section titled “getRegisteredClient(name: string) => ClientFactory | undefined”

Look up a previously registered custom client factory.

Parameters:

NameDescription
nameRegistered client factory name

Returns: The registered factory when found


registerClient(name: string, factory: ClientFactory) => void

Section titled “registerClient(name: string, factory: ClientFactory) => void”

Register a named custom client factory.

Parameters:

NameDescription
nameClient factory name
factoryFactory that creates an ApiClient-like instance

ExportKindDescription
AuthContractinterfaceFull auth contract used by createSnapshot() to build auth URLs and requests.
AuthContractConfiginterfacePartial auth contract overrides.
AuthEndpointsinterfaceRelative auth endpoint paths used by Snapshot’s built-in auth hooks.
AuthErrorConfiginterfaceOptional configuration for auth error formatting.
AuthErrorContexttypealiasAuth UI contexts that can provide custom error messaging.
AuthHeadersinterfaceHeader names Snapshot sends for session and CSRF-aware auth requests.
AuthUserinterfaceMinimal authenticated user shape returned by Snapshot auth hooks.
createAuthErrorFormatterfunctionCreate a reusable auth error formatter with shared formatting rules.
defaultContractfunctionCreate the built-in auth contract for a given API base URL.
DeleteAccountBodyinterfaceRequest body for deleting the current account.
ForgotPasswordBodyinterfaceRequest body for the forgot-password endpoint.
formatAuthErrorfunctionFormat a raw auth ApiError into the message shown to application code.
LoginBodyinterfaceCredentials posted to the login endpoint.
LoginResponseinterfaceRaw login response shape from slingshot (includes MFA fields)
LoginResulttypealiasuseLogin resolves to either a user or an MFA challenge
LoginVarstypealiasLogin variables accepted by useLogin().
LogoutVarsinterfaceLogout options accepted by useLogout().
mergeContractfunctionMerge a partial auth contract override with the built-in defaults.
MfaChallengeinterfaceReturned by useLogin when mfaRequired is true
MfaDisableBodyinterfaceRequest body for disabling MFA.
MfaEmailOtpDisableBodyinterfaceRequest body for disabling email OTP MFA.
MfaEmailOtpEnableResponseinterfaceResponse returned when email OTP MFA setup begins.
MfaEmailOtpVerifySetupBodyinterfaceRequest body for confirming email OTP MFA setup.
MfaMethodtypealiasMFA method identifiers supported by Snapshot’s auth contract.
MfaMethodsResponseinterfaceResponse listing the enabled MFA methods for the current user.
MfaRecoveryCodesBodyinterfaceRequest body for regenerating recovery codes.
MfaRecoveryCodesResponseinterfaceRecovery codes returned by the auth API.
MfaResendBodyinterfaceRequest body for resending an MFA challenge.
MfaSetupResponseinterfaceSetup payload returned when provisioning TOTP MFA.
MfaVerifyBodyinterfaceRequest body for verifying an MFA challenge.
MfaVerifySetupBodyinterfaceVerification body for confirming an MFA setup flow.
MfaVerifySetupResponseinterfaceResponse returned after successful MFA setup verification.
OAuthExchangeBodyinterfaceRequest body for exchanging an OAuth callback code.
OAuthExchangeResponseinterfaceTokens returned after a successful OAuth exchange.
OAuthProvidertypealiasOAuth provider identifier used by auth URL helpers and OAuth hooks.
PasskeyLoginBodyinterfaceRequest body for completing a passkey login.
PasskeyLoginOptionsBodyinterfaceRequest body for retrieving passkey login options.
PasskeyLoginOptionsResponseinterfaceResponse returned when beginning a passkey login flow.
PasskeyLoginVarstypealiasPasskey login variables accepted by usePasskeyLogin().
RefreshTokenBodyinterfaceRequest body for refreshing auth tokens.
RefreshTokenResponseinterfaceToken refresh response returned by the auth API.
RegisterBodyinterfaceRegistration payload posted to the register endpoint.
RegisterVarstypealiasRegistration variables accepted by useRegister().
ResendVerificationBodyinterfaceRequest body for sending a new verification email.
ResetPasswordBodyinterfaceRequest body for completing a password reset flow.
SessioninterfaceActive session metadata returned by session-management hooks.
SetPasswordBodyinterfaceRequest body for setting or rotating an account password.
TokenStorageinterfacePer-instance token storage used by Snapshot auth flows.
VerifyEmailBodyinterfaceRequest body for confirming email verification.
WebAuthnCredentialinterfaceRegistered WebAuthn credential metadata.
WebAuthnRegisterBodyinterfaceRequest body for registering a WebAuthn credential.
WebAuthnRegisterOptionsResponseinterfaceResponse returned when requesting WebAuthn registration options.

createAuthErrorFormatter(config?: AuthErrorConfig | undefined) => (error: ApiError, context: AuthErrorContext) => string

Section titled “createAuthErrorFormatter(config?: AuthErrorConfig | undefined) => (error: ApiError, context: AuthErrorContext) => string”

Create a reusable auth error formatter with shared formatting rules.

Example:

const format = createAuthErrorFormatter({ verbose: false });
const message = format(apiError, 'login');

defaultContract(apiUrl: string) => AuthContract

Section titled “defaultContract(apiUrl: string) => AuthContract”

Create the built-in auth contract for a given API base URL.


formatAuthError(error: ApiError, context: AuthErrorContext, config?: AuthErrorConfig | undefined) => string

Section titled “formatAuthError(error: ApiError, context: AuthErrorContext, config?: AuthErrorConfig | undefined) => string”

Format a raw auth ApiError into the message shown to application code.

Example:

const message = formatAuthError(apiError, 'login');
// With custom config
const message = formatAuthError(apiError, 'register', {
verbose: true,
messages: { register: 'Registration failed.' },
});

mergeContract(apiUrl: string, partial?: AuthContractConfig | undefined) => AuthContract

Section titled “mergeContract(apiUrl: string, partial?: AuthContractConfig | undefined) => AuthContract”

Merge a partial auth contract override with the built-in defaults.

Parameters:

NameDescription
apiUrlBase API URL used to derive absolute auth URLs
partialPartial contract override from code-first auth config

Returns: The merged auth contract


ExportKindDescription
AssetRefinterfaceReference to an uploaded asset (image, audio, video, file).
BanBodyinterfaceRequest body for creating a user ban.
BanCheckResponseinterfaceResult returned when checking whether a user is banned.
BanResponseinterfaceBan record returned by moderation endpoints.
communityContractvariableBuilt-in route contract for Snapshot community APIs.
CommunityHookstypealiasHook surface returned by createCommunityHooks().
communityKeysvariableQuery key helpers for the community API surface. SSR loaders can seed the QueryClient under these keys so loader-seeded keys and hook-read keys stay aligned.
CommunityNotificationinterfaceNormalized notification shape used by useCommunityNotifications().
CommunityNotificationTypetypealiasCommunity notification types surfaced by Snapshot’s notification helpers.
CommunitySearchParamsinterfaceSearch parameters accepted by the community search hooks.
ContactDatainterfaceContact card sidecar.
ContainerResponseinterfaceCommunity container returned by the community API.
ContentFormattypealiasStorage format hint for body text.
CreateContainerBodyinterfaceRequest body for creating a community container.
CreateReplyBodyinterfaceRequest body for creating a reply.
CreateReplyBodyExtendedinterfaceExtended create-reply body — accepts optional sidecar fields the server may overwrite with parsed content metadata.
CreateThreadBodyinterfaceRequest body for creating a thread in a container.
CreateThreadBodyExtendedinterfaceRequest body for creating a thread (extended). Optional sidecar fields can be set client-side; the server may overwrite them with parsed content metadata when its parseBody middleware runs. Treat client-supplied values as advisory.
EmbedDatainterfaceResolved link-preview metadata for a URL referenced in content.
ListParamsinterfaceShared page-based pagination parameters.
LocationDatainterfaceGeo coordinate sidecar.
NotificationResponseinterfaceNotification record returned by community notification endpoints.
PaginatedResponseinterfaceType definition exported by the Snapshot UI runtime.
QuotePreviewinterfaceSnapshot of a quoted message for inline display.
ReactionBodyinterfaceRequest body for adding/removing an emoji reaction. Sent to POST /community/threads/:id/reactions, etc.
ReactionResponseinterfaceReaction record returned by the read endpoints — full shape with userId, type, and createdAt. Mirrors the slingshot-community Reaction entity. The list hooks (useThreadReactions, useReplyReactions) return arrays of this type. Consumers gating UI on “is this MY reaction” read userId.
ReplyListParamsinterfaceList parameters for fetching replies in a specific thread.
ReplyResponseinterfaceReply record returned by the community API. Fields mirror the slingshot-community Reply entity. JSON sidecars are typed against slingshot-core’s content types.
ReportBodyinterfaceRequest body for filing a community moderation report.
ReportResponseinterfaceReport record returned by moderation endpoints.
ResolveReportBodyinterfaceRequest body for resolving a moderation report.
SearchResponseinterfaceSearch results returned by the thread and reply search endpoints.
SystemEventDatainterfaceSystem message payload (room renames, member joins, etc.).
ThreadListParamsinterfaceList parameters for fetching threads in a specific container.
ThreadResponseinterfaceThread record returned by the community API. Fields mirror the slingshot-community Thread entity. JSON sidecar fields (mentions, attachments, embeds, …) are typed against slingshot-core’s content types and re-exported above for direct use.
UpdateContainerBodyinterfaceRequest body for updating a community container.
UpdateReplyBodyinterfaceRequest body for updating an existing reply.
UpdateThreadBodyinterfaceRequest body for updating or moderating a thread. Field names match the entity (pinned / locked).
UseCommunityNotificationsOptsinterfaceOptions for the community notifications hook.
UseCommunityNotificationsResultinterfaceReturn shape of useCommunityNotifications().
VoiceMetadatainterfaceVoice-message-specific metadata (transcript, waveform peaks).
ExportKindDescription
CreateWebhookEndpointBodyinterfaceRequest body for creating a webhook endpoint.
ListWebhookDeliveriesParamsinterfaceParameters for listing deliveries for a single webhook endpoint.
ListWebhookEndpointsParamsinterfacePage-based pagination parameters for listing webhook endpoints.
TestWebhookBodyinterfaceRequest body for sending a test delivery through a webhook endpoint.
UpdateWebhookEndpointBodyinterfaceRequest body for updating a webhook endpoint.
WebhookDeliveryResponseinterfaceDelivery record returned for a webhook endpoint event attempt.
WebhookEndpointResponseinterfaceWebhook endpoint record returned by the webhook API.
WebhookHookstypealiasHook surface returned by createWebhookHooks().
webhooksContractvariableBuilt-in route contract for Snapshot webhook APIs.
ExportKindDescription
PushStatetypealiasHigh-level browser push subscription state reported by usePushNotifications().
usePushNotificationsfunctionStandalone hook for Web Push subscription management. No dependency on Snapshot’s SSE or auth infrastructure. CSRF: /__push/* routes are CSRF-exempt by design. No CSRF header is sent. Auth: requests use credentials: ‘include’ (cookie auth). Service worker setup: copy sw.js from node_modules/@lastshotlabs/snapshot/dist/sw.js to your project’s public/sw.js, OR use snapshot init which scaffolds it automatically.
UsePushNotificationsOptsinterfacePush notification subscription options.
UsePushNotificationsResultinterfaceReturn shape of usePushNotifications().

usePushNotifications(opts?: UsePushNotificationsOpts | undefined) => UsePushNotificationsResult

Section titled “usePushNotifications(opts?: UsePushNotificationsOpts | undefined) => UsePushNotificationsResult”

Standalone hook for Web Push subscription management. No dependency on Snapshot’s SSE or auth infrastructure.

CSRF: /__push/* routes are CSRF-exempt by design. No CSRF header is sent. Auth: requests use credentials: ‘include’ (cookie auth).

Service worker setup: copy sw.js from node_modules/@lastshotlabs/snapshot/dist/sw.js to your project’s public/sw.js, OR use snapshot init which scaffolds it automatically.

Example:

const { state, subscribe, unsubscribe } = usePushNotifications();
// With custom options
const { state, subscribe, unsubscribe } = usePushNotifications({
vapidPublicKey: 'BEl62i...',
subscribeUrl: '/api/push/subscribe',
});

ExportKindDescription
SendResulttypealiasOutcome of writing a frame. - "sent" — written to an OPEN socket this instant. - "queued" — the socket was not OPEN (connecting / reconnecting), so the frame was buffered and WILL be flushed, in order, the moment the socket opens. It has NOT reached the server yet. - "dropped" — the manager is destroyed, or the caller opted out of queueing (a frame that is reconstructed on reconnect anyway), so the frame was discarded. A caller that needs to know its write is not yet delivered (e.g. a game input that must not report “sent” until the server confirms) can read this — a "queued" result is an explicit “deferred, not delivered” signal. Note that even "sent" is not proof of delivery: a frame written to an OPEN socket can still be lost in a half-open connection. Only an application-level ack proves the server received it.
SocketHookinterfaceRealtime websocket control surface returned by useSocket().
SseConfiginterfaceSSE configuration. Each key is an endpoint path that must start with /__sse/. The value is per-endpoint options. One EventSource is created per endpoint. reconnectOnLogin: whether to reconnect all endpoints on login success (default true).
SseConnectionStatustypealiasLifecycle state of a managed SSE connection.
SseEndpointConfiginterfacePer-endpoint SSE behavior configuration.
SseEventHookResultinterfaceReturn type of useSseEvent(endpoint, event)
SseHookResultinterfaceReturn type of useSSE(endpoint)
WebSocketManagerclassPer-instance WebSocket connection manager.
ExportKindDescription
AUTH_QUERY_KEYvariableStable query key under which useUser() and the route guards cache the authenticated user. Exported so apps can invalidate, seed, or read the cache directly (e.g. after a profile update or server-side state change that should force a refresh).
isMfaChallengefunctionNarrow a login result to the MFA challenge branch.
RequestOptionsinterfaceOptional overrides for individual API client requests.
SnapshotAuthConfiginterfaceCode-first auth configuration for createSnapshot().
SnapshotCacheConfiginterfaceTanStack Query cache defaults used by Snapshot’s built-in hooks.
SnapshotConfiginterfaceBootstrap configuration for createSnapshot().
SnapshotInstanceinterfaceRuntime surface returned by createSnapshot().
SnapshotMfaConfiginterfaceMFA settings forwarded to the MFA setup endpoint.
SnapshotOAuthProviderConfiginterfaceOAuth provider settings used by getOAuthUrl() and getLinkUrl().
SnapshotSessionConfiginterfaceUser-session storage settings for token auth mode.
SnapshotWebAuthnConfiginterfaceWebAuthn relying-party settings forwarded to WebAuthn registration.
SnapshotWebSocketConfiginterfaceWebSocket settings for Snapshot’s built-in realtime hooks.

isMfaChallenge(result: LoginResult) => result is MfaChallenge

Section titled “isMfaChallenge(result: LoginResult) => result is MfaChallenge”

Narrow a login result to the MFA challenge branch.


Bootstrap configuration for createSnapshot().

Members:

NameTypeDescription
apiUrlstringAPI base URL for this snapshot instance.
bearerTokenstring | undefinedStatic API credential. Not a user session token. Do not use in browser deployments - emits a runtime warning in browser contexts.
authSnapshotAuthConfig | undefinedAuth contract, session, OAuth, MFA, and WebAuthn settings.
cacheSnapshotCacheConfig | undefinedQuery cache defaults used by Snapshot’s built-in hooks.
wsSnapshotWebSocketConfig | undefinedWebSocket settings for useSocket, useRoom, and useRoomEvent.
sseSseConfig | undefinedServer-sent event settings for useSSE and useSseEvent.
loginPathstring | undefinedPath the protectedBeforeLoad guard redirects to when the user is unauthenticated.
homePathstring | undefinedPath the guestBeforeLoad guard redirects to when an authenticated user lands on a guest-only screen.
mfaPathstring | undefinedPath used when a login or passkey flow requires MFA.

Example:

const snap = createSnapshot({
apiUrl: 'https://api.example.com',
});

Runtime surface returned by createSnapshot().

Members:

NameTypeDescription
bootstrap{ bearerToken?: string | undefined; }Bootstrap values used to create this snapshot instance.
useUser() => { user: AuthUser | null; isLoading: boolean; isError: boolean; }Fetch the current authenticated user. Returns null when logged out.
useLogin() => UseMutationResult<LoginResult, ApiError, LoginVars>Post credentials and log in. Returns an MFA challenge instead of a user when MFA is required.
useLogout() => UseMutationResult<void, ApiError, void | LogoutVars>Clear the session, tokens, and query cache. Navigates to the login route on success.
useRegister() => UseMutationResult<AuthUser, ApiError, RegisterVars>Create a new account. Auto-logs in on success when the backend allows it.
useForgotPassword() => UseMutationResult<void, ApiError, ForgotPasswordBody>Send a password-reset email to the given address.
useSocket() => SocketHook<TWSEvents>Open and manage a WebSocket connection. Returns connection state and send/close helpers.
useRoom(room: string) => { isSubscribed: boolean; }Subscribe to a WebSocket room. Returns whether the subscription is active.
useRoomEvent<T>(room: string, event: string, handler: (data: T) => void) => voidListen for a specific event on a WebSocket room. The handler fires on each matching message.
useTheme() => { theme: "light" | "dark"; toggle: () => void; set: (t: "light" | "dark...Read and toggle the current color theme (light/dark).
usePendingMfaChallenge() => MfaChallenge | nullRead the pending MFA challenge set by a login that returned mfaRequired: true.
useMfaVerify() => UseMutationResult<AuthUser, ApiError, Omit<MfaVerifyBody, "mfaToken">>Verify an MFA code against the pending challenge. Resolves to the authenticated user on success.
useMfaSetup() => UseMutationResult<MfaSetupResponse, ApiError, void>Begin TOTP MFA provisioning. Returns a secret and QR URI for authenticator apps.
useMfaVerifySetup() => UseMutationResult<MfaVerifySetupResponse, ApiError, MfaVerifySetupBody>Confirm TOTP MFA setup by verifying a code from the authenticator app.
useMfaDisable() => UseMutationResult<{ message: string; }, ApiError, MfaDisableBody>Disable MFA for the current user. Requires a valid code or recovery code.
useMfaRecoveryCodes() => UseMutationResult<MfaRecoveryCodesResponse, ApiError, MfaRecoveryCodesB...Regenerate MFA recovery codes. Returns the new codes.
useMfaEmailOtpEnable() => UseMutationResult<MfaEmailOtpEnableResponse, ApiError, void>Begin email OTP MFA enrollment. Sends a verification code to the user’s email.
useMfaEmailOtpVerifySetup() => UseMutationResult<MfaVerifySetupResponse, ApiError, MfaEmailOtpVerifySe...Confirm email OTP MFA setup by verifying the emailed code.
useMfaEmailOtpDisable() => UseMutationResult<{ message: string; }, ApiError, MfaEmailOtpDisableBody>Disable email OTP MFA for the current user.
useMfaResend() => UseMutationResult<{ message: string; }, ApiError, MfaResendBody>Resend the MFA challenge code (email OTP or SMS).
useMfaMethods() => { methods: MfaMethod[] | null; isLoading: boolean; isError: boolean; }List MFA methods currently enabled for the authenticated user.
isMfaChallenge(result: LoginResult) => result is MfaChallengeType-narrowing guard: returns true when a login result is an MFA challenge.
useResetPassword() => UseMutationResult<{ message: string; }, ApiError, ResetPasswordBody>Complete a password reset using the token from the reset email.
useVerifyEmail() => UseMutationResult<{ message: string; }, ApiError, VerifyEmailBody>Confirm the user’s email address using a verification token.
useResendVerification() => UseMutationResult<{ message: string; }, ApiError, ResendVerificationBody>Request a new verification email for the current user.
useSetPassword() => UseMutationResult<{ message: string; }, ApiError, SetPasswordBody>Set or rotate the account password. Requires the current password or a reset token.
useDeleteAccount() => UseMutationResult<void, ApiError, void | DeleteAccountBody>Schedule the current account for deletion.
useCancelDeletion() => UseMutationResult<{ message: string; }, ApiError, void>Cancel a pending account deletion before the grace period expires.
useRefreshToken() => UseMutationResult<RefreshTokenResponse, ApiError, void | RefreshTokenBody>Refresh the current access and refresh tokens.
useSessions() => { sessions: Session[]; isLoading: boolean; isError: boolean; }List all active sessions for the authenticated user.
useRevokeSession() => UseMutationResult<void, ApiError, string>Revoke a session by its ID. Logs out that device.
useOAuthExchange(opts?: { navigateOnSuccess?: boolean | undefined; } | undefined) => UseMutat...Exchange an OAuth callback code for session tokens. Called after the provider redirects back. Pass { navigateOnSuccess: false } to suppress the default navigate to homePath and let the caller decide where to go after the exchange completes (e.g. an admin callback that needs to verify a permission grant before navigating).
useOAuthUnlink() => UseMutationResult<void, ApiError, OAuthProvider>Remove an OAuth provider link from the current account.
getOAuthUrl(provider: OAuthProvider, opts?: { returnTo?: string | undefined; } | undefin...Build the redirect URL for starting an OAuth login flow with the given provider. Pass opts.returnTo to override the api’s default post-login redirect with a per-flow target — used when a secondary origin (admin app, embedded surface) shares the same OAuth client but needs the callback delivered to its own origin.
getLinkUrl(provider: OAuthProvider) => stringBuild the redirect URL for linking an OAuth provider to the current account.
useWebAuthnRegisterOptions() => UseMutationResult<WebAuthnRegisterOptionsResponse, ApiError, void>Request WebAuthn registration options (challenge, relying party info) from the server.
useWebAuthnRegister() => UseMutationResult<{ message: string; }, ApiError, WebAuthnRegisterBody>Complete WebAuthn credential registration with the attestation response from the authenticator.
useWebAuthnCredentials() => { credentials: WebAuthnCredential[]; isLoading: boolean; isError: boole...List all registered WebAuthn credentials for the current user.
useWebAuthnRemoveCredential() => UseMutationResult<{ message: string; }, ApiError, string>Remove a registered WebAuthn credential by its ID.
useWebAuthnDisable() => UseMutationResult<{ message: string; }, ApiError, void>Disable WebAuthn for the current user and remove all registered credentials.
usePasskeyLoginOptions() => UseMutationResult<PasskeyLoginOptionsResponse, ApiError, PasskeyLoginOp...Request passkey login options (challenge) from the server to start a passwordless login.
usePasskeyLogin() => UseMutationResult<LoginResult, ApiError, PasskeyLoginVars>Complete a passkey login with the assertion response from the authenticator.
formatAuthError(error: ApiError, context: AuthErrorContext) => stringFormat an API error into a user-facing auth error message using optional per-context overrides.
useSSE(endpoint: string) => SseHookResultConnect to a server-sent events endpoint. Returns connection status and a close function.
useSseEvent<T = unknown>(endpoint: string, event: string) => SseEventHookResult<T>Subscribe to a named event on an SSE endpoint. Returns the latest payload and connection status.
onSseEvent(endpoint: string, event: string, handler: (payload: unknown) => void) => () ...Register a callback for a named SSE event. Returns an unsubscribe function.
useCommunityNotifications(opts?: UseCommunityNotificationsOpts | undefined) => UseCommunityNotificatio...Subscribe to real-time community notifications via SSE. Requires an /__sse/notifications endpoint.
useContainers(params?: ListParams | undefined) => UseQueryResult<PaginatedResponse<Contain...List community containers with optional pagination.
useContainer(containerId: string) => UseQueryResult<ContainerResponse, ApiError>Fetch a single container by ID.
useCreateContainer() => UseMutationResult<ContainerResponse, ApiError, CreateContainerBody, unk...Create a new community container.
useUpdateContainer() => UseMutationResult<ContainerResponse, ApiError, { containerId: string; }...Update a container’s metadata.
useDeleteContainer() => UseMutationResult<void, ApiError, { containerId: string; }, unknown>Delete a container and its contents.
useContainerThreads({ containerId, ...params }: ThreadListParams) => UseQueryResult<PaginatedRes...List threads in a container with pagination and optional filters.
useContainerThread(threadId: string) => UseQueryResult<ThreadResponse, ApiError>Fetch a single thread by ID.
useCreateThread() => UseMutationResult<ThreadResponse, ApiError, { containerId: string; } & ...Create a new thread in a container.
useUpdateThread() => UseMutationResult<ThreadResponse, ApiError, { threadId: string; contain...Update a thread’s content or metadata.
useDeleteThread() => UseMutationResult<void, ApiError, { threadId: string; containerId: stri...Delete a thread.
usePublishThread() => UseMutationResult<ThreadResponse, ApiError, { threadId: string; contain...Publish a draft thread, making it visible to other users.
useLockThread() => UseMutationResult<ThreadResponse, ApiError, { threadId: string; contain...Lock a thread to prevent new replies.
useUnlockThread() => UseMutationResult<ThreadResponse, ApiError, { threadId: string; contain...Unlock a thread so replies can be posted again.
usePinThread() => UseMutationResult<ThreadResponse, ApiError, { threadId: string; contain...Pin a thread to the top of its container.
useUnpinThread() => UseMutationResult<ThreadResponse, ApiError, { threadId: string; contain...Unpin a previously pinned thread.
useThreadReplies({ threadId, ...params }: ReplyListParams) => UseQueryResult<PaginatedRespons...List replies in a thread with pagination.
useReply(replyId: string) => UseQueryResult<ReplyResponse, ApiError>Fetch a single reply by ID.
useCreateReply() => UseMutationResult<ReplyResponse, ApiError, { threadId: string; } & Crea...Post a new reply to a thread.
useUpdateReply() => UseMutationResult<ReplyResponse, ApiError, { replyId: string; threadId:...Update a reply’s content.
useDeleteReply() => UseMutationResult<void, ApiError, { replyId: string; threadId: string; ...Delete a reply.
useThreadReactions(threadId: string) => UseQueryResult<ReactionResponse[], ApiError>List reactions on a thread.
useReplyReactions(replyId: string) => UseQueryResult<ReactionResponse[], ApiError>List reactions on a reply.
useAddThreadReaction() => UseMutationResult<void, ApiError, { threadId: string; containerId: stri...Add an emoji reaction to a thread.
useRemoveThreadReaction() => UseMutationResult<void, ApiError, { reactionId: string; threadId: strin...Remove an emoji reaction from a thread.
useAddReplyReaction() => UseMutationResult<void, ApiError, { replyId: string; threadId: string; ...Add an emoji reaction to a reply.
useRemoveReplyReaction() => UseMutationResult<void, ApiError, { reactionId: string; replyId: string...Remove an emoji reaction from a reply.
useContainerMembers(containerId: string, params?: ListParams | undefined) => UseQueryResult<Memb...List members of a container with pagination.
useContainerModerators(containerId: string, params?: ListParams | undefined) => UseQueryResult<Memb...List moderators of a container.
useContainerOwners(containerId: string, params?: ListParams | undefined) => UseQueryResult<Memb...List owners of a container.
useAddMember() => UseMutationResult<MemberRecord, ApiError, { containerId: string; userId...Add a user as a member of a container.
useRemoveMember() => UseMutationResult<void, ApiError, { containerId: string; userId: string...Remove a member from a container.
useAssignModerator() => UseMutationResult<void, ApiError, { containerId: string; userId: string...Promote a member to moderator.
useRemoveModerator() => UseMutationResult<void, ApiError, { containerId: string; userId: string...Remove moderator role from a user.
useAssignOwner() => UseMutationResult<void, ApiError, { containerId: string; userId: string...Promote a member to owner.
useRemoveOwner() => UseMutationResult<void, ApiError, { containerId: string; userId: string...Remove owner role from a user.
useNotifications(params?: ListParams | undefined) => UseQueryResult<PaginatedResponse<Notific...List notifications for the current user with pagination.
useNotificationsUnreadCount() => UseQueryResult<{ count: number; }, ApiError>Get the count of unread notifications.
useMarkAllNotificationsSeen() => UseMutationResult<void, ApiError, void, unknown>Clear the notification badge without marking rows read.
useMarkNotificationRead() => UseMutationResult<void, ApiError, { notificationId: string; }, unknown>Mark a single notification as read.
useMarkAllNotificationsRead() => UseMutationResult<void, ApiError, void, unknown>Mark all notifications as read.
useDismissNotification() => UseMutationResult<void, ApiError, { notificationId: string; }, unknown>Dismiss a notification owned by the current user.
useReports(params?: ListParams | undefined) => UseQueryResult<PaginatedResponse<ReportR...List moderation reports with pagination.
useReport(reportId: string) => UseQueryResult<ReportResponse, ApiError>Fetch a single report by ID.
useCreateReport() => UseMutationResult<ReportResponse, ApiError, ReportBody, unknown>File a moderation report against a thread or reply.
useResolveReport() => UseMutationResult<ReportResponse, ApiError, { reportId: string; } & Res...Resolve a moderation report with an action (e.g., warn, delete).
useDismissReport() => UseMutationResult<ReportResponse, ApiError, { reportId: string; }, unkn...Dismiss a moderation report without taking action.
useBans(params?: ListParams | undefined) => UseQueryResult<PaginatedResponse<BanResp...List banned users with pagination.
useCheckBan(userId: string, containerId?: string | undefined) => UseQueryResult<BanCheck...Check whether a specific user is banned.
useCreateBan() => UseMutationResult<BanResponse, ApiError, BanBody, unknown>Ban a user from a container or globally.
useRemoveBan() => UseMutationResult<void, ApiError, { banId: string; userId: string; }, u...Remove a ban, restoring the user’s access.
useSearchThreads(params: CommunitySearchParams & { q: string; }) => UseQueryResult<SearchResp...Full-text search across threads.
useSearchReplies(params: CommunitySearchParams & { q: string; }) => UseQueryResult<SearchResp...Full-text search across replies.
useWebhookEndpoints() => UseQueryResult<WebhookEndpointResponse[], ApiError>List webhook endpoints with pagination.
useWebhookEndpoint(endpointId: string) => UseQueryResult<WebhookEndpointResponse, ApiError>Fetch a single webhook endpoint by ID.
useCreateWebhookEndpoint() => UseMutationResult<WebhookEndpointResponse, ApiError, CreateWebhookEndpo...Create a new webhook endpoint.
useUpdateWebhookEndpoint() => UseMutationResult<WebhookEndpointResponse, ApiError, { endpointId: stri...Update an existing webhook endpoint’s URL, events, or status.
useDeleteWebhookEndpoint() => UseMutationResult<void, ApiError, { endpointId: string; }, unknown>Delete a webhook endpoint.
useWebhookDeliveries({ endpointId, page, pageSize, }: ListWebhookDeliveriesParams) => UseQueryRes...List delivery attempts for a webhook endpoint.
useWebhookDelivery(deliveryId: string) => UseQueryResult<WebhookDeliveryResponse, ApiError>Fetch a single delivery record by ID.
useTestWebhookEndpoint() => UseMutationResult<void, ApiError, { endpointId: string; } & TestWebhook...Send a test delivery through a webhook endpoint.
apiApiClientLow-level API client bound to this snapshot instance.
tokenStorageTokenStorageToken storage used for session persistence (access + refresh tokens).
queryClientQueryClientTanStack Query client shared across all hooks in this snapshot instance.
useWebSocketManager() => WebSocketManager<TWSEvents> | nullAccess the WebSocket connection manager. Returns null when WebSocket is not configured.
protectedBeforeLoad(ctx: { context: { queryClient: QueryClient; }; }) => Promise<void>Low-level route guard that redirects unauthenticated users to the login page. Prefer protect() — it returns a typed { beforeLoad } fragment that slots into createFileRoute(...)({...}) without a caller cast.
guestBeforeLoad(ctx: { context: { queryClient: QueryClient; }; }) => Promise<void>Low-level route guard that redirects authenticated users away from guest-only pages. Prefer guest() — it returns a typed { beforeLoad } fragment that slots into createFileRoute(...)({...}) without a caller cast.
protect() => { beforeLoad: never; }Route fragment factory for protected (auth-required) routes.
guest() => { beforeLoad: never; }Route fragment factory for guest-only (logged-out) routes. Mirror of protect().
setNavigator(nav: ((to: string, opts: { replace?: boolean | undefined; }) => void) | null...Register a router-aware navigator. Auth hooks (useLogout, useDeleteAccount, OAuth/MFA flows) call this for post-mutation redirects so the router actually transitions instead of falling through to pushState + popstate (which TanStack Router ignores). Pass null to clear.
QueryProviderFC<{ children: ReactNode; }>React provider that wraps children with the TanStack QueryClientProvider for this instance.