Pushizo Web SDK with Angular
The primary path for Angular is the @pushizo/angular package: providePushizo(options) (standalone) or PushizoModule.forRoot(options) (NgModule) initializes the shared @pushizo/web instance once in the browser at app startup;…
The primary path for Angular is the @pushizo/angular package: providePushizo(options) (standalone) or PushizoModule.forRoot(options) (NgModule) initializes the shared @pushizo/web instance once in the browser at app startup; PushizoService exposes the SDK and the permission/subscription state as Signals and Observables. On the server (Angular SSR, isPlatformBrowser false) the SDK is never touched. This guide is based on the Angular 17+ standalone architecture. Setup without the package (only @pushizo/web) is in section 9.
1. Installation
npm install @pushizo/angular @pushizo/web@pushizo/web is a peer dependency (peerDependency); @angular/core and @angular/common 17 or later and rxjs 7 are required. The package ships in Angular's partial compilation format; the Angular CLI links it during the application build.
The service worker must be served from the site root. Create the src/PushizoSDKWorker.js file and add it to the angular.json assets list with root output:
// src/PushizoSDKWorker.js
const apiUrl = new URL(self.location.href).searchParams.get('apiUrl') || 'https://api.pushizo.com';
importScripts(`${apiUrl.replace(/\/$/, '')}/sdk-web/PushizoSDKWorker.js`);"assets": [
{ "glob": "**/*", "input": "public" },
{ "glob": "PushizoSDKWorker.js", "input": "src", "output": "/" }
]If you use Angular PWA (@angular/pwa, ngsw-worker.js), two service workers cannot register in the same scope (/). Two options:
- Register the Pushizo worker in a different scope:
serviceWorkerScope: '/pushizo/'(push subscriptions work independently of the scope; a notification click still opens theurl). Since the scope is narrower than the file location, no extra header is needed. - Or skip ngsw and add the
importScriptsline to your own worker.
Environment: hsAppId, hsApiUrl in src/environments/environment.ts.
2. Provider and service
// src/app/app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { providePushizo } from '@pushizo/angular';
import { routes } from './app.routes';
import { environment } from '../environments/environment';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
// Does not block startup: init runs in the background; components watch the `ready()` signal.
providePushizo({
appId: environment.hsAppId,
apiUrl: environment.hsApiUrl,
serviceWorkerPath: '/PushizoSDKWorker.js',
allowLocalhostAsSecureOrigin: !environment.production,
bell: { enabled: true },
}),
],
};In NgModule projects, in the root module: imports: [BrowserModule, PushizoModule.forRoot({ appId: environment.hsAppId, apiUrl: environment.hsApiUrl })].
PushizoService (in the root injector) provides:
| Member | Description |
|---|---|
sdk | The shared SDK instance (login, User, Notifications, Session, InAppMessages, Inbox …) |
ready(), error() | init completed / error (an init error is not thrown; it is written here) |
permission() | 'default' | 'granted' | 'denied' | 'unsupported' |
pushSubscription() | { id, token, optedIn, permission } |
state() / state$ | The entire state (Signal / Observable) |
permission$, pushSubscription$ | Observables that emit on change (they emit the latest value immediately) |
notificationClick$ | Notification clicks; the SDK listener is removed when the subscription ends |
The state is fed by the web SDK's observers, and updates run inside NgZone. When the root injector is destroyed, the observers are removed and the Observables complete.
3. Permission and subscription component
// src/app/push-toggle.component.ts
import { Component, inject } from '@angular/core';
import { PushizoService } from '@pushizo/angular';
@Component({
selector: 'app-push-toggle',
standalone: true,
template: `
@if (hs.error(); as error) {
<p role="alert">{{ error.message }}</p>
} @else if (!hs.ready()) {
<p>Loading SDK…</p>
} @else if (hs.permission() === 'unsupported') {
<p>This browser does not support web push (HTTPS required).</p>
} @else if (hs.permission() === 'denied') {
<p>Notifications are blocked in the browser settings.</p>
} @else if (hs.pushSubscription().optedIn) {
<button type="button" (click)="hs.sdk.User.pushSubscription.optOut()">Turn off notifications</button>
} @else {
<button type="button" (click)="hs.sdk.Notifications.requestPermission()">Allow notifications</button>
}
`,
})
export class PushToggleComponent {
readonly hs = inject(PushizoService);
}In templates that prefer RxJS: hs.pushSubscription$ | async.
4. Login / logout
Hook it up to your authentication service's user stream:
// src/app/auth.service.ts (relevant part)
import { Injectable, effect, inject, signal } from '@angular/core';
import { PushizoService } from '@pushizo/angular';
@Injectable({ providedIn: 'root' })
export class AuthService {
private readonly hs = inject(PushizoService);
readonly user = signal<{ id: string; identityHash?: string } | null>(null);
constructor() {
effect(() => {
if (!this.hs.ready()) return;
const user = this.user();
if (user) void this.hs.sdk.login(user.id, user.identityHash); // identity_hash: HMAC-SHA256(sdk_secret, external_id), generated on the server
else if (this.hs.sdk.User.externalId) void this.hs.sdk.logout();
});
}
}5. Tags, events and route tracking
hs.sdk.User.addTags({ plan: 'pro' });
hs.sdk.User.removeTag('plan');
hs.sdk.Session.sendEvent('purchase', { sku: 'A1' }, 49.9);Report route changes for the in-app screen trigger:
// src/app/app.component.ts
import { Component, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs';
import { PushizoService } from '@pushizo/angular';
@Component({ selector: 'app-root', standalone: true, template: '<router-outlet />' })
export class AppComponent {
private readonly hs = inject(PushizoService);
constructor() {
inject(Router)
.events.pipe(filter((e): e is NavigationEnd => e instanceof NavigationEnd), takeUntilDestroyed())
.subscribe((e) => {
if (this.hs.ready()) this.hs.sdk.InAppMessages.setScreen(e.urlAfterRedirects);
});
}
}6. Inbox component
// src/app/inbox.component.ts
import { Component, DestroyRef, effect, inject, signal } from '@angular/core';
import type { InboxItem } from '@pushizo/web';
import { PushizoService } from '@pushizo/angular';
@Component({
selector: 'app-inbox',
standalone: true,
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)="markAllRead()">Mark all as read</button>
@if (error()) {
<p role="alert">{{ error() }}</p>
} @else if (items().length === 0) {
<p>No notifications.</p>
} @else {
<ul>
@for (item of items(); track item.id) {
<li [attr.data-read]="item.read">
<strong>{{ item.title ?? '(untitled)' }}</strong>
@if (item.body) { <p>{{ item.body }}</p> }
@if (item.url) { <a [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>
`,
})
export class InboxComponent {
private readonly hs = inject(PushizoService);
readonly items = signal<InboxItem[]>([]);
readonly unread = signal(0);
readonly loading = signal(false);
readonly error = signal<string | null>(null);
constructor() {
const destroyRef = inject(DestroyRef);
effect(() => {
if (!this.hs.ready()) return;
void this.load();
const stop = this.hs.sdk.Inbox.addObserver((e) => this.unread.set(e.unreadCount));
destroyRef.onDestroy(stop);
});
}
async load() {
this.loading.set(true);
try {
const page = await this.hs.sdk.Inbox.list({ limit: 20 });
this.items.set(page.items);
this.unread.set(page.unreadCount);
this.error.set(null);
} catch (e) {
this.error.set(e instanceof Error ? e.message : String(e)); // descriptive error if there is no user/subscription
} finally {
this.loading.set(false);
}
}
async markRead(id: string) {
const updated = await this.hs.sdk.Inbox.markRead(id);
this.items.update((list) => list.map((i) => (i.id === id ? updated : i)));
}
async markAllRead() {
await this.hs.sdk.Inbox.markAllRead();
await this.load();
}
async archive(id: string) {
await this.hs.sdk.Inbox.archive(id);
this.items.update((list) => list.filter((i) => i.id !== id));
}
}7. Notification clicks
// Inside a component or a root service
inject(PushizoService)
.notificationClick$.pipe(takeUntilDestroyed())
.subscribe(({ notification, result }) => {
void router.navigateByUrl(result.url ?? notification.url ?? '/');
});When the subscription ends (takeUntilDestroyed), the SDK listener is removed as well. Events are emitted inside NgZone; zone-based templates need no extra handling.
8. Troubleshooting
NullInjectorError: No provider for PushizoService:providePushizo(...)orPushizoModule.forRoot(...)has not been added.ReferenceError: window is not defined(SSR): do not call@pushizo/webdirectly on the server; the package does not runiniton the server.- Service worker scope conflict (ngsw): use
serviceWorkerScope: '/pushizo/'. PushizoSDKWorker.js404: theangular.jsonassetsentry must write to the root output ("output": "/").- Other symptoms: Web SDK troubleshooting; for iOS Safari, iOS web push.
9. Alternative: setup without the package
Without @pushizo/angular, you can write your own service using only npm install @pushizo/web (in the sections above, use the permission getter instead of permission(), and subscription() instead of pushSubscription()):
// src/app/pushizo.service.ts
import { Injectable, PLATFORM_ID, inject, signal } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import Pushizo, { type PushizoSdk, type InitOptions, type PushSubscriptionState } from '@pushizo/web';
import { environment } from '../environments/environment';
@Injectable({ providedIn: 'root' })
export class PushizoService {
readonly sdk: PushizoSdk = Pushizo;
readonly ready = signal(false);
readonly error = signal<string | null>(null);
readonly subscription = signal<PushSubscriptionState | null>(null);
private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
/** Called from `provideAppInitializer`; does nothing during SSR (Angular Universal). */
async init(options?: Partial<InitOptions>): Promise<void> {
if (!this.isBrowser) return;
this.sdk.User.pushSubscription.addObserver((state) => this.subscription.set(state));
try {
await this.sdk.init({
appId: environment.hsAppId,
apiUrl: environment.hsApiUrl,
serviceWorkerPath: '/PushizoSDKWorker.js',
allowLocalhostAsSecureOrigin: !environment.production,
bell: { enabled: true },
...options,
});
this.ready.set(true);
this.subscription.set(this.sdk.User.pushSubscription.state);
} catch (err) {
this.error.set(err instanceof Error ? err.message : String(err));
}
}
get permission() {
return this.ready() ? this.sdk.Notifications.permission : 'default';
}
requestPermission() {
return this.sdk.Notifications.requestPermission();
}
login(externalId: string, identityHash?: string) {
return this.sdk.login(externalId, identityHash);
}
logout() {
return this.sdk.User.externalId ? this.sdk.logout() : Promise.resolve();
}
}// src/app/app.config.ts
import { ApplicationConfig, provideAppInitializer, inject } from '@angular/core';
import { PushizoService } from './pushizo.service';
export const appConfig: ApplicationConfig = {
providers: [
// init is not awaited so it does not block app startup; components watch the `ready()` signal.
provideAppInitializer(() => {
void inject(PushizoService).init();
}),
],
};In NgModule projects: { provide: APP_INITIALIZER, useFactory: (hs: PushizoService) => () => { void hs.init(); }, deps: [PushizoService], multi: true }. On this path, SDK callbacks may arrive outside the zone; in zone-based template bindings, update inside NgZone.run.
10. Feature flags, content cards and site search
PushizoService exposes the Web SDK's observer and view APIs as Signals, Observables and a directive: when the subscription ends or the injector is destroyed, observers are removed (FeatureFlags.removeObserver, Inbox.removeObserver, Notifications.removeForegroundLifecycleListener) and the content cards view is destroy()ed.
import { Component, inject, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { PushizoContentCardsDirective, PushizoService } from '@pushizo/angular';
import type { SearchResponse } from '@pushizo/web';
@Component({
selector: 'app-home',
standalone: true,
imports: [PushizoContentCardsDirective],
template: `
<span>Notifications @if (unread()) { ({{ unread() }}) }</span>
@if (newCheckout()) { <p>New checkout flow is on (limit {{ limit() }})</p> }
<input type="search" (input)="search($any($event.target).value)" />
<ul>
@for (r of results()?.results ?? []; track r.id) {
<li><a [href]="r.url">{{ r.title }}</a></li>
}
</ul>
<!-- Ready-made card feed: loading/empty/error states live in the view -->
<div pushizoContentCards [pushizoContentCardsOptions]="{ theme: 'auto', limit: 20 }"></div>
`,
})
export class HomeComponent {
private readonly pushizo = inject(PushizoService);
readonly newCheckout = this.pushizo.featureFlag('new_checkout'); // updates when flags refresh
readonly limit = this.pushizo.featureFlagValue<number>('cart_limit', 5);
readonly unread = this.pushizo.inboxUnreadCount; // null: not known yet
readonly results = signal<SearchResponse | null>(null);
constructor() {
void this.pushizo.init().then(() => this.pushizo.refreshInboxUnreadCount()).catch(() => undefined);
this.pushizo.notificationForeground$.pipe(takeUntilDestroyed()).subscribe((e) => {
if (document.visibilityState === 'visible') e.preventDefault();
});
}
async search(text: string): Promise<void> {
this.results.set(text.trim() ? await this.pushizo.search(text, { limit: 5 }) : null);
}
}featureFlag/featureFlagValue: returndefaultValueuntil the SDK is ready and on the server.featureFlagsChange$andinboxChange$are available as streams too.- Instead of the
pushizoContentCardsdirective you can set up the view yourself withrenderContentCards(element, options)and call the handle'sdestroy(). To bundle the view, pass{ mount: mountContentCards }(import { mountContentCards } from '@pushizo/web/content-cards'). - For the ready-made search dialog use
pushizo.sdk.Search.open(); for click measurement usepushizo.sdk.Search.trackClick(queryId, url). - 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 throughPushizoService.sdk.
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…
SDK overview
Client (Web, iOS, Android, Flutter and bridges) and server (Node, PHP, Python, Go, Java, .NET, Ruby) SDKs; shared concepts and end-to-end verification.