Introduction
When building a live-streaming app, security is often an afterthought—until something goes wrong. If you are using ZEGOCLOUD for video calls, exposing your AppSecret in the frontend is a major security risk.
In this tutorial, I'll show you how to build a secure Token Mint using Supabase Edge Functions. This ensures your secret keys stay on the server, while your app gets a safe, temporary token to join rooms.
Prerequisites
To follow along, you’ll need:
Step 1: Create the Edge Function
Open your terminal in your project folder and run:
supabase functions new get-zego-token
This creates a new folder: supabase/functions/get-zego-token/index.ts.
Step 2: The Token Generation Logic
We will use the zego-server-assistant library to generate a Token04. Paste the following code into your index.ts:
import { serve } from "https://deno.land/std@0.168.0/http/server.ts"
import { generateToken04 } from 'https://esm.sh/zego-server-assistant@1.0.1'
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
}
serve(async (req) => {
if (req.method === 'OPTIONS') {
return new Response('ok', { headers: corsHeaders })
}
try {
const { userId, roomID } = await req.json()
const appId = parseInt(Deno.env.get('ZEGO_APP_ID') || '0')
const serverSecret = Deno.env.get('ZEGO_SERVER_SECRET') || ''
const effectiveTimeInSeconds = 3600 // 1 hour
const payload = ''
const token = generateToken04(appId, userId, serverSecret, effectiveTimeInSeconds, payload)
return new Response(
JSON.stringify({ token }),
{ headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
)
} catch (error) {
return new Response(JSON.stringify({ error: error.message }), {
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 400,
})
}
})
Step 3: Secure Your Secrets
Don't hardcode your keys! Use the Supabase CLI to set your environment variables:
supabase secrets set ZEGO_APP_ID=your_app_id
supabase secrets set ZEGO_SERVER_SECRET=your_server_secret
Then, deploy your function:
supabase functions deploy get-zego-token
Conclusion
You now have a production-ready backend that keeps your ZEGOCLOUD credentials safe. By calling this function from your frontend, you can securely generate tokens on the fly.
I’m a developer currently building a Social Live-Streaming platform. If you found this helpful, follow me for more deep dives into real-time web tech!
Top comments (0)