PushizoDocs
Integrations

Pushizo Web SDK with Vue

The primary path for Vue is the @pushizo/vue package: app.use(PushizoPlugin, options) initializes the shared @pushizo/web instance once in the browser, and components access the SDK and the reactive permission/subscription…

The primary path for Vue is the @pushizo/vue package: app.use(PushizoPlugin, options) initializes the shared @pushizo/web instance once in the browser, components access the SDK and the reactive permission/subscription state through the usePushizo() composable, and this.$pushizo is available in the Options API. The package works with Vue 3 and Vue 2.7 and is SSR-safe (init is never called on the server). For Nuxt 3, a client-only plugin file is all you need. Setup without the package (only @pushizo/web) is in section 9.

1. Installation

npm install @pushizo/vue @pushizo/web

@pushizo/web is a peer dependency (peerDependency); Vue ^3.2 or ^2.7 is required.

The service worker goes at the site root: public/PushizoSDKWorker.js in Vite projects, public/PushizoSDKWorker.js in Nuxt.

// public/PushizoSDKWorker.js
const apiUrl = new URL(self.location.href).searchParams.get('apiUrl') || 'https://api.pushizo.com';
importScripts(`${apiUrl.replace(/\/$/, '')}/sdk-web/PushizoSDKWorker.js`);

Environment: VITE_HS_APP_ID, VITE_HS_API_URL (Nuxt: NUXT_PUBLIC_HS_APP_ID, NUXT_PUBLIC_HS_API_URL → runtimeConfig.public).

2. Plugin and composable

// src/main.ts (Vue 3)
import { createApp } from 'vue';
import { PushizoPlugin } from '@pushizo/vue';
import App from './App.vue';

createApp(App)
  .use(PushizoPlugin, {
    appId: import.meta.env.VITE_HS_APP_ID,
    apiUrl: import.meta.env.VITE_HS_API_URL,
    serviceWorkerPath: '/PushizoSDKWorker.js',
    allowLocalhostAsSecureOrigin: import.meta.env.DEV,
    bell: { enabled: true },
  })
  .mount('#app');

Vue 2.7: Vue.use(PushizoPlugin, { appId: … }). Even if the plugin is installed more than once, the SDK is initialized only once; only the first options are used. An init error is not thrown; it is written to the usePushizo().error ref.

usePushizo() returns the following (the refs are read-only):

FieldDescription
pushizoThe shared SDK instance (login, User, Notifications, Session, InAppMessages, Inbox …)
ready, errorinit completed / error
permission'default' | 'granted' | 'denied' | 'unsupported'
pushSubscription{ id, token, optedIn, permission }
stateThe entire state in a single ref

onNotificationClick(handler) adds a notification click listener and removes it when the component (or effectScope) ends. The state is fed by the web SDK's observers; in Vue 3 the observers are removed when the app unmounts (app.unmount()).

Nuxt 3

// plugins/pushizo.client.ts — runs on the client only
import { PushizoPlugin } from '@pushizo/vue';

export default defineNuxtPlugin((nuxtApp) => {
  const config = useRuntimeConfig();
  nuxtApp.vueApp.use(PushizoPlugin, {
    appId: config.public.hsAppId,
    apiUrl: config.public.hsApiUrl,
    allowLocalhostAsSecureOrigin: import.meta.dev,
  });
});

Even if the plugin is installed on the server, it does not touch the SDK; ready stays false and code that touches the SDK does not run until it is ready. Since components using usePushizo() are also rendered on the server, it is equally safe to install the plugin as a universal plugin (plugins/pushizo.ts) instead of .client.ts.

3. Permission and subscription

<script setup lang="ts">
import { usePushizo } from '@pushizo/vue';

const { pushizo, ready, error, permission, pushSubscription } = usePushizo();
</script>

<template>
  <p v-if="error" role="alert">{{ error.message }}</p>
  <p v-else-if="!ready">Loading SDK…</p>
  <p v-else-if="permission === 'unsupported'">This browser does not support web push (HTTPS required).</p>
  <p v-else-if="permission === 'denied'">Notifications are blocked in the browser settings.</p>
  <button v-else-if="pushSubscription.optedIn" type="button" @click="pushizo.User.pushSubscription.optOut()">Turn off notifications</button>
  <button v-else type="button" @click="pushizo.Notifications.requestPermission()">Allow notifications</button>
</template>

permission updates with the prompt result and (in browsers that support the Permissions API) with changes made in the site settings.

4. Login / logout

// When the user in your Pinia store changes
import { watch } from 'vue';
import { usePushizo } from '@pushizo/vue';

const { pushizo, ready } = usePushizo();
watch(
  [ready, () => auth.user],
  ([isReady, user]) => {
    if (!isReady) return;
    if (user) void pushizo.login(user.id, user.identityHash); // identity_hash from the server (if required)
    else if (pushizo.User.externalId) void pushizo.logout();
  },
  { immediate: true },
);

5. Tags, events and route tracking

pushizo.User.addTags({ plan: 'pro' });
pushizo.User.removeTag('plan');
pushizo.Session.sendEvent('purchase', { sku: 'A1' }, 49.9);

In-app screen trigger with Vue Router:

// src/router.ts
import { usePushizo } from '@pushizo/vue';

router.afterEach((to) => {
  const { pushizo, ready } = usePushizo();
  if (ready.value) pushizo.InAppMessages.setScreen(to.name ? String(to.name) : to.path);
});

usePushizo() does not use inject (the single SDK instance is shared at module level), so it can also be called outside components, such as in a router guard, as long as the plugin has been installed first.

6. Inbox component

<script setup lang="ts">
import { onUnmounted, ref, watch } from 'vue';
import type { InboxItem } from '@pushizo/web';
import { usePushizo } from '@pushizo/vue';

const { pushizo, ready } = usePushizo();
const items = ref<InboxItem[]>([]);
const unread = ref(0);
const loading = ref(false);
const error = ref<string | null>(null);
let stop: (() => void) | null = null;

async function load() {
  loading.value = true;
  try {
    const page = await pushizo.Inbox.list({ limit: 20 });
    items.value = page.items;
    unread.value = page.unreadCount;
    error.value = null;
  } catch (e) {
    error.value = e instanceof Error ? e.message : String(e);
  } finally {
    loading.value = false;
  }
}
async function markRead(id: string) {
  const updated = await pushizo.Inbox.markRead(id);
  items.value = items.value.map((i) => (i.id === id ? updated : i));
}
async function archive(id: string) {
  await pushizo.Inbox.archive(id);
  items.value = items.value.filter((i) => i.id !== id);
}

watch(ready, (r) => { if (r) { void load(); stop = pushizo.Inbox.addObserver((e) => { unread.value = e.unreadCount; }); } }, { immediate: true });
onUnmounted(() => stop?.());
</script>

<template>
  <section aria-label="Notification inbox">
    <h2>Notifications ({{ unread }} unread)</h2>
    <button type="button" :disabled="loading" @click="load">{{ loading ? 'Loading…' : 'Refresh' }}</button>
    <button type="button" @click="pushizo.Inbox.markAllRead().then(load)">Mark all as read</button>
    <p v-if="error" role="alert">{{ error }}</p>
    <p v-else-if="items.length === 0">No notifications.</p>
    <ul v-else>
      <li v-for="item in items" :key="item.id" :data-read="item.read">
        <strong>{{ item.title ?? '(untitled)' }}</strong>
        <p v-if="item.body">{{ item.body }}</p>
        <a v-if="item.url" :href="item.url">Open</a>
        <button type="button" :disabled="item.read" @click="markRead(item.id)">Read</button>
        <button type="button" @click="archive(item.id)">Archive</button>
      </li>
    </ul>
  </section>
</template>

7. Notification clicks

import { onNotificationClick } from '@pushizo/vue';

// inside setup: removed automatically when the component unmounts
onNotificationClick(({ notification, result }) => {
  router.push(result.url ?? notification.url ?? '/');
});

8. Troubleshooting

  • window is not defined: do not call @pushizo/web directly on the server; the @pushizo/vue plugin never calls init on the server.
  • usePushizo: önce app.use(PushizoPlugin, …) error ("call app.use(PushizoPlugin, …) first"): the composable was called before the plugin was installed.
  • Service worker 404 / no subscription created / notifications not arriving: Web SDK troubleshooting.
  • iOS Safari: iOS web push.

9. Alternative: setup without the package

Without @pushizo/vue, you can write your own plugin using only npm install @pushizo/web (in the sections above, use this file's usePushizo() → { sdk, ready, error, subscription } instead of the package's usePushizo()):

// src/pushizo.ts
import { inject, ref, type App, type InjectionKey, type Ref } from 'vue';
import Pushizo, { type PushizoSdk, type InitOptions, type PushSubscriptionState } from '@pushizo/web';

export interface PushizoState {
  sdk: PushizoSdk;
  ready: Ref<boolean>;
  error: Ref<string | null>;
  subscription: Ref<PushSubscriptionState | null>;
}

export const PushizoKey: InjectionKey<PushizoState> = Symbol('pushizo');

export function createPushizo(options: InitOptions) {
  const ready = ref(false);
  const error = ref<string | null>(null);
  const subscription = ref<PushSubscriptionState | null>(null);

  return {
    install(app: App) {
      app.provide(PushizoKey, { sdk: Pushizo, ready, error, subscription });
      if (typeof window === 'undefined') return; // SSR: don't touch browser APIs
      Pushizo.User.pushSubscription.addObserver((state) => { subscription.value = state; });
      Pushizo.init(options)
        .then(() => {
          ready.value = true;
          subscription.value = Pushizo.User.pushSubscription.state;
        })
        .catch((err: unknown) => { error.value = err instanceof Error ? err.message : String(err); });
    },
  };
}

export function usePushizo(): PushizoState {
  const state = inject(PushizoKey);
  if (!state) throw new Error('usePushizo cannot be used before the createPushizo plugin is installed');
  return state;
}
// src/main.ts
createApp(App)
  .use(createPushizo({ appId: import.meta.env.VITE_HS_APP_ID, apiUrl: import.meta.env.VITE_HS_API_URL, serviceWorkerPath: '/PushizoSDKWorker.js' }))
  .mount('#app');

On this path, permission changes are not reflected automatically (add Pushizo.Notifications.addPermissionObserver), and because usePushizo() uses inject, calling it outside a component/setup requires app.runWithContext(() => usePushizo()).

10. Feature flags, content cards and site search

The composables tie the Web SDK's observer and view APIs to the component scope: when the scope ends, observers are removed (FeatureFlags.removeObserver, Inbox.removeObserver, Notifications.removeForegroundLifecycleListener) and the content cards view is destroy()ed.

<script setup lang="ts">
import { ref } from 'vue';
import {
  onNotificationForeground,
  useContentCards,
  useFeatureFlag,
  useFeatureFlagValue,
  useInboxUnreadCount,
  usePushizoSearch,
} from '@pushizo/vue';

const newCheckout = useFeatureFlag('new_checkout'); // updates when flags refresh
const limit = useFeatureFlagValue<number>('cart_limit', 5);
const unread = useInboxUnreadCount(); // null: not known yet
const { response, loading, error, search, trackClick } = usePushizoSearch();

const cards = ref<HTMLElement | null>(null);
useContentCards(cards, { theme: 'auto', limit: 20 }); // rendered once the element is mounted and the SDK is ready

onNotificationForeground((e) => {
  if (document.visibilityState === 'visible') e.preventDefault();
});
</script>

<template>
  <span>Notifications<template v-if="unread"> ({{ unread }})</template></span>
  <p v-if="newCheckout">New checkout flow is on (limit {{ limit }})</p>

  <input type="search" @input="search(($event.target as HTMLInputElement).value, { limit: 5 })" />
  <p v-if="loading">Searching…</p>
  <p v-if="error" role="alert">Search failed.</p>
  <ul>
    <li v-for="(r, i) in response?.results ?? []" :key="r.id">
      <a :href="r.url" @click="trackClick(r.url, i + 1)">{{ r.title }}</a>
    </li>
  </ul>

  <div ref="cards" class="cards" />
</template>
  • useFeatureFlag / useFeatureFlagValue: return defaultValue until the SDK is ready and on the server; call them inside setup.
  • useContentCards: returns { error, refresh }; the view script is lazy-loaded. To bundle it instead, pass { mount: mountContentCards } (import { mountContentCards } from '@pushizo/web/content-cards').
  • usePushizoSearch: with back-to-back searches only the latest response is written; empty text clears the state. For the ready-made search dialog use pushizo.Search.open().
  • Login with a profile (pushizo.login('user_42', undefined, { email, tags })), the badge (pushizo.Notifications.setBadgeCount(3)), location permission (pushizo.Location.permissionGranted), custom in-app rendering (pushizo.InAppMessages.setRenderer) and chat (pushizo.Chat.getConfig() …) are used directly through usePushizo().pushizo.

On this page