This article will help us understand the difference and how can we instantiate Stream.
Client-side and Server-Side Chat clients are instantiated similarly, but have key differences. The client will be the front end and the Server will be our backend. For instance, this article has the frontend (Client-side) as React/JS and has the Backend (Sever-side) as Node/Express/JS. Hope this gives you a clear idea.
The following code snippets and example are for two basic functions of Server-side and Client-side operations - creating a signed user token in the server and creating a user/opening a websocket client-side.
What do we do server-side?
Totally up to you, but these are the activities that are mandated to be server-side:
1. API secret is a must for instantiating Server
2. Creating user tokens
3. Updating permissions, setting user roles
4. User ban.. etc.
How do we set up the Client-side -
const chatClient = StreamChat.getInstance(appKey, { timeout: 6000 });
Now, We need to connectUser-
chatClient.connectUser(
{
id: userID,
name: userID,
image: 'https://getstream.io/random_png/?id=falling-breeze-3&name=userID'
},
userToken
);
This is the logic to obtain userToken from the server -
let fetchuserToken = async () => {
let userToken = await fetch("http://localhost:3002/token",
{
method: "post",
headers: { "Content-Type" : "application/json"},
body: JSON.stringify({
input: userID
})
}).then(response => response.json())
.then(fetchuserToken => {
return fetchuserToken;
})
.catch(error => console.warn(error));
return userToken;
}
const userToken = fetchuserToken;
The token's value will be obtained from the server; in this instance, it is the localhost.
How do we set-up the Server-side - (AppKey, a secret that can be obtained from Dashboard)
const client = new StreamChat(appID, secret, { timeout: 6000 });
Node running on port 3002
app.post("/token", (req,res) =>
{
const { input } = req.body;
console.log(input);
if (input)
{
const token = client.createToken(input);
return res.json(token);
}
else
{
return res.json("Could not generate token");
}
})
This is how we create the token for the same user id passed from the frontend.
Comments
1 comment
I have an existing app where i already generate jwt token to authenticate users can i use my app generated JWT for the streams' app token?
Please sign in to leave a comment.