Skip to content

Basic Connection ​

Problem ​

You need one typed session whose messages are sent only after the transport is ready and whose lifecycle can be cleaned up deterministically.

Solution ​

Subscribe before connecting, then await connect() before sending.

ts
import { createPulse } from '@vielzeug/pulse';

type Schema = {
  server: { 'chat:message': { text: string } };
  client: { 'chat:send': { text: string } };
};

const pulse = createPulse<Schema>('wss://api.example.com/ws', {
  reconnect: true,
});
pulse.tap((event) => {
  if (event.type === 'error') console.error(event.error);
  if (event.type === 'status-change') console.log('status:', event.status);
});

const stop = pulse.on('chat:message', ({ text }) => console.log(text));

try {
  await pulse.connect();
  pulse.send('chat:send', { text: 'Hello!' });
} catch (error) {
  console.error('Pulse connection failed:', error);
}

stop();
pulse.dispose();

Pitfalls ​

  • Construction does not connect. Always await connect() before sending.
  • Sends do not buffer. Disconnected sends throw PulseConnectionError.
  • disconnect() cancels retries. Call connect() again to begin a new session.