Introduction

We've encountered the need to build realtime chat and messaging inside of many projects in our careers. We always passed on it due to time, cost, and maintaining yet another application. If you have worked on a project that has under taken chat, you know how much work goes into it. We've been working for almost exactly 5 months on bringing this product to market, so that everyone can offer full featured realtime chat and messaging at an affordable price.

There are numerous things we'd like to add and would love your feedback on what we should focus on next. Please feel free to contact us at any time to make requests or ask us for clarification on anything.

Getting Started

The easiest way is to use our JavaScript SDK to embed a chat box on the page. It's really easy. Head on over to https://userchat.io and click on 'get started for FREE'.

https://userchat.io

When the page loads, a new server key will be generated for you automatically. This will be your first server and can be used to try out the product or start implementing.

<link rel="stylesheet" href="https://cdn.userchat.io/userchat.css">
<script src="https://cdn.userchat.io/userchat.js"></script>
<script>
  window.userChatConfig = {
    key: 'YOUR SERVER KEY GOES HERE',

  };

  var userChat = require('user-chat-sdk').default;

  document.addEventListener("DOMContentLoaded", function() {
    userChat.box.create('#demo-chat', {
      id: 'demo.chat',
      name: 'Demo Chat'
    });
  });
</script>

Getting Started

Using the JavaScript SDK

Here is a breakdown of each part.

Import CSS and JavaScript from the User Chat CDN

<link rel="stylesheet" href="https://cdn.userchat.io/userchat.css">
<script src="https://cdn.userchat.io/userchat.js"></script>

User Chat JS SDK files are hosted on our CDN, backed by Cloudflare, so you know it will always be fast. There are two files you'll probably want to include, the default CSS and the minified JS. At the time of this writing the version 1.1.6 JS file is 359470 bytes and the CSS is 9600. When you include these files on the page without any version numbers, the most recent version will be automatically loaded. If you'd like to lock in to a particular version (not recommended), you can get a full directory listing at https://cdn.userchat.io.

Global Configuration

window.userChatConfig = {
  key: 'YOUR SERVER KEY GOES HERE',
  currentUser: {
    id: '0s89dfh09df8',
    name: 'Travis Mathis',
    email: '[email protected]'
  },
  apiUrl: 'https://userchat-api.yourdomain.com',
  boxUrl: 'https://userchat-box.yourdomain.com',
  cdnUrl: 'https://userchat-cdn.yourdomain.com',
  cssUrl: 'https://userchat-css.yourdomain.com/userchat.css',
  jsUrl: 'https://userchat-js.yourdomain.com/userchat.js',
  socketUrl: 'https://userchat-ws.yourdomain.com/'
};

We use a global window variable for the main configuration options. key is the only required option, which you can find in your server dashboard. Generally you will not need to use apiUrl, socketUrl, cdnUrl, or boxUrl - unless you're an Enterprise customer with onsite installation or host on your own cloud.

For custom css download our default css file, modify it, and host it yourself. Then pass it in as a url as the cssUrl config option.

Pass a currentUser object to define the chatting user, otherwise, chat will try to de-anonymize the visiting user. currentUser requires a valid id, email, and name.

Create your first chat box

Using raw JavaScript

document.addEventListener("DOMContentLoaded", function() {
  userChat.box.create('#demo-chat', {
    id: 'demo.chat',
    name: 'Demo Chat'
  });
});

Finally, we have the creation of the actual box. There's a good bit to digest here and several options that you'll want to know about. The first line here ensures that we don't try to create the box before the element is on the page.

document.addEventListener does this well.

If you have jQuery, feel free to use that approach instead.

Using jQuery

$(function() {
  userChat.box.create('#demo-chat', {
    id: 'demo.chat',
    name: 'Demo Chat'
  });
});

Call userChat.box.create to create a chat box.

This function takes two arguments. The first is required and is the id of the element you want to bind the chat box to. The element must rendered on the page before the chat box can be bound to it.

The second is a configuration object. While it is not required, it is highly recommend you set these yourself.

The configuration object can have the following four attributes:

id

This is a unique id for the thread. It is validated against a simple regex (~r/^[\w-\.|]+$/) and will error if it doesn't pass. For those of you who don't natively read regex, you can have upper or lowercase letters, any numbers, -, or . in your id. We recommend using UUIDv4 strings and will generate one for you if this option is omitted.

When email notifications are sent, a button will be included linking to the chat. This is that link. It defaults to window.location.href.

name

This is the title / name of the thread. It will appear at the top of the box and in the email notifications sent to your users.

users

Often, you'll want to pre-define the users who will receive email notifications and have access to the thread. To do this, pass an array of objects representing each user. Each object should have an id, email, and name property. The id value needs to follow the same rules as the thread id above. If omitted, we will automatically create a UUIDv4 for the user.

Core Concepts

User Chat was built to make it really simple to embed a chat box into any modern website. We do this in part by abstracting away a lot of complicated client / server interaction. We hope this section will help to give you a good idea of what's happening under the hood.

One important thing to note is that sockets are not required and will fall back to API requests if unavailable. This gives you a wide array of platform and browser support.

Initialization

userchat.init();

The User Chat JS SDK needs to be initialized before a chat box can be rendered. You can do it yourself, but really don't have to. The first time you create a new box, it's done automatically.

Chat Box

When we use the term 'chat box' we're referring to a rendered <UserChatBox> ReactJS component. The component and React are included with the User Chat JavaScript SDK. A box can be created or destroyed through a simple JS interface.

Create

userChat.box.create(idSelector, options);

Box creation is described in the create your first chat box section above. Behind the scenes, the SDK handles setting default options, creating the core objects and rendering the React component. It will delay until after SDK initialization, so if you experience lag, try initializing the SDK before calling create.

Destroy

userChat.box.destroy(id);

To destroy a chat box, call the destroy function with the id of the chat box's thread. This will remove the chat box from it's container element, but continue to receive data updates from the User Chat servers. That way, if you want to render the same thread again in another chat box it will load with no delays.

Destroy All

userChat.box.destroyAll();

If you have multiple chat boxes on the page and want to close all of them, use destroyAll. It's fast and easy.

Events

The User Chat JS SDK ships with it's own events system. After initialization, events can be subscribed to.

On

userChat.events.on('deanonymize', function(data) { ...do a thing });

Subscribe to an event.

The first argument is the event name, the second a callback function to be fired when the event is triggered. The callback function will receive any data passed when the event is broadcasted.

Off

Remove a single callback for an event

userChat.events.off('deanonymize', function(data) { ...do a thing });

Remove all callbacks for an event

userChat.events.off('deanonymize');

Remove one or all callbacks for a specific event.

As with on, the first argument is the event name. The second argument is optional. We don't recommend calling this function without a second argument unless you're implementing your own UI. Doing so has the potential to remove callback functions that are required by the provided chat box.

Broadcast

userChat.event.broadcast('some event', data);

Trigger an event.

Generally, you should never use this. The SDK fires events at the right time for the right reasons. When you call this function, all subscribed callbacks will be executed in the order they are received.

Create your own events

Example custom event

userChat.init();

userChat.events.on('my custom event', function(data) {
  console.log('custom event fired', data);
});

userChat.events.broadcast('my custom event', 'data here');

It's possible to piggyback on our events system if you need to. Creating your own events is as simple as calling the methods above.

The code in the right column will console log 'custom event fired' and 'data here'.

GraphQL API

Queries

The query type defines GraphQL operations that retrieve data from the server.

All GraphQL operations must specify their selections down to fields which return scalar values to ensure an unambiguously shaped response.

Message Query

Argument Type Description
message Message Returns a Message object

Input Fields

Input Field Type Description Required
uuid String A unique ID true

Return Fields

Return Field Type Description
message String message value
thread Thread Thread Object
timestamp Int Unix timestamp when message was CREATED
updated Int Unix timestamp when message was UPDATED
user User User Object
uuid ID A unique ID

Thread Query

Argument Type Description
thread Thread Returns a Thread object

Input Fields

Input Field Type Description Required
uuid String A unique ID true

Return Fields

Return Field Type Description
link String the return link used in user notifications
messages [Message] An array of Message objects
name String Chat thread name(ie: 'Barons Chat')
notify Boolean Notifications are enabled or disabled
users [User] An array of User objects with access to this chat instance
uuid ID A unique ID

User Query

Argument Type Description
user User Returns a User object

Input Fields

Input Field Type Description Required
uuid String A unique ID true

Return Fields

Return Field Type Description
email String A valid email address
name String The name a user will appear as in chat
updated Int Unix timestamp when user was last UPDATED
uuid ID A unique ID

Mutations

The mutation type defines GraphQL operations that change data on the server. It is analogous to performing HTTP verbs such as POST, PATCH, and DELETE.

All GraphQL operations must specify their selections down to fields which return scalar values to ensure an unambiguously shaped response.

Create Message

Payload

Argument Type Description
messageCreate Message CREATE a message

Input Fields

Input Field Type Description Required
message String A message true
threadId String A valid Thread ID true

Return Fields

Return Field Type Description
message String message value
thread Thread Thread Object
timestamp Int Unix timestamp when message was CREATED
updated Int Unix timestamp when message was UPDATED
user User User Object
uuid ID A unique ID

Destroy Message

Payload

Argument Type Description
messageDestroy Message DELETE a specific message
Input Fields
Input Field Type Description Required
uuid String A unique ID true

Update Message

Payload

Argument Type Description
messageUpdate Message UPDATE a message

Input Fields

Input Field Type Description Required
message String A message true
threadId String A valid Thread ID true
uuid String A unique ID true

Return Fields

Return Field Type Description
message String message value
thread Thread Thread Object
timestamp Int Unix timestamp when message was CREATED
updated Int Unix timestamp when message was UPDATED
user User User Object
uuid ID A unique ID

View Message

Payload

Argument Type Description
messageView Message Marks a message as viewed or seen by a user.

Input Fields

Input Field Type Description Required
uuid String A unique ID true

Create Thread

Payload

Argument Type Description
createThread Thread CREATE a chat thread

Input Fields

Input Field Type Description Required
link String A link provided to users when notified false
name String Name of the chat instance false
notify Boolean Enable or disable notifications for this chat instance false
users String A specific user access list for private chatrooms false
uuid String A unique ID true

Return Fields

Return Field Type Description
link String the return link used in user notifications
messages [Message] An array of Message objects
name String Chat thread name(ie: 'Barons Chat')
notify Boolean Notifications are enabled or disabled
users [User] An array of User objects with access to this chat instance
uuid ID A unique ID

Update Thread

Payload

Argument Type Description
updateThread Thread UPDATE a chat thread

Input Fields

Input Field Type Description Required
link String A link provided to users when notified false
name String Name of the chat instance false
notify Boolean Enable or disable notifications for this chat instance false
users String A specific user access list for private chatrooms false
uuid String A unique ID true

Return Fields

Return Field Type Description
link String the return link used in user notifications
messages [Message] An array of Message objects
name String Chat thread name(ie: 'Barons Chat')
notify Boolean Notifications are enabled or disabled
users [User] An array of User objects with access to this chat instance
uuid ID A unique ID

View Thread

Payload

Argument Type Description
threadView Thread Marks all messages in a thread as viewed or seen by a user.

Input Fields

Input Field Type Description Required
uuid String A unique ID true

Create User

Payload

Argument Type Description
userCreate User CREATE a user

Input Fields

Input Field Type Description Required
email String A valid email address true
name String The name a user will appear in chat as true
uuid String A unique ID false

Return Fields

Return Field Type Description
email String A valid email address
name String The name a user will appear as in chat
updated Int Unix timestamp when user was last UPDATED
uuid ID A unique ID

Update User

Payload

Argument Type Description
userUpdate User UPDATE a user

Input Fields

Input Field Type Description Required
email String A valid email address false
name String The name a user will appear in chat as false
uuid String A unique ID false

Return Fields

Return Field Type Description
email String A valid email address
name String The name a user will appear as in chat
updated Int Unix timestamp when user was last UPDATED
uuid ID A unique ID

Objects

Message Object

Field Type Description
message String message value
thread Thread Thread Object
timestamp Int Unix timestamp when message was CREATED
updated Int Unix timestamp when message was UPDATED
user User User Object
uuid ID A unique ID

Thread Object

Field Type Description
link String the return link used in user notifications
messages [Message] An array of Message objects
name String Chat thread name(ie: 'Barons Chat')
notify Boolean Notifications are enabled or disabled
users [User] An array of User objects with access to this chat instance
uuid ID A unique ID

User Object

Field Type Description
email String A valid email address
name String The name a user will appear as in chat
updated Int Unix timestamp when user was last UPDATED
uuid ID A unique ID

Scalars

Boolean

The Boolean scalar type represents true or false.

ID

The ID scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as "4") or integer (such as 4) input value will be accepted as an ID.

Int

The Int scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^53 - 1) and 2^53 - 1 since it is represented in JSON as double-precision floating point numbers specified by IEEE 754.

String

The String scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.

SDKs

Make sure you have the correct language examples selected in the top right of the page before continuing. If you don't see your language of choice shoot us a message.

Config

API Url

Current

Key

Release

Set User

Socket URL

Token

User

Socket

Connected

Events

Broadcast

Off

On

Messages

Create

Destroy

Get

Update

View

Threads

Create

Get

Update

Users

Create

Get

Update

Low Level API Wrapper

Queries

message

thread

user

Mutations

messageCreate

messageDestroy

messageUpdate

messageView

threadCreate

threadUpdate

userCreate

userUpdate