Skip to content
Connecting to Agora with Tokens — React Native - Featured

Connecting to Agora with Tokens — React Native

By Author: Ekaansh Arora In Developer

When you’re building a real-time engagement application, security is of key importance (pun intended). Making sure users’ audio/video is visible only to the intended recipients is critical. Using the Agora Voice or Video SDK, you can easily add another layer of security to your app with the help of tokens.

In this tutorial, we’ll take a look at how to fetch tokens from a server and use them to join a video/voice channel in React Native. You can deploy your own server to generate tokens, or you can use this example. We’ll be using this example token server in our tutorial, and you can easily deploy the same server by following the instructions. A Docker image is also available.

Prerequisites

To get us up to speed with a basic video calling app, let’s use this demo. You can follow the instructions in the readme.md file to get the app working on your device. We’ll be discussing the code for fetching and updating tokens below. If you just want a working demo, you can check the tokens branch for the final outcome.

Connecting with Tokens

We’ll make a GET request to our server (running locally or on a remote server) with our channel nameandUID before we start the call using the joinChannel method. We’ll use fetch to make our request and obtain our token. Our server responds with {“rtcToken”:”<TOKEN HERE>”}. We get the token value from the JSON and pass it as the first parameter in our joinChannel method.

Note: We’re using the URL structure found in the sample token server.

Note: If you’re running an Android emulator and trying to access your token server running locally, use the URL http://10.0.2.2. Why?

Staying Connected

All tokens have an expiry. The length of time until they expire is set by the token server, or it can be set as a parameter sent in the request. For example, your-server.com/rtc/channel-test/publisher/uid/0/?expiry=60 would set the expiry as 60 seconds for uid 0 in channel-test for the token server we’re using.

When a connected user’s token is set to expire in 30 seconds, we receive a TokenPrivilegeWillExpire event. We can set an event handler to update the token before it expires, avoiding any interruption in the connection. Once we’ve obtained a new token, we can use the renewToken method to renew our token. We’ll add the listener in our init method.

Conclusion

Those two easy steps can make your app secure. If you want to learn about how the demo app works, see this tutorial. And if you want to look at other features, see the API Reference.