Pushizo Web SDK with React
The primary path for React and Next.js is the @pushizo/react package: a single PushizoProvider initializes the shared @pushizo/web instance once in the browser, and hooks give you access to the SDK and the permission/subscription state. The package is SSR-safe…
The primary path for React and Next.js is the @pushizo/react package: a single PushizoProvider initializes the shared @pushizo/web instance once in the browser, and hooks give you access to the SDK and the permission/subscription state. The package is SSR-safe (init is never called on the server) and does not initialize the SDK a second time during React StrictMode's double effect in development. This guide covers Vite / Create React App and Next.js (App Router) setups, the service worker path, login/logout, tags/events and an inbox component. Setup without the package (only @pushizo/web) is in section 10. Working example: examples/web-nextjs.
1. Installation
npm install @pushizo/react @pushizo/web@pushizo/web is a peer dependency (peerDependency); React 18 or 19 is required.
The service worker must be at the site root: public/PushizoSDKWorker.js for Vite/CRA and Next.js.
// public/PushizoSDKWorker.js — the real worker is loaded from the API server; SDK updates arrive without touching your site.
const apiUrl = new URL(self.location.href).searchParams.get('apiUrl') || 'https://api.pushizo.com';
importScripts(`${apiUrl.replace(/\/$/, '')}/sdk-web/PushizoSDKWorker.js`);In Next.js, set a header in next.config.ts so the file can cover the whole site (examples/web-nextjs/next.config.ts):
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
async headers() {
return [
{
source: '/PushizoSDKWorker.js',
headers: [
{ key: 'Service-Worker-Allowed', value: '/' },
{ key: 'Cache-Control', value: 'no-cache' },
],
},
];
},
};
export default nextConfig;Environment variables: VITE_HS_APP_ID / VITE_HS_API_URL (Vite) or NEXT_PUBLIC_HS_APP_ID / NEXT_PUBLIC_HS_API_URL (Next.js). The App ID is not secret; the API key (hs_live_…) must never be put in the client.
2. Provider and hooks
PushizoProvider calls Pushizo.init with options; only the first value is used. An init error is not thrown; it is written to usePushizoState().error.
// src/pushizo-providers.tsx (Next.js: app/providers.tsx)
'use client'; // Next.js App Router; not needed in Vite/CRA
import type { ReactNode } from 'react';
import type { InitOptions } from '@pushizo/web';
import { PushizoProvider } from '@pushizo/react';
const options: InitOptions = {
appId: process.env.NEXT_PUBLIC_HS_APP_ID ?? '',
apiUrl: process.env.NEXT_PUBLIC_HS_API_URL ?? 'http://localhost:4000',
serviceWorkerPath: '/PushizoSDKWorker.js',
allowLocalhostAsSecureOrigin: process.env.NODE_ENV !== 'production', // development only
logLevel: 'warn',
bell: { enabled: true },
};
export function Providers({ children }: { children: ReactNode }) {
return <PushizoProvider options={options}>{children}</PushizoProvider>;
}| Hook | Returns |
|---|---|
usePushizo() | The shared SDK instance (login, User, Notifications, Session, InAppMessages, Inbox …) |
usePushizoState() | { ready, error, permission, pushSubscription } |
useNotificationPermission() | 'default' | 'granted' | 'denied' | 'unsupported' |
usePushSubscription() | { id, token, optedIn, permission } |
useNotificationClick(handler) | Notification click listener; removed when the component unmounts |
The state is fed by the web SDK's observers (Notifications.addPermissionObserver, User.pushSubscription.addObserver); the observers are removed when the provider unmounts. Hooks throw a descriptive error outside the provider.
Next.js root layout:
// app/layout.tsx
import { Providers } from './providers';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="tr">
<body>
<Providers>{children}</Providers>
</body>
</html>
);
}Vite: <Providers><App /></Providers> in main.tsx (with import.meta.env.VITE_HS_APP_ID in the options).
3. Permission and subscription button
import { useNotificationPermission, usePushizo, usePushizoState, usePushSubscription } from '@pushizo/react';
export function PushToggle() {
const sdk = usePushizo();
const { ready, error } = usePushizoState();
const permission = useNotificationPermission();
const subscription = usePushSubscription();
if (error) return <p role="alert">{error.message}</p>;
if (!ready) return <p>Loading SDK…</p>;
if (permission === 'unsupported') return <p>This browser does not support web push (HTTPS required).</p>;
if (permission === 'denied') return <p>Notifications are blocked in the browser settings.</p>;
return subscription.optedIn ? (
<button type="button" onClick={() => void sdk.User.pushSubscription.optOut()}>Turn off notifications</button>
) : (
<button type="button" onClick={() => void sdk.Notifications.requestPermission()}>Allow notifications</button>
);
}requestPermission() handles permission and subscription together; optIn() asks for permission if needed. useNotificationPermission updates even when the user changes the permission in the site settings (in browsers that support the Permissions API). Slidedown/bell prompts configured in the dashboard can also be enabled through init options (slidedown, bell, promptOptions).
4. Login / logout
Sync the SDK whenever your authentication state changes. If identity verification is required, identity_hash comes from your server (Pushizo.identityHash(sdkSecret, externalId) — Node/PHP SDK).
import { useEffect } from 'react';
import { usePushizo, usePushizoState } from '@pushizo/react';
export function useSyncIdentity(user: { id: string; identityHash?: string } | null) {
const sdk = usePushizo();
const { ready } = usePushizoState();
useEffect(() => {
if (!ready) return;
if (user) void sdk.login(user.id, user.identityHash);
else if (sdk.User.externalId) void sdk.logout();
}, [ready, sdk, user]);
}login links the anonymous device to the user (multiple devices are merged under the same user); logout moves the device to a new anonymous user.
5. Tags, properties and events
const sdk = usePushizo();
sdk.User.addTags({ plan: 'pro', city: 'İzmir' }); // offline queue; consecutive operations are merged
sdk.User.removeTag('plan');
sdk.User.setLanguage('tr');
sdk.Session.sendEvent('purchase', { sku: 'A1' }, 49.9); // event + conversion valueTag calls return synchronously and are written to a queue; sdk.User.getTags() returns the local copy. Events also fire in-app message triggers (event: purchase). These calls throw if made before init completes; call them once ready is true.
6. SPA route changes (in-app screen trigger)
For the screen trigger of in-app messages, report the screen name on every route change.
// Next.js App Router
'use client';
import { useEffect } from 'react';
import { usePathname } from 'next/navigation';
import { usePushizo, usePushizoState } from '@pushizo/react';
export function ScreenTracker() {
const sdk = usePushizo();
const { ready } = usePushizoState();
const pathname = usePathname();
useEffect(() => {
if (ready) sdk.InAppMessages.setScreen(pathname);
}, [ready, sdk, pathname]);
return null;
}Use the same approach with useLocation().pathname in React Router. During steps such as checkout, you can pause display with sdk.InAppMessages.paused = true.
7. Inbox component
Messages sent with add_to_inbox: true are listed through the Inbox API. A user and a subscription belonging to them (push, otherwise email/SMS) are required; otherwise Inbox.list throws a descriptive error — show empty/error states.
'use client';
import { useCallback, useEffect, useState } from 'react';
import type { InboxItem } from '@pushizo/web';
import { usePushizo, usePushizoState } from '@pushizo/react';
export function InboxPanel() {
const sdk = usePushizo();
const { ready } = usePushizoState();
const [items, setItems] = useState<InboxItem[]>([]);
const [unread, setUnread] = useState(0);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const load = useCallback(() => {
setLoading(true);
sdk.Inbox.list({ limit: 20 })
.then((page) => { setItems(page.items); setUnread(page.unreadCount); setError(null); })
.catch((e: unknown) => setError(e instanceof Error ? e.message : String(e)))
.finally(() => setLoading(false));
}, [sdk]);
useEffect(() => {
if (!ready) return;
load();
return sdk.Inbox.addObserver((e) => setUnread(e.unreadCount)); // type: listed | read | read_all | archived | count
}, [ready, sdk, load]);
const markRead = (id: string) =>
void sdk.Inbox.markRead(id).then((updated) => setItems((list) => list.map((i) => (i.id === id ? updated : i))));
const archive = (id: string) => void sdk.Inbox.archive(id).then(() => setItems((list) => list.filter((i) => i.id !== id)));
if (!ready) return null;
return (
<section aria-label="Notification inbox">
<header>
<h2>Notifications ({unread} unread)</h2>
<button type="button" onClick={load} disabled={loading}>{loading ? 'Loading…' : 'Refresh'}</button>
<button type="button" onClick={() => void sdk.Inbox.markAllRead().then(load)}>Mark all as read</button>
</header>
{error ? <p role="alert">{error}</p> : items.length === 0 ? <p>No notifications.</p> : (
<ul>
{items.map((item) => (
<li key={item.id} data-read={item.read}>
<strong>{item.title ?? '(untitled)'}</strong>
{item.body && <p>{item.body}</p>}
{item.url && <a href={item.url}>Open</a>}
<button type="button" disabled={item.read} onClick={() => markRead(item.id)}>Read</button>
<button type="button" onClick={() => archive(item.id)}>Archive</button>
</li>
))}
</ul>
)}
</section>
);
}Pagination: while page.hasMore, call sdk.Inbox.list({ cursor: page.nextCursor! }).
8. Notification clicks and foreground
import { useEffect } from 'react';
import { useNotificationClick, usePushizo } from '@pushizo/react';
useNotificationClick(({ notification, result }) => {
router.push(result.url ?? notification.url ?? '/'); // result.actionId: action button
});
const sdk = usePushizo();
useEffect(() => {
const offForeground = sdk.Notifications.addForegroundLifecycleListener((e) => {
if (document.visibilityState === 'visible') e.preventDefault(); // don't show a system notification while the page is open
});
return () => {
offForeground();
};
}, [sdk]);The click is forwarded to the page after the service worker brings the tab to the front; matching is configured with the notificationClickHandlerMatch / notificationClickHandlerAction init options.
9. Testing and troubleshooting
- "window is not defined": do not use the SDK (
@pushizo/web) directly in a server component; the@pushizo/reactprovider never callsiniton the server. - In development, use
allowLocalhostAsSecureOrigin: truefor HTTPlocalhost; HTTPS is required in production. - Service worker 404: the file is not at the root of
public/, orserviceWorkerPathis wrong. - No subscription is created: Dashboard → Channels → Web Push is not enabled (
vapid_public_keyis empty). - End to end: mark the record as a Test device under Subscriptions in the dashboard → Messages → Send test push → check
received/openedin Message Tracking. - For iOS Safari's add-to-home-screen and user gesture requirements, see iOS web push.
10. Alternative: setup without the package
You can build the same structure without @pushizo/react, using only npm install @pushizo/web. The provider and hook below do in your own code what the package does (in the sections above, use this file's usePushizo() → { sdk, ready, error, subscription } instead of the package's usePushizo()).
// src/pushizo/provider.tsx
'use client'; // Next.js App Router; not needed in Vite/CRA
import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';
import Pushizo, { type PushizoSdk, type PushSubscriptionState } from '@pushizo/web';
interface PushizoContextValue {
sdk: PushizoSdk;
ready: boolean;
error: string | null;
subscription: PushSubscriptionState | null;
}
const PushizoContext = createContext<PushizoContextValue | null>(null);
export function PushizoProvider({ appId, apiUrl, children }: { appId: string; apiUrl: string; children: ReactNode }) {
const [ready, setReady] = useState(false);
const [error, setError] = useState<string | null>(null);
const [subscription, setSubscription] = useState<PushSubscriptionState | null>(null);
useEffect(() => {
if (!appId) {
setError('App ID is not set');
return;
}
let cancelled = false;
const unsubscribe = Pushizo.User.pushSubscription.addObserver((state) => setSubscription(state));
Pushizo.init({
appId,
apiUrl,
serviceWorkerPath: '/PushizoSDKWorker.js',
allowLocalhostAsSecureOrigin: window.location.hostname === 'localhost', // development only
logLevel: 'warn',
bell: { enabled: true },
})
.then(() => {
if (cancelled) return;
setReady(true);
setSubscription(Pushizo.User.pushSubscription.state);
})
.catch((err: unknown) => {
if (!cancelled) setError(err instanceof Error ? err.message : String(err));
});
return () => {
cancelled = true;
unsubscribe();
};
}, [appId, apiUrl]);
const value = useMemo<PushizoContextValue>(() => ({ sdk: Pushizo, ready, error, subscription }), [ready, error, subscription]);
return <PushizoContext.Provider value={value}>{children}</PushizoContext.Provider>;
}
export function usePushizo(): PushizoContextValue {
const ctx = useContext(PushizoContext);
if (!ctx) throw new Error('usePushizo must be used within PushizoProvider');
return ctx;
}init is idempotent: React StrictMode running the effect twice in development causes no problem; the second call returns the promise of the first init. The cancelled flag only prevents writing state to an unmounted component. On this path, permission changes are not reflected in state automatically; add Pushizo.Notifications.addPermissionObserver if needed.
11. Feature flags, content cards and site search
The package ties the Web SDK's observer and view APIs to the component lifetime: observers are removed when the component unmounts (FeatureFlags.removeObserver, Inbox.removeObserver, Notifications.removeForegroundLifecycleListener) and the content cards view is destroy()ed.
import {
PushizoContentCards,
useFeatureFlag,
useFeatureFlagValue,
useInboxUnreadCount,
useNotificationForeground,
usePushizoSearch,
} from '@pushizo/react';
export function Home() {
const newCheckout = useFeatureFlag('new_checkout'); // re-renders when flags refresh
const limit = useFeatureFlagValue<number>('cart_limit', 5);
const unread = useInboxUnreadCount(); // null: not known yet
const { response, loading, error, search, trackClick } = usePushizoSearch();
useNotificationForeground((e) => {
if (document.visibilityState === 'visible') e.preventDefault();
});
return (
<main>
<span>Notifications{unread ? ` (${unread})` : ''}</span>
{newCheckout && <p>New checkout flow is on (limit {limit})</p>}
<input type="search" onChange={(e) => void search(e.target.value, { limit: 5 })} />
{loading && <p>Searching…</p>}
{error && <p role="alert">Search failed.</p>}
<ul>
{response?.results.map((r, i) => (
<li key={r.id}>
<a href={r.url} onClick={() => trackClick(r.url, i + 1)}>{r.title}</a>
</li>
))}
</ul>
{/* Ready-made card feed: loading/empty/error states live in the view */}
<PushizoContentCards options={{ theme: 'auto', limit: 20 }} className="cards" />
</main>
);
}useFeatureFlag/useFeatureFlagValue: returndefaultValueuntil the SDK is ready and on the server.PushizoContentCards:optionsis read on the first render only; the view script is lazy-loaded. To bundle it instead, passoptions={{ 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 useusePushizo().Search.open().- Login with a profile (
sdk.login('user_42', undefined, { email, tags })), the badge (sdk.Notifications.setBadgeCount(3)), location permission (sdk.Location.permissionGranted), custom in-app rendering (sdk.InAppMessages.setRenderer) and chat (sdk.Chat.getConfig()…) are used directly throughusePushizo().
AI setup prompts
Setup prompts live in this repository: docs/ai-prompts/. There is no separate public URL. A prompt calls the public API with your app's own API key. The key is never written into the prompt file.
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…