Vue
@getenginex/sdk-vue connects the core client and @tanstack/vue-query v5 to a Vue 3 app: reactive session, typed queries and mutations, invalidation after every write, cache cleanup on user switch and realtime. The package runs in the browser. In Nuxt, use it client-side only (see Nuxt).
npm i @getenginex/sdk @getenginex/sdk-vue @tanstack/vue-query vuePeers: vue >=3.5, @tanstack/vue-query ^5 and @getenginex/sdk >=0.6.0 <1.0.0. A complete project, in mock mode (no gateway), is at examples/vue-vite.
Plugin
Create the core client once, outside the components, and install EnginexPlugin:
// main.ts
import { createEnginexClient, localStorageTokenStore } from '@getenginex/sdk'
import { EnginexPlugin } from '@getenginex/sdk-vue'
import { createApp } from 'vue'
import App from './App.vue'
const enginex = createEnginexClient({ locale: 'pt-BR', tokenStore: localStorageTokenStore() })
createApp(App).use(EnginexPlugin, { client: enginex }).mount('#app')The plugin installs TanStack's VueQueryPlugin, provides the client to the composables and, when the session's user changes, removes from the cache everything under ['enginex', 'user'] (see User switch). The session subscription is released on app.unmount().
With the app's QueryClient
Without a queryClient, the plugin creates one per app (never a module singleton), with a 60 s staleTime on queries. If the app already has a QueryClient, pass it: it is used as-is, without changing any option.
import { QueryClient } from '@tanstack/vue-query'
const queryClient = new QueryClient({
defaultOptions: { queries: { staleTime: 5 * 60_000, retry: 1, refetchOnWindowFocus: false } },
})
createApp(App).use(EnginexPlugin, { client: enginex, queryClient }).mount('#app')If the app already installs VueQueryPlugin
With installVueQuery: false the plugin does not install VueQueryPlugin, and queryClient becomes required: it must be exactly the same one the app installed in VueQueryPlugin. The plugin throws an error if it is missing. With two different QueryClients, the cache cleanup on user switch and the invalidation of mutations would act on one cache while the queries read from another; that is why the plugin (on install) and the composables (in setup) throw an error when the app's VueQueryPlugin uses another QueryClient. This also applies without installVueQuery: false: if the app already installed VueQueryPlugin, pass the same queryClient to EnginexPlugin.
createApp(App)
.use(VueQueryPlugin, { queryClient })
.use(EnginexPlugin, { client: enginex, queryClient, installVueQuery: false })
.mount('#app')client and queryClient must be stable. To switch tenants, create another app (or remount it).
Session
<script setup lang="ts">
import { useEnginex, useSession } from '@getenginex/sdk-vue'
const session = useSession()
const enginex = useEnginex()
</script>
<template>
<button v-if="session.status === 'authenticated'" @click="enginex.auth.logout()">Log out</button>
<LoginButton v-else />
</template>useSession()returns a read-only ref (shallowRef) overclient.session; the reference only changes when the session changes (refreshing the same user's tokens does not replace it). The subscription is released when the component's scope ends. In the template the ref is unwrapped (session.status); in the<script>, usesession.value.useEnginex()returns the plugin's client (throws in an app withoutEnginexPlugin).
User keys: useUserKey
To invalidate or read the signed-in player's data from the cache, useUserKey(namespace?, method?) returns a computed with the ['enginex', 'user', userId, namespace?, method?] prefix for the current session, or null with no session. namespace and method accept a value, ref or getter:
import { useUserKey } from '@getenginex/sdk-vue'
import { useQueryClient } from '@tanstack/vue-query'
const queryClient = useQueryClient()
const walletKey = useUserKey('wallet') // ['enginex', 'user', userId, 'wallet']
const refresh = () => walletKey.value && queryClient.invalidateQueries({ queryKey: walletKey.value })Outside a component, enginexKeys.user(userId, namespace, method?) (from @getenginex/sdk/query) builds the same key. For an exact setQueryData, use the key from the factory itself (q.wallet.getBalance().queryKey).
User switch
When the session's user changes (logout, login, or login with a different sub), the plugin removes from the cache everything under ['enginex', 'user']: one player's data is never served to another. The comparison uses status and userId, so refreshing the same user's tokens clears nothing. ['enginex', 'public'] and the app's keys are left as they are. If the app has its own keys with player data, clear them yourself (e.g. with a watch over useSession()).
Queries
<script setup lang="ts">
import { useEnginexQueries, useEnginexQuery } from '@getenginex/sdk-vue'
const q = useEnginexQueries()
const { data: balance, error, isPending } = useEnginexQuery(() => q.wallet.getBalance(), { refetchInterval: 10_000 })
</script>
<template>
<Skeleton v-if="isPending" />
<ErrorMessage v-else-if="error" :code="error.code" />
<p v-else-if="balance">{{ balance.realBalance }}</p>
</template>The getter rule
useEnginexQuery and useEnginexMutation receive a getter (() => q.wallet.getBalance()), never the options already built. The reason: the key of user queries carries the userId at the moment the factory is called (with no session, 'anonymous'). The getter runs again when the session changes and when any ref read inside it changes, and the key follows. A fixed object, built once in setup, would be stuck on the 'anonymous' key forever and never see the login:
// WRONG: the options are built once, with the user (or 'anonymous') at setup time
useEnginexQuery(q.wallet.getBalance()) // does not compile: the parameter is a getter
// RIGHT: the getter runs again when the session changes
useEnginexQuery(() => q.wallet.getBalance())That is why the input that changes goes inside the getter, read from a ref:
const page = ref(1)
const { data, isPending } = useEnginexQuery(() => q.wallet.listTransactions({ page: page.value }))
page.value = 2 // the key changes and page 2 is fetchedReturn value and overrides
useEnginexQueries()returns the core factories. Call the factory inside the getter, not outside.- Products:
useEnginexQueries(createIgamingQueries, igaming)(orcreatePredictionsQueries) returns the product package's factories. - The return value is vue-query's
useQuery, witherrortyped asEnginexError. As in vue-query,data,error,isPendingetc. are refs (destructure and use them in the template, or read.valuein the script). In TypeScript,dataanderrorare unions of refs: the type is the form vue-query declares, and the template and.valuework normally. overrides(second argument:refetchInterval,select,enabled,staleTime,retry...) win over the factory's options;queryKeyandqueryFncannot be replaced.undefinedvalues are ignored (they do not erase, for example, thestaleTimeofconfig.*).retry: accepts a number, boolean or function, or a ref of any of them. The getter form (retry: () => 2) is not supported, because it would be ambiguous with the function form(failureCount, error) => boolean; use a ref (retry: ref(2)) if the value needs to change.- Cancellation: unmounting the last component that observes the query aborts the SDK's
fetchand raises no error. - Default retry:
UNAUTHENTICATED(user query with no session) is not retried, because it made no request; the other errors follow theQueryClient'sretry(oroverrides.retry).
Product queries
import { createIgaming } from '@getenginex/sdk-igaming'
import { createIgamingQueries } from '@getenginex/sdk-igaming/query'
const igaming = createIgaming(enginex) // in the same module as the client, once
// in a component's setup
const ig = useEnginexQueries(createIgamingQueries, igaming)
const games = useEnginexQuery(() => ig.casino.listGames({ page: 1 }), { select: (page) => page.items })Mutations
<script setup lang="ts">
import { useEnginexMutation, useEnginexMutations } from '@getenginex/sdk-vue'
const m = useEnginexMutations()
const pix = useEnginexMutation(() => m.deposits.createPix(), {
onSuccess: (deposit) => router.push(`/deposit/${deposit.id}`),
onError: (error) => toast(error.code),
})
</script>
<template>
<button :disabled="pix.isPending.value" @click="pix.mutate({ amount: 5000 })">Deposit</button>
</template>- On success, it invalidates exactly
invalidates(input, result)(here: balance, transactions and deposits), waits for the refetches and only then calls youronSuccess:mutateAsyncandisPendingfinish with the data already updated. - On error it invalidates nothing and
onErrorreceives theEnginexError. If your ownonSuccessthrows, the invalidation has already happened andonErrorreceives its error (which is not necessarily anEnginexError). useEnginexMutations(createIgamingMutations, igaming)returns a product's mutations.- As with queries, the first argument is a getter and
overrideswins over the factory's options (mutationFncannot be replaced).
Idempotency in mutations
Deposit, withdrawal (request, confirmOtp), bonus.optIn/claim/redeemPromoCode, loyalty.redeem and the Predictions orders send an Idempotency-Key. The full rule (table of ambiguous failures, ABORTED, explicit key) is in Idempotency; in Vue:
- The attempt lives in the composable instance.
useEnginexMutationkeeps the attempt (input and key) per instance, and it survives the getter re-running and TanStack'sretry. Two instances never share a key. - The method is part of the fingerprint. The same instance that switches method (e.g. deposit ↔ withdrawal with the same input) does not reuse the other's key.
- Adjustments go in the second argument. Pass
retry,onSuccessetc. inoverrides. Spreading the options (useEnginexMutation(() => ({ ...m.deposits.createPix(), retry: 1 }))) loses the SDK's call, which the spread does not copy, and with it the per-instance attempt. - Only after an ambiguous failure.
NETWORK_ERROR,TIMEOUT, 5xx,KEY_IN_USEandVALIDATION_ERRORafter a 2xx keep the key. Success, the other 4xx andABORTEDdiscard it: the nextmutateis a new operation. - The input is compared by content. A "try again" with a literal
pix.mutate({ amount: 5000 }), after a 503, reuses the key. Changing the amount starts a new operation. - Explicit key:
m.deposits.createPix({ idempotencyKey })wins over the attempt, so you can store the key and repeat after reloading the page. Generate one per operation (when the player confirms), never one per screen. Since the getter runs again when therefholding the key changes, a two-step flow works like this:
const operation = ref<{ amount: number; idempotencyKey: string }>()
const pix = useEnginexMutation(() => m.deposits.createPix({ idempotencyKey: operation.value?.idempotencyKey }))
// step 1: the player confirms the amount (one key per operation)
const confirm = (amount: number) => (operation.value = { amount, idempotencyKey: crypto.randomUUID() })
// step 2, on another click; "try again" calls pay() once more
const pay = () => operation.value && pix.mutate({ amount: operation.value.amount })When in doubt, prefer the simple path: without an explicit key, the SDK takes care of it.
Realtime
<script setup lang="ts">
import { coreTopics } from '@getenginex/sdk/realtime'
import { useRealtime, useRealtimeStatus, useRealtimeSync } from '@getenginex/sdk-vue'
useRealtimeSync() // balance and notifications in the cache, no polling
const status = useRealtimeStatus()
useRealtime(coreTopics.notification(), (n) => toast(n.title))
</script>
<template>
<Banner v-if="status === 'reconnecting'">Reconnecting...</Banner>
</template>useRealtime(topic, handler)subscribes for as long as the scope (component oreffectScope) exists and unsubscribes when it ends.topicaccepts a value, ref or getter, andnulldoes not subscribe (e.g. a market id not yet known).handleris a function or a ref of a function, and the latest one receives the messages without resubscribing. The topic is compared by key: an equivalent topic (coreTopics.balance()returned again by the getter) does not resubscribe, and a different topic does. A private topic is only subscribed with a user in the session and resubscribes on user switch.useRealtimeStatus()returns a read-only ref with'connecting' | 'open' | 'reconnecting' | 'closed' | 'unavailable'. It does not open the connection.useRealtimeSync(options?)is opt-in. With a user in the session, it invalidates the balance query on everybalance_update(it never usessetQueryData: the message does not carry reserved and bonus amounts), thenotificationsqueries on every notification and, after a reconnection (onResync), thewalletandnotificationsqueries. Only active queries are refetched.optionscan be an object, a ref or a getter: with a ref or getter, the topics react to changes.
Product topics go in topics, each with the keys it feeds. Build the keys with the factories (.queryKey), never by hand; use the function form for user keys, which depend on the session at the time of the message. With a getter, the topic follows marketId:
import { createPredictions } from '@getenginex/sdk-predictions'
import { createPredictionsQueries } from '@getenginex/sdk-predictions/query'
import { predictionsTopics } from '@getenginex/sdk-predictions/realtime'
const predictions = createPredictions(enginex) // in the same module as the client, once
// in a component's setup
const props = defineProps<{ marketId: string }>()
const pq = useEnginexQueries(createPredictionsQueries, predictions)
useRealtimeSync(() => ({
topics: [
{
topic: predictionsTopics.orderbook({ marketId: props.marketId }),
invalidate: [pq.markets.getOrderbook({ marketId: props.marketId }).queryKey],
},
{
topic: predictionsTopics.orders(),
invalidate: () => [pq.orders.list().queryKey],
},
],
}))useRealtimeSync does not apply the messages' content to the cache: for that (e.g. applying orderbook deltas), use useRealtime. The WebSocket URL and the rest of the connection follow the core's Realtime (wsUrl in createEnginexClient).
Testing
The core mocks (createMockFetch and createMockRealtime, from @getenginex/sdk/testing; see Testing and mocks) work with @vue/test-utils: mount the component in an app with EnginexPlugin and a fake client.
import { createEnginexClient, memoryTokenStore } from '@getenginex/sdk'
import { createMockFetch, createMockRealtime } from '@getenginex/sdk/testing'
import { EnginexPlugin } from '@getenginex/sdk-vue'
import { flushPromises, mount } from '@vue/test-utils'
import { expect, it } from 'vitest'
import Balance from './Balance.vue'
it('shows the player balance', async () => {
const realtime = createMockRealtime()
const enginex = createEnginexClient({
baseUrl: 'https://gateway.test',
tenantHost: 'casino.test',
tokenStore: memoryTokenStore(),
fetch: createMockFetch(),
webSocket: realtime.webSocket,
})
await enginex.auth.login({ email: 'ana@exemplo.com', password: 'Senha@123' })
const wrapper = mount(Balance, { global: { plugins: [[EnginexPlugin, { client: enginex }]] } })
await flushPromises()
expect(wrapper.text()).toContain('R$')
})Each test mounts its own app, so the QueryClient (created by the plugin) is never shared between tests. To control the cache, pass your own queryClient to the plugin. The examples/vue-vite project runs entirely in mock mode, with the balance updated by realtime.
Nuxt: client-only
The package has no SSR support. The factories build the key from the client's session, and on the server the browser client has no session: a user query rendered during SSR would come out with the 'anonymous' key and break hydration. In Nuxt, use the SDK only on the client, with both measures below:
- install the plugin in a client-only Nuxt plugin (
plugins/enginex.client.ts, below); and - render the components that use the composables only on the client: wrap them in
<ClientOnly>or name them*.client.vue.
One alone is not enough. With the client-only plugin, SSR still renders the components, and the first composable throws because it cannot find EnginexPlugin in the server's app. With only <ClientOnly>, the plugin also runs on the server, on every request, creating a client without the browser's session (there is no localStorage in Node) that no component uses.
// plugins/enginex.client.ts
import { createEnginexClient, localStorageTokenStore } from '@getenginex/sdk'
import { EnginexPlugin } from '@getenginex/sdk-vue'
export default defineNuxtPlugin((nuxtApp) => {
const enginex = createEnginexClient({ locale: 'pt-BR', tokenStore: localStorageTokenStore() })
nuxtApp.vueApp.use(EnginexPlugin, { client: enginex })
})There is no server-side prefetch in Nuxt. sdk-vue has no equivalent of prefetchEnginex (from @getenginex/sdk-next) and does not hydrate queries: every query, including the public ones (configuration, catalog), runs in the browser after the component mounts. Prefetching and hydrating queries on the server (SSR via Nuxt) are outside this version.