# Live updates in Qwik

> Connect to Hibira from a Qwik component only once it is visible, so pusher-js stays out of the first load, and sign private channels in a Qwik City endpoint.

Source: https://hibira.io/guides/qwik

Connect to Hibira from a Qwik component only once it is visible, so pusher-js stays out of the first load, and sign private channels in a Qwik City endpoint.

Package: pusher-js

- useVisibleTask$ loads pusher-js on demand and disconnects on cleanup.
- A Qwik City onPost endpoint signs private and presence channels with the pusher npm package.

## 1. Install

```shell
npm install pusher-js pusher
```

## 2. Use it

```tsx
import { component$, useSignal, useVisibleTask$ } from '@builder.io/qwik';

export default component$(() => {
  const status = useSignal('Waiting for updates');
  useVisibleTask$(async ({ cleanup }) => {
    const { default: Pusher } = await import('pusher-js');
    const pusher = new Pusher(import.meta.env.PUBLIC_HIBIRA_APP_KEY, {
      cluster: 'hkg',
      wsHost: 'ws.hibira.io',
      channelAuthorization: { endpoint: '/api/hibira/auth', transport: 'ajax' },
    });
    pusher.subscribe('orders').bind('order.shipped', (o: { id: number }) => (status.value = `Order #${o.id} shipped`));
    cleanup(() => pusher.disconnect());
  });
  return <p>{status.value}</p>;
});
```

## 3. Sign channel subscriptions

```ts
// src/routes/api/hibira/auth/index.ts
import type { RequestHandler } from '@builder.io/qwik-city';
import Pusher from 'pusher';

export const onPost: RequestHandler = async ({ parseBody, env, json }) => {
  const pusher = new Pusher({
    appId: env.get('HIBIRA_APP_ID')!, key: env.get('HIBIRA_APP_KEY')!, secret: env.get('HIBIRA_APP_SECRET')!,
    host: 'ws.hibira.io', port: '443', useTLS: true,
  });
  const form = (await parseBody()) as Record<string, string>;
  // check the signed-in user may join this channel first
  json(200, pusher.authorizeChannel(form.socket_id, form.channel_name));
};
```

## Before you start

- On the Free plan, list every origin your pages load from in the app’s allowed origins (http://localhost:3000 while developing, then your domain). "*" needs a paid plan.
- The app secret is shown only once, when you create the app or rotate its secret. Keep it on your server, never in a browser or game build.

- [npm](https://www.npmjs.com/package/pusher-js)
- [npm](https://www.npmjs.com/package/pusher)
