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

sendMessage publishes a message to a room as the given user. 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.sendMessage({
  userId: 'alice',
  roomId: '123',
  text: 'hello!',
})
  .then(res => console.log('sent message with id', res.id))
  .catch(err => console.error(err))

Get Messages From a Room

getRoomMessages 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.getRoomMessages({
  roomId: room.id,
  limit: 10,
})
  .then(messages => {
    console.log('got last 10 messages')
    for (let m of messages) {
      renderMessage(m)
    }
    return chatkit.getRoomMessages({
      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))

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.
  • roleName (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',
  roleName: '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.
  • roleName (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',
  roleName: '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',
  roleName: '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:

  • roleName (string, required): Name of the role with which permissions are associated.
1
2
3
4
5
6
7
8
chatkit.getPermissionsForRoomRole({
  roleName: '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:

  • roleName (string, required): Name of the role with which permissions are associated.
1
2
3
4
5
6
7
8
chatkit.getPermissionsForGlobalRole({
  roleName: '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:

  • roleName (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({
  roleName: '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:

  • roleName (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({
  roleName: '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"
}

Did you find this document useful?

We are always striving to create the most accurate and informative docs as possible. If there is something especially wrong (or right) here then please let us know.