This article focuses on the best practices related to token creation. Using best practices with Stream tokens is important because it will greatly improve the security of your App. Creating tokens with token expiration is key to best practices.
For code examples of token creation and other related information please reference our docs page on token creation here. To learn more about token creation as it pertains to the client, server, and Stream API, please view this article.
To implement token expiration times, you will enter an expiration time in the future as a second parameter in the token creation method. The below example sets a token to expire in 15 minutes. Note: 15 minutes is a recommended amount of time for token expiration
const token = chatClient.createToken(userID, Math.floor(Date.now() / 1000) + (60 * 15));
Web Socket Connection
When a token expires during an active web socket connection, the web socket will continue to stay connected allowing the user to stay in the App. Once the user has left the App and the web socket connection disconnects, the client will then need a new token to access the Stream API once again. The Web Socket connection could disconnect from either the user quitting or backgrounding the App.
Updating the Token
To update your user's token you will want to implement a function or class that is responsible for requesting a new token from your own login infrastructure. To learn more about updating your users' tokens after they expire and to view an example, please reference this section of our Stream Token & Authentication docs.
Static tokens do not have an expiration time. To do this, simply leave out the date/time parameter as shown in the example below. As noted above, if you are planning to go live with your App it is recommended that tokens have an expiration.
const token = chatClient.createToken(userID);
Unless you are using tokens for a development application (dev tokens), tokens are always created server-side. Using client-side generated tokens is not possible for production applications. One exception to this is handling guest user sessions, which can be created client-side and do not require any server-side authentication.
When creating tokens for production App with Stream, best practices include creating tokens with token expiration. This greatly improves the security and scalability of your App. Feel free to use static tokens in the development environments when you need to experiment and quickly stand up Apps. To learn more, please view the related resources mentioned in this article and reach out to email@example.com!