How to set up token server? and how to integrate i...
# ask-ai
b
How to set up token server? and how to integrate it in flutter app?
t
Thanks for reaching out, Rongrong. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Setting up a token server and connecting it to your Flutter app for LiveKit is easier than you might think! Just follow these steps: Setting Up the Token Server 1. Pick a backend language you’re comfortable with and install the LiveKit Server SDK. For example: ◦ Node.js:
npm install livekit-server-sdk
◦ Go:
go get github.com/livekit/server-sdk-go/v2
1. Make sure to keep your API keys safe by putting them in a secure environment file. 2. Create an endpoint to generate tokens. Here’s a simple example in Node.js:`import express from 'express'; import { AccessToken } from 'livekit-server-sdk'; const app = express(); const port = 3000; app.post('/token', async (req, res) => { const { roomName, participantName } = req.body; const at = new AccessToken('your-api-key', 'your-api-secret', { identity: participantName, ttl: '10m', }); at.addGrant({ roomJoin: true, room: roomName }); res.send(at.toJwt()); }); app.listen(port, () => console.log(
Server running on port ${port}
));` Integrating with Your Flutter App 1. Create a service in your Flutter app that fetches tokens from your server. Here’s a quick example:
Copy code
import 'dart:convert';
import 'package:http/http.dart' as http;

class TokenService {
  final String tokenServerUrl = <YOUR_TOKEN_SERVER_URL>;

  Future<String> fetchToken(String roomName, String participantName) async {
    final response = await http.post(
      Uri.parse(tokenServerUrl),
      headers: {'Content-Type': 'application/json'},
      body: jsonEncode({'roomName': roomName, 'participantName': participantName}),
    );

    if (response.statusCode == 200) {
      return response.body;
    } else {
      throw Exception('Failed to fetch token');
    }
  }
}
2. Then, use that token to connect your Flutter app to LiveKit. When you’re ready for production, just double-check that your token server is secure and hooked up to your authentication system. If you have any questions or want me to walk you through anything, just let me know — I’m here to help!
b
is there an example project with token server in production setup? not sandbox mode
t
Hey there! Yes, there’s a handy example project you can use to set up a token server and integrate it into a Flutter app with LiveKit. Flutter Agent Starter Project This project gives you a full setup for both token server integration and a Flutter app. Here’s what you’ll find inside: • A Flutter app template designed for LiveKit Agents • A built-in token service implementation in
lib/services/token_service.dart
• Support for iOS, macOS, Android, and web platforms • Easy integration with LiveKit Cloud Sandbox for quick prototyping Getting Started 1. Create a Sandbox Token Server for your LiveKit Cloud project. 2. Clone and connect the template using the LiveKit CLI:
Copy code
lk app create --template agent-starter-flutter --sandbox <token_server_sandbox_id>
1. Install dependencies and run:
Copy code
flutter pub get
flutter run
Alternative Setup If you’d rather skip the CLI, no worries! You can manually clone the repo and set things up by: • Adding a
LIVEKIT_SANDBOX_ID
to your
.env
file for sandbox use • Updating
token_service.dart
with your own token server URL and manually generated tokens Feel free to reach out if you want a hand with setting up the example project—I’m here to help! Sources: lib/services/token_service.dart | README.md
b
do you have token server example in python?
t
Sure thing! There are some Python-based examples to help you set up a token server for LiveKit. Here are a few options you might find useful: 1. Standalone Token Generation Function This example shows a straightforward function to generate tokens using the LiveKit Python SDK:
Copy code
import os
from livekit import api

def generate_token(room_name, identity):
    token = (
        api.AccessToken(os.getenv('LIVEKIT_API_KEY'), os.getenv('LIVEKIT_API_SECRET'))
        .with_identity(identity)
        .with_grants(api.VideoGrants(room_join=True, room=room_name))
        .to_jwt()
    )
    return token
2. Flask-Based Token Server Here’s an example using Flask to create an endpoint for token generation:
Copy code
from flask import Flask, request, jsonify
from livekit import api

app = Flask(__name__)

@app.route('/generate-token', methods=['POST'])
def generate_token():
    data = request.json
    room_name = data.get('room_name')
    identity = data.get('identity')

    token = (
        api.AccessToken(os.getenv('LIVEKIT_API_KEY'), os.getenv('LIVEKIT_API_SECRET'))
        .with_identity(identity)
        .with_grants(api.VideoGrants(room_join=True, room=room_name))
        .to_jwt()
    )
    return jsonify({'token': token})
3. Repository Links • Standalone Token Function • Flask-Based Token Server If you have any questions or want to dive deeper into these examples, just let me know—I’m here to help! Sources: templates.yaml | complex-agents/ivr-agent/flask_livekit/extension.py | ivr-nagivator/flask_livekit/extension.py | examples/rpc.py | auth.py
b
Does the Standalone Token Generation Function create tokens locally? if so, what are the differences in standalone function vs token server?
t
Both the standalone token generation function and a token server create tokens, but they do it in different ways and for different needs: Standalone Token Generation Function • This generates tokens right inside your application or script. • It’s great for development, testing, or smaller projects where your app handles token creation directly. • Just a heads-up: it needs the API key and secret stored within the app, which could be a security concern if they get exposed. • So, it’s not the best fit for production setups where many users or devices need tokens safely. Token Server • This is a dedicated backend service that creates tokens whenever you ask for them. • Your API keys and secrets stay securely on the server, which helps keep things safe. • It also supports authentication and authorization, so you can control who gets tokens. • Perfect for scaling up and handling production environments with lots of users or devices. • Plus, it can work with your existing authentication systems to make everything smooth for users. So, to sum it up: the standalone function is quicker and easier to set up but less secure and scalable, while a token server offers better security and is ready for production. If you want, I’m here to help you set up whichever option fits your needs!
✅ 1
b
how to integrate app with render token service
t
Hey there! To get your app working smoothly with a render token service, here’s a simple step-by-step guide: 1. Token Service Setup • First, deploy a token server using the LiveKit Server SDK. Here’s a quick example in Node.js:
Copy code
import express from 'express';
import { AccessToken } from 'livekit-server-sdk';

const app = express();
app.post('/token', async (req, res) => {
  const { roomName, participantName } = req.body;
  const token = new AccessToken('your-api-key', 'your-api-secret', {
    identity: participantName,
    ttl: '10m',
  }).addGrant({ roomJoin: true, room: roomName }).toJwt();
  res.send(token);
});

app.listen(3000, () => console.log('Token server running on port 3000'));
2. Environment Configuration • Next up, set your environment variables on Render.com like this:
Copy code
LIVEKIT_URL=wss://your-livekit-url.livekit.cloud
LIVEKIT_API_KEY=your-livekit-api-key
LIVEKIT_API_SECRET=your-livekit-api-secret
3. Client-Side Integration • Then, in your app, you’ll want to fetch tokens from your token server. Here’s how you might do it in Flutter:
Copy code
class TokenService {
  final String tokenServerUrl = <YOUR_TOKEN_SERVER_URL>;

  Future<String> fetchToken(String roomName, String participantName) async {
    final response = await http.post(
      Uri.parse(tokenServerUrl),
      headers: {'Content-Type': 'application/json'},
      body: jsonEncode({'roomName': roomName, 'participantName': participantName}),
    );

    if (response.statusCode == 200) {
      return response.body;
    } else {
      throw Exception('Failed to fetch token');
    }
  }
}
4. Development vs Production • For development, feel free to use LiveKit Cloud Sandbox or even hardcoded tokens to get started quickly. • When you’re ready for production, make sure your token server is secure and properly integrated with your authentication system. If you hit any bumps or want to chat more about this setup, just let me know—I’m here to help! Sources: render.com/README.md | Authentication Examples | livekit/livekit_composite | DeepWiki | lib/services/token_service.dart | Next.js quickstart | LiveKit Docs | TEMPLATE.md