# WebSockets (Socket.IO)

What is WebSocket

The **WebSocket API,** built on [socket.io](https://socket.io/) technology, is an advanced feature that makes it possible to open a two-way interactive communication session between a user's browser and a server. Through this API, you can send messages to the server and receive event-driven responses, all without the need to continuously poll the server for replies.

### How to Add WebSockets to Your App:

1\) Select the app you want to add a WebSocket to

2\) Go to the Plugins section and install the Socket.io plugin.

<figure><img src="https://3071851461-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M4Nnmtk9_gFGWOddsf6%2Fuploads%2FvQ2U3fyHNWeEL0o9PMjG%2F1.jpg?alt=media&#x26;token=38d4d567-9972-47c2-ac4d-f422346499ec" alt=""><figcaption></figcaption></figure>

### Where Can You Use WebSocket API (Socket.IO)?

If you use [Directual web-page builder](https://readme.directual.com/web-pages/portal):

* Refresh the page (e.g. update the content after submitting the form — that is an alternative to [synchronous scenarios](https://readme.directual.com/scenarios/synchronic-scenarios-1))
* Alert users with Toast notifications
* Redirect user

If you use external front-end (e.g., [ReactJS](https://readme.directual.com/directual-react-js/boilerplate-for-react-js)):

* Receive signals about changes in systems and refresh data instantly
* Build interactive messengers 💬
* Build scenarios with messages for specific users (alerts, notifications and etc.).

### How to Use Sockets for user notifications

1. Create a scenario that calls socket plugin (send PUSH-message step)
2. Set "Event name" to **`alert`**
3. Configure your message.&#x20;

There are two options for configuring the message: simple and complex.

Simple notification:

<figure><img src="https://3071851461-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M4Nnmtk9_gFGWOddsf6%2Fuploads%2FyD9CYsL9ZXhHLr9gi3Zh%2Fimage.png?alt=media&#x26;token=4865c6f7-209f-4559-900c-a33aefeb15f4" alt=""><figcaption></figcaption></figure>

Complex notification (with notification settings like page to display on, position, duration, etc.)

Notifications are based on [React-hot-toast](https://react-hot-toast.com/). Find the full list of parameters [here](https://react-hot-toast.com/docs/toast)

Example of a message:

<pre class="language-json"><code class="lang-json">{
    "message": "Hello world! My name is {{name}}",
    "parameters": {
      "position": "top-right",
      "duration": 4000,
      "icon": "🇷🇺"
    }
}
<strong>
</strong><strong>// if you want to send push to the certain page (or a few, comma separated) and its subpages (my-home-page)
</strong>{
    "message": "Hello world! My name is {{name}}",
    "page": "my-home-page,profile",
    "parameters": {
      "position": "top-right",
      "duration": 4000,
      "icon": "🇷🇺"
    }
}
</code></pre>

Message in the app:

<figure><img src="https://3071851461-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M4Nnmtk9_gFGWOddsf6%2Fuploads%2F9Vp6jxxnudnTNInFZpyr%2Ftoast.gif?alt=media&#x26;token=974ae56f-bef3-4471-9a9c-389c9a5d03a0" alt=""><figcaption></figcaption></figure>

### How to Use Sockets for redirecting user

1. Create a scenario that calls socket plugin (send PUSH-message step)
2. Set "Event name" to `redirect`
3. Configure redirect details in message field:

```
{
   "target": "/my-page",
   "delay": 200
}

// or optioannly with indicating page/pages (comma separated)

{
   "target": "<=",
   "page": "my-home-page,profile",
   "delay": 200
}
```

&#x20;A redirection will occur based on our routing rules. The rules for redirection are as follows:

* `<=` – navigate back in history
* `../` – move up in the directory
* `../../` – move up two levels, and so on
* `./param` – append a parameter to the right in the URL.

### How to Use Sockets in Web-page Builder as a refresher

1. Create a scenario that calls socket plugin (send PUSH-message step)
2. Add a refresher to the page (if needed)

The Refresher web-plugin (indicate the `event_name`):

<figure><img src="https://3071851461-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M4Nnmtk9_gFGWOddsf6%2Fuploads%2FWSvAjGdrYRg0wu4SrSed%2Ffps_sockets_plugin.gif?alt=media&#x26;token=010db8cd-cf4c-4347-a76c-7d08cd136e60" alt=""><figcaption></figcaption></figure>

Scenario with the same `event_name`:

<figure><img src="https://3071851461-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M4Nnmtk9_gFGWOddsf6%2Fuploads%2Fftst1JXLOkZPwMyo7BwF%2Ffps_sockets_plugin_settings.gif?alt=media&#x26;token=d4f25d08-a5e1-476e-8239-b221a66dc075" alt=""><figcaption><p>In this case scenario triggers on Changed objects</p></figcaption></figure>

* **Message**: no need here (although you can combine refresher and user notifications)
* **Event name**: the same `event_name`
* **UserID**: set `*` if you want to broadcast the message. set user's ID if you want to send a message to a certain user.

Here is how it works:

<figure><img src="https://3071851461-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M4Nnmtk9_gFGWOddsf6%2Fuploads%2Fe167zXGlIJoMSLKQ4Khe%2Ffps_sockets.gif?alt=media&#x26;token=5725a593-7dd9-4619-91ac-9c3bac298d85" alt=""><figcaption></figcaption></figure>

### How to Use WebSockets in React Apps

You can find an example template with Socket.IO support in [Directual and React JS](https://readme.directual.com/directual-react-js/boilerplate-for-react-js) section.

1. [Clone the repo](https://github.com/directual/directual-react-boilerplate#step-1-cloning-directual-react-boilerplate-repo)
2. [Copy your Directual APP ID into .env file](https://github.com/directual/directual-react-boilerplate#step-2-copying-your-directual-app-id-into-env-file)
3. [Create a user and log in](https://github.com/directual/directual-react-boilerplate#step-3-testing-authentication) (for example, the user's ID is `testUser`)
4. Go to `WebSocket Page`
5. Create a scenario, add **Send PUSH-message** step (it is a part of Socket.io plugin):

<figure><img src="https://3071851461-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M4Nnmtk9_gFGWOddsf6%2Fuploads%2FMPo9P2DT8nTPA5YGLPGs%2Fsocket-step.gif?alt=media&#x26;token=fbeb6466-5615-4f14-9f12-7da1a6ca23fe" alt=""><figcaption></figcaption></figure>

Configuring the step:

<figure><img src="https://3071851461-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M4Nnmtk9_gFGWOddsf6%2Fuploads%2FOnlqBiqxKJNmm6VcSm9W%2Fimage.png?alt=media&#x26;token=efe6b2a6-d805-4165-959b-f2bb3b42dc0f" alt=""><figcaption></figcaption></figure>

* **UserID**: set `*` if you want to broadcast the message. set user's ID if you want to send a message to a certain user (in our case — testUser`)`
* **Event name**: the first parameter of socket event (`eventName`)
* **Message**: the second parameter of socket event (`args`)

Have a look at the boilerplate, [websocket.js](https://github.com/directual/directual-react-boilerplate/blob/master/src/pages/Websocket.js):

```javascript
//subscribe to any events
socket.onAny((eventName, args) => {
        setMessage(<div>{`${eventName}: ${JSON.stringify(args)}`} &nbsp;<code>{(new Date()).toISOString()}</code></div>);
});

//subscribe to only 'message' events (the 'Event name' parameter)
socket.on('message', (msg) => {
    setMessage(<div>{msg} &nbsp;<code>{(new Date()).toISOString()}</code></div>);
})
```

Here is how it works (we send objects to the scenario, the web-page is refreshed without reload):

<figure><img src="https://3071851461-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M4Nnmtk9_gFGWOddsf6%2Fuploads%2F5vdTBaHPzM9SA7xVU04R%2Fsockets.gif?alt=media&#x26;token=18f18e85-00ff-4207-bcad-337e9b318d44" alt=""><figcaption></figcaption></figure>

### How to Use WebSocket API in Any Apps

You can use any WebSocket API (Socket.IO) client in any app.

Directual offers a standard endpoint for connection to WebSockets: <https://api.directual.com>

You can see how to connect and receive messages from the Platform in the code below:

```javascript
import io from 'socket.io-client';

// autoConnect set to false, 
// because before we must get session_id for auth users
const socket = io('https://api.directual.com', {autoConnect: false})

var sessionID = ? // you'll get sessioID when authorise your user
var appID = ? // you could get appID in API section
//login users process...

socket.auth = {app_id: appID, session_id: sessionID};
socket.connect();

//subscribe to any events
socket.onAny((eventName, args) => {
   console.log(`${eventName}: ${JSON.stringify(args)}`);
});

//subscribe to only 'message' events
socket.on('message', (msg) => {
   console.log(msg);
})

```
