Tokens
Tokens can be used to:
- restrict access to private Channels
- forcefully subscribe users to Channels
- authenticate and identify users connected to Channels
- send direct messages to users (instead of to entire Channels)
Tokens can be generated using our API, then you can pass them down to users so they can authenticate with Channels. A common implementation is to generate a Token per user on your backend, then store it with the user object in your database. You can then pass their token down to the user (via your API, for example) and it can be used with our Client-side SDK to authenticate with Channels.
Do I need to use Tokens?
Tokens are not necessary in every application. Some applications may choose to use Tokens for logged in users only, or even not at all - it really depends on your use case.
If you’re providing data that you want everyone to be able to see (without
signing into your app, for example) then it probably makes the most sense to use
an unprotected
channel, which can be subscribed to using our frontend SDKs
without using Tokens.
A good use-case for Tokens would be if you’re building something like a group messaging app, for example, and need to limit access to certain channels, such as private group chat channels, to specific users.
Server-side Examples
The examples below assume you have already set up the Hop server-side SDK.
Generating Tokens
You can generate Tokens manually (using our Console) or via our SDKs & API.
Here’s an example of generating tokens using the server-side SDK:
Subscribing Tokens to Channels
When you subscribe a Token to a channel, it will be subscribed to that channel in realtime and it will be made available to any live connections using that Token.
In this example, let’s assume that we have a private channel with the ID game
.
Sending Messages Directly to Tokens
Determine if a Token is Online
You can use the isOnline
function to check if a Token is currently connected
to Channels.
Client-side Examples
Using Tokens with Client-side SDKs
Implementing Tokens into your frontend app is super easy. Just pass it into
hop.init
in the token
key. For example: