Node.js server SDK

Node.js SDK for the Chatkit service.

Setting Up

Installing

Via npm:

npm install @pusher/chatkit-server --save

Via yarn:

yarn add @pusher/chatkit-server

Importing

If you’re using a transpiler or a sufficiently up-to-date browser then you can import the SDK like this:

import Chatkit from '@pusher/chatkit-server';

If not, then you can import it using the standard require syntax:

const Chatkit = require('@pusher/chatkit-server');

Instantiating the Client object

The Client constructor takes an options object with the following properties:

Example
1
2
3
4
const chatkit = new Chatkit.default({
  instanceLocator: YOUR_INSTANCE_LOCATOR,
  key: YOUR_KEY,
})

SDK Usage

Unless otherwise specified, a promise will be returned from each function call made using the SDK.

All functions take a single object as the expected argument. The expected shape of the object is described in the documentation below.

As such, a typical usage would look something like this:

1
2
3
4
5
6
7
8
9
chatkit.createUser({
  id: 'userId',
  name: 'Some Name',
})
  .then(() => {
    console.log('User created successfully');
  }).catch((err) => {
    console.log(err);
  });

Users

Creating a User

Create a new User to use with the Chatkit service.

Usage

The createUser method takes a single object of the form:

  • id (string, required): An ID that uniquely identifies a User in the Chatkit service.
  • name (string, required): A name assigned to the user.
  • avatarURL (string, optional): Valid URL pointing to an image.
  • customData (map, optional): Map of user related properties.
1
2
3
4
5
6
7
8
9
chatkit.createUser({
  id: 'userId',
  name: 'Some name',
})
  .then(() => {
    console.log('User created successfully');
  }).catch((err) => {
    console.log(err);
  });
Response

Returns a user object if the user was successfully created

1
2
3
4
5
6
{
  "id": "userId",
  "name": "user",
  "created_at": "2017-03-23T11:36:42Z",
  "updated_at": "2017-03-23T11:36:42Z"
}

Batch creating Users

Create multiple Chatkit users.

Usage

The createUsers method takes a single object of the form:

  • users (Array, required): Array of user objects.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const usersToCreate = [
  {
    id: 'user1',
    name: 'User 1',
  },
  {
    id: 'user2',
    name: 'User 2',
  }
];

chatkit.createUsers({ users: usersToCreate })
  .then((res) => {
    console.log(res);
  }).catch((err) => {
    console.log(err);
  });
Response

A JSON array containing a list of created user objects

1
2
3
4
5
6
7
8
9
10
11
12
{
  "id": "user1",
  "name": "User 1",
  "created_at": "2017-03-23T11:36:42Z",
  "updated_at": "2017-03-23T11:36:42Z"
},
{
  "id": "user2",
  "name": "User 2",
  "created_at": "2017-03-23T11:36:42Z",
  "updated_at": "2017-03-23T11:36:42Z"
}

Updating a User

Update the metadata attached to a given user.

Usage

The updateUser method takes a single object containing the attributes that should be updated. You can also attach custom metadata to a user using the customData attribute.

  • id (string, required): Unique ID to match the user to be updated.
  • name (string, optional): An updated name for the user
  • avatarURL (string, optional): An updated avatar URL for the user
  • customData (object, optional): Updated custom data for the user
1
2
3
4
5
6
7
8
9
10
11
12
13
chatkit.updateUser({
  id: 'someId',
  name: 'New Name',
  avatarURL: 'https://some.url',
  customData: {
    age: 21,
  },
})
  .then(() => {
    console.log('User updated successfully');
  }).catch((err) => {
    console.log(err);
  });

Deleting a User

Delete a previously created User.

Usage

The deleteUser method takes a single object of the form:

  • id (string, required): Unique ID to match the user to be deleted.
1
2
3
4
5
6
chatkit.deleteUser({ userId: 'someId' })
  .then(() => {
    console.log('User deleted successfully');
  }).catch((err) => {
    console.log(err);
  });
Response

No response body is returned on successful deletion.

Authenticate a User

Generate a HTTP status and body appropriate to use as the response of an authentication request from one of your clients. e.g.

1
2
3
4
5
6
7
8
9
10
// Example using Express

app.post('/auth', (req, res) => {
  const authData = chatkit.authenticate({
    userId: req.query.user_id
  });

  res.status(authData.status)
     .send(authData.body);
})

Get a User

Get a single user by ID. Takes an object with an id property.

1
2
3
4
5
chatkit.getUser({
  id: 'callum',
})
  .then(user => console.log('got a user', user))
  .catch(err => console.error(err))

Get Users

The getUsers function returns users, orederd by creation date from oldest to newest. Takes an object with the following properties.

  • fromTimestamp (string, optional) return users newer than this
  • limit (number, optional) return at most this many users
1
2
3
4
5
6
chatkit.getUsers()
  .then((res) => {
    console.log(res);
  }).catch((err) => {
    console.log(err);
  });
Response

An array of JSON objects

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[
  {
    "id": "gary",
    "name": "Gary McGaryface",
    "avatar_url": "https://gravatar.com/img/8819",
    "custom_data": {
    "email": "a@b.com"
  },
    "created_at": "2017-03-23T11:36:42Z",
    "updated_at": "2017-03-23T11:36:42Z"
  },
  {
    "id": "john",
    "name": "John Doe",
    "avatar_url": "https://gravatar.com/img/8819",
    "custom_data": {
    "email": "a@b.com"
  },
    "created_at": "2017-03-23T11:36:42Z",
    "updated_at": "2017-03-23T11:36:42Z"
  }
]

Get Users by ID

Supply an array of user IDs, get back an array of Users.

1
2
3
4
5
chatkit.getUsersById({
  userIds: ['alice', 'bob', 'carol', 'dave'],
})
  .then(users => console.log('got users', users))
  .catch(err => console.error(err))

Rooms

Create a Room

1
2
3
4
5
6
7
8
9
10
chatkit.createRoom({
  creatorId: 'userId',
  name: 'my room',
  customData: { foo: 42 },
})
  .then(() => {
    console.log('Room created successfully');
  }).catch((err) => {
    console.log(err);
  });

Create a new public or private room.

Usage

createRoom takes an object of the form:

  • creatorId (string, required): The ID of the user who is creating the room.
  • name (string, required): The name of the room.
  • isPrivate (boolean, optional): Whether or not the room is to be private. Defaults to false.
  • userIds (array, optional): An array of user IDs to be added as members of the room.
  • customData (object, optional) Arbitrary custom data to be attached to the room.
Response

An object that looks like this:

1
2
3
4
5
6
7
8
9
10
{
  id: '123',
  created_by_id: 'a_user',
  name: 'my room',
  private: false,
  created_at: '2017-11-10T14:57:46Z',
  updated_at: '2017-11-10T14:57:46Z',
  member_user_ids: [ 'some_other_user', 'a_user' ],
  custom_data: { foo: 42 },
}

Update a Room

updateRoom modifies a room’s name or privacy. Takes an object with the following properties:

  • id (string, required): The ID of the room to be updated.
  • name (string, optional): The name of the room.
  • isPrivate (boolean, optional): Whether or not the room is to be private. Defaults to false.
  • customData (object, optional) Arbitrary custom data to be attached to the room.
1
2
3
4
5
6
7
8
chatkit.updateRoom({
  id: roomToUpdate.id,
  name: 'Members only',
  isPrivate: true,
  customData: { bar: 'baz' },
})
  .then(() => console.log('room successfully updated'))
  .catch(err => console.error(err))

Add users to a room

addUsersToRoom adds users as members of a room. Takes an object with the following parameters

  • roomId (string, required) The room to add users to
  • userIds ([]string, required) The users to add
1
2
3
4
5
6
chatkit.addUsersToRoom({
  roomId: room.id,
  userIds: ['alice', 'bob']
})
  .then(() => console.log('added'))
  .catch(err => console.error(err))

Remove users from a room

removeUsersFromRoom removes users with the given ID from a room. Takes an object with the following parameters

  • roomId (string, required) The room to remove users from
  • userIds ([]string, required) The users to remove
1
2
3
4
5
6
chatkit.removeUsersFromRoom({
  roomId: room.id,
  userIds: ['alice', 'bob']
})
  .then(() => console.log('removed'))
  .catch(err => console.error(err))

Delete a Room

deleteRoom irreversibly deletes the room, along with all its messages and metadata. Takes an object with a single id parameter: the ID of the room to be deleted.

1
2
3
4
5
chatkit.deleteRoom({
  id: roomToDelete.id
})
  .then(() => console.log('gone forever'))
  .catch(err => console.error(err))

Get a Room

Fetch a room by its ID. Takes an object with a single roomId parameter.

1
2
3
4
5
chatkit.getRoom({
  roomId: "123",
})
  .then(room => console.log('got room', room))
  .catch(err => console.error(err))

Get Rooms

getRooms fetches rooms, ordered by ID, in pages of 100 at a time. Takes an object with the following properties:

  • fromId (string, optional) starting ID of the range of rooms (exclusive)
  • includePrivate (boolean, optional) If true private rooms will be included in the response, otherwise they will be filtered out.
1
2
3
chatkit.getRooms({})
  .then(rooms => console.log('got rooms', rooms))
  .catch(err => console.error(err))

Get User Joinable Rooms

Get a list of rooms that the user can join.

Usage

The getUserJoinableRooms function takes an object of the form:

  • userId (String, required): ID of the user for whom rooms should be retrieved
1
2
3
4
5
6
7
8
chatkit.getUserJoinableRooms({
  userId: 'user1'
})
  .then((res) => {
    console.log(res);
  }).catch((err) => {
    console.log(err);
  });
Response

An array of JSON objects

1
2
3
4
5
6
7
8
9
10
11
[
  {
    "id": "1",
    "created_by_id": "user2",
    "name": "mycoolroom",
    "private": false,
    "created_at": "2017-03-23T11:36:42Z",
    "updated_at": "2017-03-23T11:36:42Z",
    "member_user_ids":["user3", "user4"]
  }
]

Get User Rooms

Get a list of rooms that the user is a member of.

Usage

The getUserRooms function takes an object of the form:

  • userId (String, required): ID of the user for whom rooms should be retrieved
1
2
3
4
5
6
7
8
chatkit.getUserRooms({
  userId: 'user1',
})
  .then((res) => {
    console.log(res);
  }).catch((err) => {
    console.log(err);
  });
Response

An array of JSON objects

1
2
3
4
5
6
7
8
9
10
11
[
  {
    "id": "1",
    "created_by_id": "user2",
    "name": "mycoolroom",
    "private": false,
    "created_at": "2017-03-23T11:36:42Z",
    "updated_at": "2017-03-23T11:36:42Z",
    "member_user_ids":["user3", "user4"]
  }
]

Messages

Send a message

There are two methods to send messages. In the simplest case you can send plain text messages with sendSimpleMessage. Takes an object of the form:

  • userId (string, required) the ID of the user to send the message as
  • roomId (string, required) the ID of the room to send the message to
  • text (string, required) the content of the message
1
2
3
4
5
6
7
chatkit.sendSimpleMessage({
  userId: 'alice',
  roomId: '123',
  text: 'hello!',
})
  .then(res => console.log('sent message with id', res.id))
  .catch(err => console.error(err))

For more complex messages you should use sendMultipartMessage instead. Takes an object of the form:

  • userId (string, required) the ID of the user to send the message as
  • roomId (string, required) the ID of the room to send the message to
  • parts (array, required) the parts composing the message.

Where each part is one of the following:

An inline part.

AttributeTypeDescription
typestringThe MIME type of the content.
contentstringThe string content of the part.

A URL part.

AttributeTypeDescription
typestringThe MIME type of the resource that the URL points to.
urlstringA URL.

An attachment part.

AttributeTypeDescription
typestringThe MIME type of the attachment.
fileBufferA Buffer – e.g. as returned from readFile.
namestringThe name of the attached file. (Optional.)
customDataanyArbitrary custom data to associate with the file. (Optional.)

For example, sending a message consisting of three parts, one of each of the above:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
fs.readFile("tiny-pig.gif", (err, data) => {
  if (err) {
    console.error(err)
  } else {
    chatkit
      .sendMultipartMessage({
        roomId: process.argv[2],
        userId: "alice",
        parts: [
          {
            type: "text/plain",
            content: "see attached",
          },
          {
            type: "audio/ogg",
            url: "https://example.com/oink.ogg",
          },
          {
            type: "image/gif",
            file: data,
            customData: { foo: "bar" },
          },
        ],
      })
      .then(id => console.log("sent", id))
      .catch(console.error)
  }
})

Fetch messages from a room

fetchMultipartMessages fetches the messages from a room. Messages are returned in pages of at most 100 at a time. Takes an object with the following properties:

  • roomId (string, required) the ID of the room to get messages from
  • direction (string, optional) direction to page back through messages – one of "older" or "newer"
  • initialId (string, optional) starting ID of the range of messages (exclusive)
  • limit (number, optional) number of messages to return in a single page (defaults to 20, maximum 100)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
chatkit.fetchMultipartMessages({
  roomId: room.id,
  limit: 10,
})
  .then(messages => {
    console.log('got last 10 messages')
    for (let m of messages) {
      renderMessage(m)
    }
    return chatkit.fetchMultipartMessages({
      roomId: room.id,
      initialId: res[messages.length - 1].id,
    })
  })
  .then(moreMessages => {
    console.log('got the next 10 messages before them')
    for (let m of moreMessages) {
      renderMessage(m)
    }
  })
  .catch(err => console.error(err))
fetchMultipartMessages replaces its deprecated predecessor getRoomMessages. The latter functions similarly but return the legacy message type.

Delete a Message

deleteMessage irreversibly deletes the message and replaces it with a generic tombstone. Takes an object with a single id parameter: the ID of the message to be deleted.

1
2
3
4
5
chatkit.deleteMessage({
  id: messageToDelete.id
})
  .then(() => console.log('gone forever'))
  .catch(err => console.error(err))

Read Cursors

Set a read cursor

setReadCursor sets the read cursor for the given user and room to the given position (the latest read message ID). Takes an object with the following properties

  • userId (string, required) The ID of the user to set the cursor for.
  • roomId (string, required) The ID of the room to set the cursor for.
  • position (number, required) The latest read message ID
1
2
3
4
5
6
7
8
chatkit
  .setReadCursor({
    userId: user.id,
    roomId: room.id,
    position: 42,
  })
  .then(() => console.log('done!'))
  .catch(err => console.error(err))

Get a read cursor

getReadCursor gets the read cursor for the given user and room. Takes an object with the following properties

  • userId (string, required) The ID of the user to get the cursor for.
  • roomId (string, required) The ID of the room to get the cursor for.
1
2
3
4
5
6
7
chatkit
  .getReadCursor({
    userId: user.id,
    roomId: room.id,
  })
  .then(cursor => console.log('got cursor', cursor))
  .catch(err => console.error(err))

Get all of a user’s read cursors

getReadCursorsForUser gets all of the given user’s read cursors. Takes an object with the following properties

  • userId (string, required) The ID of the user to get the cursors for.
1
2
3
4
5
6
chatkit
  .getReadCursorsForUser({
    userId: user.id,
  })
  .then(cursors => console.log('got cursors', cursors))
  .catch(err => console.error(err))

Get all of the read cursors for a room

getReadCursorsForRoom gets all of the read cursors for the given room. Takes an object with the following properties

  • roomId (string, required) The ID of the room to get the cursors for.
1
2
3
4
5
chatkit.getReadCursorsForRoom({
  roomId: room.id,
})
  .then(cursors => console.log('got cursors', cursors))
  .catch(err => console.error(err))

Roles and Permissions

Creating a Role with the Room scope

Create a Role intended for use within the scope of a room identified by its ID.

Usage

createRoomRole takes an object of the form:

  • name (string, required): A unique name for the role.
  • permissions (array, required): A list of permissions outlined in the authentication docs.
1
2
3
4
5
6
7
8
9
chatkit.createRoomRole({
  name: 'mycoolroomrole',
  permissions: ['room:join'],
})
  .then(() => {
    console.log('Room role created successfully');
  }).catch((err) => {
    console.log(err);
  });
Response

No response body is returned.

Creating a Role with the Global scope

Create a Role intended for use globally.

Usage

createGlobalRole takes an object of the form:

  • name (string, required): A unique name for the role.
  • permissions (array, required): A list of permissions outlined in the authentication docs.
1
2
3
4
5
6
7
8
9
chatkit.createGlobalRole({
  name: 'mycoolglboalrole',
  permissions: ['room:join'],
})
  .then(() => {
    console.log('Global role created successfully');
  }).catch((err) => {
    console.log(err);
  });
Response

No response body is returned.

Deleting a Room scoped Role

Delete a room scoped role.

Usage

deleteRoomRole takes an object of the form:

  • name (string, required): Role name by which the role is identified.
1
2
3
4
5
6
chatkit.deleteRoomRole({ name: 'mycoolroomrole' })
  .then(() => {
    console.log('Room role deleted successfully');
  }).catch((err) => {
    console.log(err);
  });
Response

No response body is returned.

Deleting a Global scoped Role

Delete a global scoped role.

Usage

deleteGlobalRole takes an object of the form:

  • name (string, required): Role name by which the role is identified.
1
2
3
4
5
6
chatkit.deleteGlobalRole({ name: 'mycoolglobalrole' })
  .then(() => {
    console.log('Global role deleted successfully');
  }).catch((err) => {
    console.log(err);
  });
Response

No response body is returned.

Assigning a Room scoped role to a User

Assign a room scoped role to a User for a given room ID.

Usage

assignRoomRoleToUser takes an object of the form:

  • userId (string, required): User ID to assign the role to.
  • name (string, required): Name of the role to be assigned to the user.
  • roomId (integer, required): Room ID to which the role is bound to.
1
2
3
4
5
6
7
8
9
10
chatkit.assignRoomRoleToUser({
  userId: 'userId',
  name: 'mycoolroomrole',
  roomId: '234',
})
  .then(() => {
    console.log('Assigned room role successfully');
  }).catch((err) => {
    console.log(err);
  });
Response

No response body is returned

Assigning a Global scoped role a User

Assign a role scoped globally to a User.

Usage

assignGlobalRoleToUser takes an object of the form:

  • userId (string, required): User ID to assign the role to.
  • name (string, required): Name of the role to be assigned to the user.
1
2
3
4
5
6
7
8
9
chatkit.assignGlobalRoleToUser({
  userId: 'userId',
  name: 'mycoolglobalrole',
})
  .then(() => {
    console.log('Assigned global role successfully');
  }).catch((err) => {
    console.log(err);
  });
Response

No response body is returned

Removing a Room scoped role for a User

Un-assign a room scoped role from a User.

Usage

removeRoomRoleForUser takes an object of the form:

  • userId (string, required): User ID the role was assigned to.
  • roomId (string, required): Room ID of the role.
1
2
3
4
5
6
7
8
9
chatkit.removeRoomRoleForUser({
  userId: 'userId',
  name: 'mycoolroomrole',
})
  .then(() => {
    console.log('Removed room role successfully');
  }).catch((err) => {
    console.log(err);
  });
Response

No response body is returned.

Removing a Global scoped role for a User

Un-assign a global scoped role from a User.

Usage

removeGlobalRoleForUser takes an object of the form:

  • userId (string, required): User ID the role was assigned to.
1
2
3
4
5
6
chatkit.removeGlobalRoleForUser({ userId: 'userId' })
  .then(() => {
    console.log('Removed global role successfully');
  }).catch((err) => {
    console.log(err);
  });
Response

No response body is returned.

List all Roles for an Instance

Fetch all roles created for an instance.

Usage

getRoles does not take any arguments.

1
2
3
4
5
6
chatkit.getRoles()
  .then((res) => {
    console.log(res);
  }).catch((err) => {
    console.log(err);
  });
Response

An array of JSON objects

1
2
3
4
5
6
7
8
9
10
11
12
[
  {
    "role_name": "mycoolglobalrole",
    "permissions": ["room:join"],
    "scope_name": "global"
  },
  {
    "role_name": "mycoolroomrole",
    "permissions": ["room:update"],
    "scope_name": "room"
  }
]

List Roles for a User

Fetch roles assigned to a user.

Usage

getUserRoles takes an object of the form:

  • userId (string, required): User ID to which roles are assigned.
1
2
3
4
5
6
chatkit.getUserRoles({ userId: 'userId' })
  .then((res) => {
    console.log(res);
  }).catch((err) => {
    console.log(err);
  });
Response

An array of JSON objects

1
2
3
4
5
6
7
8
9
10
11
[
  {
    "role_name": "mycoolglobalrole",
    "permissions": ["room:join"]
  },
  {
    "role_name": "mycoolroomrole",
    "permissions": ["room:update"],
    "room_id": 234
  }
]

List Permissions associated with a Room scoped Role

Fetch the list of permissions assigned to a room scoped role.

Usage

getPermissionsForRoomRole takes an object of the form:

  • name (string, required): Name of the role with which permissions are associated.
1
2
3
4
5
6
7
8
chatkit.getPermissionsForRoomRole({
  name: 'mycoolroomrole'
})
  .then((res) => {
    console.log(res);
  }).catch((err) => {
    console.log(err);
  });
Response

An Array of permission names

1
["room:update"]

List permissions associated with a Global scoped Role

Fetch the list of permissions assigned to a global role.

Usage

getPermissionsForGlobalRole takes an object of the form:

  • name (string, required): Name of the role with which permissions are associated.
1
2
3
4
5
6
7
8
chatkit.getPermissionsForGlobalRole({
  name: 'mycoolglobalrole'
})
  .then((res) => {
    console.log(res);
  }).catch((err) => {
    console.log(err);
  });
Response

An Array of permission names

1
["room:join"]

Update Permissions associated with a Room scoped Role

Update the list of permissions assigned to a room scoped role.

Usage

updatePermissionsForRoomRole takes an object of the form:

  • name (string, required): Name of the role with which permissions are associated.
  • permissionsToAdd ([]string, optional): The permissions to add to the role.
  • permissionsToRemove ([]string, optional): The permissions to remove from the role.
1
2
3
4
5
6
chatkit.updatePermissionsForRoomRole({
  name: 'mycoolroomrole',
  permissionsToAdd: ['room:update']
})
  .then(() => console.log('done!'))
  .catch(err => console.error(err))

Update permissions associated with a Global scoped Role

Update the list of permissions assigned to a global role.

Usage

updatePermissionsForGlobalRole takes an object of the form:

  • name (string, required): Name of the role with which permissions are associated.
  • permissionsToAdd ([]string, optional): The permissions to add to the role.
  • permissionsToRemove ([]string, optional): The permissions to remove from the role.
1
2
3
4
5
6
chatkit.updatePermissionsForGlobalRole({
  name: 'mycoolglobalrole',
  permissionsToRemove: ['room:update']
})
  .then(() => console.log('done!'))
  .catch(err => console.error(err))

Errors

Errors

Error responses returned by the API take the shape of an object which contains details of the error.

1
2
3
4
5
{
  "error": "unprocessable_entity/invalid_json_body",
  "description": "Failed to parse request body",
  "uri": "https://docs.pusher.com/errors/unprocessable_entity/invalid_json_body"
}