Docs

Server API

What runs on your backend: signing access tokens with your App ID and App Certificate, and managing live rooms.

No API call to join

Your backend does not call a Gravix API when a user joins a room. It signs the access token itself with our token library, and Gravix checks the signature when the user connects. So a join never waits on an extra service, and your App Certificate never leaves your server.

Token libraries

gravix-rtc-token on npm runs on Node 18+, Deno, Bun and edge runtimes, with no runtime dependencies and TypeScript types. gravix-token-go is the Go version (Go 1.21+) with the same options.

terminal
npm install gravix-rtc-token
server.ts
// server.ts (your backend, Node 18+). This file never ships inside an app.
import express from 'express';
import { createToken } from 'gravix-rtc-token';

const APP_ID = process.env.GRAVIX_APP_ID!;                   // from your dashboard
const APP_CERTIFICATE = process.env.GRAVIX_APP_CERTIFICATE!; // server only, never in an app
const REGION_URL = process.env.GRAVIX_URL!;                   // wss://YOUR-REGION-URL

const app = express();
app.use(express.json());

// requireUser is your own login check: the identity comes from YOUR session,
// never from the request body.
app.post('/rtc/token', requireUser, async (req, res) => {
  const room = req.body?.room;
  if (typeof room !== 'string' || !/^[\w.-]{1,64}$/.test(room)) {
    return res.status(400).json({ error: 'invalid room' });
  }
  const token = await createToken(APP_ID, APP_CERTIFICATE, {
    room,                       // the library adds your App ID prefix
    identity: req.user.id,
    name: req.user.name,
    canPublish: true,           // false = listen only; decide it here, not in the app
    ttlSeconds: 60 * 60,        // short-lived: 1 hour
  });
  res.json({ token, url: REGION_URL });
});

app.listen(3000);
token.go
// token.go (your backend, Go 1.21+). gravixtoken is the gravix-token-go package.
func tokenHandler(w http.ResponseWriter, r *http.Request) {
	user, ok := currentUser(r) // your own login check
	if !ok {
		http.Error(w, "sign in first", http.StatusUnauthorized)
		return
	}
	var body struct {
		Room string `json:"room"`
	}
	if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body.Room == "" {
		http.Error(w, "invalid room", http.StatusBadRequest)
		return
	}

	// The App Certificate stays in the server's environment.
	jwt, err := gravixtoken.New(os.Getenv("GRAVIX_APP_ID"), os.Getenv("GRAVIX_APP_CERTIFICATE")).
		Room(body.Room).
		Identity(user.ID).
		Name(user.Name).
		CanPublish(true). // false = listen only
		TTL(time.Hour).   // short-lived
		ToJWT()
	if err != nil {
		http.Error(w, "could not sign", http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]string{
		"token": jwt,
		"url":   os.Getenv("GRAVIX_URL"), // wss://YOUR-REGION-URL
	})
}

Token options

Names are the Node option and the Go builder method.

NodeGoWhat it does
roomRoomRequired. The room name in your app. The library adds your App ID prefix.
identityIdentityRequired. Your user ID, taken from your own session.
nameNameDisplay name shown to other participants.
metadataMetadataFree-form string attached to the participant.
attributesAttributesKey-value pairs attached to the participant.
ttlSecondsTTLHow long the token is valid. Default 6 hours, at most 24 hours.
canPublishCanPublishMay send audio and video. Default true; false = listener.
canSubscribeCanSubscribeMay receive others' audio and video. Default true.
canPublishDataCanPublishDataMay send data messages. Default true.
canUpdateOwnMetadataCanUpdateOwnMetadataMay change their own name, metadata and attributes. Default true; the SDKs use it to share the camera facing.
canPublishSourcesCanPublishSourcesLimit publishing to some sources, for example the microphone only.
hiddenHiddenJoins without being shown to other participants.
roomAdminRoomAdminRoom moderator rights; a token with it can call the room API for that room.

roomName(appId, room) adds the App ID prefix to a room name and displayName(appId, room) strips it for display (RoomName and DisplayName in Go).

Managing rooms

Your backend can act on a live room: give or take a seat, mute a track, remove a user. SendPOST https://<region host>/twirp/gravix.RoomService/<Method> with a JSON body andAuthorization: Bearer <token>, where the token is signed by your token library withroomAdmin: true for that room. The room in the body is the full name with your App ID prefix (roomName(appId, room)).

MethodWhat it does
ListParticipantsEveryone in the room. Body: room.
GetParticipantOne user, with their tracks. Body: room, identity.
UpdateParticipantChange a user's rights (seat or listener), name, metadata or attributes, without a rejoin. Body: room, identity, permission, …
MutePublishedTrackMute one of a user's tracks. Body: room, identity, track_sid, muted.
RemoveParticipantDisconnect a user from the room. Body: room, identity.
server/room-api.js
import { createToken, roomName } from 'gravix-rtc-token';

const APP_ID = process.env.GRAVIX_APP_ID;
const APP_CERT = process.env.GRAVIX_APP_CERTIFICATE;

// Any Gravix region host works; a call for a user in another region is forwarded there.
async function roomApi(host, method, room, body) {
  const token = await createToken(APP_ID, APP_CERT, {
    room, identity: 'my-backend', roomAdmin: true, canPublish: false, ttlSeconds: 300,
  });
  const res = await fetch(`https://${host}/twirp/gravix.RoomService/${method}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
    body: JSON.stringify({ room: roomName(APP_ID, room), ...body }),
  });
  if (!res.ok) throw new Error(`${method}: ${res.status} ${await res.text()}`);
  return res.json();
}

// Give a listener a seat, without a rejoin:
await roomApi('blr1.gravixcloud.com', 'UpdateParticipant', 'party-42', {
  identity: 'user-123',
  permission: { canSubscribe: true, canPublish: true, canPublishData: true },
});

// Take the seat back: their microphone is unpublished, they stay in the room as a listener.
await roomApi('blr1.gravixcloud.com', 'UpdateParticipant', 'party-42', {
  identity: 'user-123',
  permission: { canSubscribe: true, canPublish: false, canPublishData: true },
});
  • Any Gravix region host works: if the user is connected to another region, the call is forwarded there. Forwarding adds roughly one round trip between regions; the user's own region is fastest. A user who has left answers 404.
  • MutePublishedTrack needs the track_sid (from GetParticipant); an empty one answers 400.
  • Keep the admin token on your server and short-lived; never send it to an app.
  • The API is not on the join path: joining still needs no call to us.

Questions about the API?

Call or WhatsApp us, or sign up free.