Client API

This guide covers the documentation around the Javascript client used for connecting to the websocket server.

Installation

You can install the package from npm and then bundle it using Webpack or rollup.

npm i @adonisjs/websocket-client

and then import it as follows

import Ws from '@adonisjs/websocket-client'
const ws = Ws('ws://localhost:3333')

Also you can grab the UMD bundle from unpkg.

<script src="https://unpkg.com/@adonisjs/websocket-client"></script>
<script>
  const ws = adonis.Ws('ws://localhost:3333')
</script>

Polyfill

The module build requires regenerator-runtime polyfill, so make sure to add it via babel.

Production builds

The development build contains a bunch of log statements, so it is recommended to use Webpack DefinePlugin or rollup-plugin-replace in order to define NODE_ENV.

Getting started

Let’s get started by connecting to the Websocket server and make some subscriptions.

If url is not defined, it will fallback to the current hostname. Otherwise a complete URL with ws protocol is required.
const ws = Ws(url, options)

// connect to the server
ws.connect()

options

Key Default Value Description

path

adonis-ws

The path to the used for making the connection. Only change, if you changed it on the server

reconnection

true

Whether or not make reconnect automatically after disconnect

reconnectionAttempts

10

Number to reconnection attempts to be made, before giving up

reconnectionDelay

1000

How long to wait, before reconnecting. The value will be used as n x delay, where n is the current value of reconnection attempts.

query

null

Query string to passed to the connection URL. You can pass an object

encoder

JsonEncoder

The encoder to be used. The same encoder will be required on the server too.

It is recommended to listen for open and close events, to manage your application state properly.

let isConnected = false

ws.on('open', () => {
  isConnected = true
})

ws.on('close', () => {
  isConnected = false
})

Once, connected you can subscribe to different/multiple topics.

const chat = ws.subscribe('chat')

chat.on('ready', () => {
  chat.emit('message', 'hello')
})

chat.on('error', (error) => {
  console.log(error)
})

chat.on('close', () => {
})

Subscription API

Following is the list of methods to be used for sending/receiving messages.

emit(event, data)

Send event to the server

chat.emit('message', {
  body: 'hello',
  user: 'virk'
})

on(event, callback)

Bind event listener

chat.on('message', () => {})
chat.on('new:user', () => {})

off(event, callback)

Remove event listener

const messageHandler = function () {}

chat.on('message', messageHandler)
chat.off(messageHandler)

close()

Initiate request to close the subscription. You must wait for the close event, to mark the subscription as closed.

chat.on('close', () => {
  // server acknowledged close
})

chat.close()

leaveError

The leaveError event is emitted, when server refuses to close the subscription. This ideally will never occur.

chat.on('leaveError', (response) => {
  console.log(response)
})

error

Emitted when error occurs on the TCP connection. Ideally you must be listening to ws.on('error') event.

chat.on('error', (event) => {
})

close

Emitted when subscription is closed.

chat.on('close', () => {
})

Ws API

Below is the list of methods available on a single ws connection.

const ws = Ws(url, options)

connect

Initiate the connection

ws.connect()

close

Forcefully close the connection. After this, all subscription will removed and no reconnection will be triggered.

ws.close()

getSubscription(topic)

Returns instance of a subscription for a given topic. If there is no subscription null will be returned.

ws.subscribe('chat')

ws.getSubscription('chat').on('message', () => {
})

subscribe(topic)

Subscribe to a topic. Subscribing to the same topic twice, will raise an exception.

const chat = ws.subscribe('chat')

Authentication

The Javascript client makes it super easy to authenticate users. The auth credentials are only passed once to the server, during the initial connection and then same information can be reused to allow or disallow channel subscriptions.

If you are using sessions, then user will be authenticated automatically, if they have a valid session.

withBasicAuth(username, password)

Authenticate user using basic auth

const ws = Ws(url, options)

ws
  .withBasicAuth(username, password)
  .connect()

withApiToken(token)

Authenticate user using api token

const ws = Ws(url, options)

ws
  .withApiToken(token)
  .connect()

withJwtToken(token)

Authenticate user using JWT token

const ws = Ws(url, options)

ws
  .withJwtToken(token)
  .connect()

On the server, you can access the user information from the auth object.

You must setup required middleware before running the following code. Learn more about middleware
Ws.channel('chat', ({ auth }) => {
  console.log(auth.user)
})

In order to enforce authenticated connections, make sure to define the named middleware.

Ws.channel('chat', ({ auth }) => {
  console.log(auth.user)
}).middleware(['auth'])