Using the SDK

First step to using the SDK is to setup authentication. The JavaScript SDK is unique in that everything runs within the browser on the client side, which means you cannot safely use your Project Token for authentication as you do in the other, server-side SDKs.

To get around this, the JavaScript SDK uses JSON Web Tokens (JWT) to authenticate with SignalWire and apply fine grained permissions to the end-user.

Your server uses your Project ID and Project Token to make a request to generate a JWT with your specific requirements, such as expiration time, scopes and permissions, resource name, and give the resulting JWT Token to the browser. The JWT is safe to expose in the browser and to the end user, it is signed and cannot be edited. The browser can then safely log into SignalWire using the Project ID and the JWT.

To learn more about generating and using JWT, including all the options available to you, visit Authentication for JavaScript SDK Documentation.

Generate a JWT

To generate a JWT, make a server-side POST request to the JWT endpoint on the Relay REST API.

curl https://your-space.signalwire.com/api/relay/rest/jwt \
  -X POST \
  -u 'YourProjectID:YourProjectToken' \
  -H 'Content-Type: application/json'

Will result in a JSON response like:

{
    "jwt_token": "a_long_jwt_token",
    "refresh_token": "a_long_jwt_refresh_token"
}

For more information and examples on generating JSON Web Tokens, visit Authentication for JavaScript SDK Documentation

Connect using JWT

Using the JWT you received in the previous step, you can connect to Relay using your Project ID and the JWT.

const client = new Relay({
  project: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
  token: 'a_long_jwt_token'
})

You can then use client to make Relay requests.

Refresh JWT Token

All tokens have an expiration, so that a user cannot stay logged in forever. You can use the refresh token you received in Generate a JWT to refresh a token you already generated.

To refresh a JWT, make a server-side PUT request to the JWT endpoint with the refresh token:

curl https://your-space.signalwire.com/api/relay/rest/jwt \
  -X PUT \
  -u 'YourProjectID:YourProjectToken' \
  -H 'Content-Type: application/json' \
  -d '{
        "refresh_token": "a_long_jwt_token"
      }'

Will result in a JSON response like:

{
    "jwt_token": "a_new_jwt_token",
    "refresh_token": "a_new_jwt_refresh_token"
}

For more information about automatically refreshing JWT as they're about to expire, see refreshToken Event Documentation


Did this page help you?