Generating tokens

Generate tokens for your clients

In order for client apps to connect to LiveKit rooms, they need a token generated by your backend server. In this guide, we'll walk through how to set up a server to generate tokens for your clients.

1. Install LiveKit Server SDK

go get github.com/livekit/server-sdk-go/v2

2. Keys and Configuration

Create a new file at development.env and with your API Key and Secret:

export LIVEKIT_API_KEY=<your API Key>
export LIVEKIT_API_SECRET=<your API Secret>

3. Make an endpoint that returns a token

Create a server:

// server.go
import (
"net/http"
"log"
"time"
"os"
"github.com/livekit/protocol/auth"
)
func getJoinToken(room, identity string) string {
at := auth.NewAccessToken(os.Getenv("LIVEKIT_API_KEY"), os.Getenv("LIVEKIT_API_SECRET"))
grant := &auth.VideoGrant{
RoomJoin: true,
Room: room,
}
at.AddGrant(grant).
SetIdentity(identity).
SetValidFor(time.Hour)
token, _ := at.ToJWT()
return token
}
func main() {
http.HandleFunc("/getToken", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(getJoinToken("my-room", "identity")))
})
log.Fatal(http.ListenAndServe(":8080", nil))
}

Load the environment variables and run the server:

$ source development.env
$ go run server.go

4. Create a client app to connect

Create a client app that fetches a token from the server we just made, then uses it to connect to a LiveKit room: