First steps with Chat
Quickly implement a full-fledged chat into your web application.
Installation
First, you need to obtain the JavaScript SDK using one of these two methods.
Using npm
If you are using npm, from your terminal you can run:
npm install @signalwire/js
Then, include the package in JavaScript as follows:
import * as SignalWire from '@signalwire/js'
Using a CDN
You can import the library from a CDN into your HTML file: paste the following within the <head>
section of your page:
<script src="https://cdn.signalwire.com/@signalwire/js"></script>
A global SignalWire
variable will be available for use by JavaScript.
Getting a token
The chat is organized in channels. To start receiving messages from a channel, you need an authentication token which grants you access to that channel. To get a demo token:
const res = await fetch("https://guides.swrooms.com/public/chat_token", {
method: "POST",
headers: {
"accept": "application/json",
"content-type": "application/json",
},
body: JSON.stringify({
member_id: "my-unique-id",
channels: {
"my-channel-name": {
read: true,
write: true
}
},
state: {}
})
});
const reply = await res.json()
// token is in reply.token
Make sure to wrap the code into an async
function to be able to use await
.
Receiving messages
Now you can use the token to initialize a client and start receiving messages:
const chatClient = new SignalWire.Chat.Client({
token: reply.token
});
await chatClient.subscribe(["my-channel-name"]);
chatClient.on("message", msg => {
console.log(msg.member.id, "says", msg.content)
});
Sending messages
After you have initialized a client, you can use it for sending messages too. For example:
chatClient.publish({
channel: "my-channel-name",
content: "Hello, world!"
});
Next steps
Congratulations! You have now created your own basic chat application.
In this example, we made a POST request to an endpoint located at https://guides.swrooms.com/public/chat_token
to obtain a token. While this works for demo purposes, it has some limitations:
- Channels and users are shared across all applications using the same endpoint
- Some APIs are limited
- swrooms.com is not supported for production applications
Having your own server will also allow you to access the following additional APIs and SDKs:
- REST APIs: create and manage tokens
- Realtime SDK: receive events from active chat rooms and control them server-side.
To access these full capabilities, you should provide your own chat_token
endpoint using your own server. Follow the guide to keep learning: