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

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 (
"http"
"log"
"time"
lksdk "github.com/livekit/server-sdk-go"
"github.com/livekit/protocol/auth"
)
func getJoinToken(room, identity string) string {
config = readFile(config)
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)
return at.ToJWT()
}
func main() {
http.HandleFunc("/getToken", func(w http.ResponseWriter, r *http.Request) {
w.write(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: