You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase托管Twilio视频应用Token无效:Server.js转Cloud Function方法咨询

Migrate Twilio Token Server to Firebase Cloud Functions

Got it, let's get your Twilio token endpoint migrated to Firebase Cloud Functions smoothly. Here's how to refactor your existing server.js into a proper Cloud Function, fix the invalid token issue, and tie everything together with Firebase's environment setup.

Step 1: Refactor into Cloud Functions index.js

First, replace or update your functions/index.js file with this code. We'll ditch the Express server wrapper and use Firebase's native HTTP trigger, while keeping your core Twilio token logic intact:

const functions = require('firebase-functions');
const { AccessToken } = require('twilio').jwt;
const { VideoGrant } = AccessToken;

// Load environment variables from Firebase Config
const config = functions.config();
for (const key in config.envs) {
  process.env[key.toUpperCase()] = config.envs[key];
}

const MAX_ALLOWED_SESSION_DURATION = 14400;
const twilioAccountSid = process.env.TWILIO_ACCOUNT_SID;
const twilioApiKeySID = process.env.TWILIO_API_KEY_SID;
const twilioApiKeySecret = process.env.TWILIO_API_KEY_SECRET;

// HTTP function to generate Twilio Video tokens
exports.generateTwilioToken = functions.https.onRequest((req, res) => {
  // Allow CORS (critical for Firebase Hosting frontend access)
  res.set('Access-Control-Allow-Origin', '*');
  if (req.method === 'OPTIONS') {
    // Handle pre-flight OPTIONS requests
    res.set('Access-Control-Allow-Methods', 'GET');
    res.set('Access-Control-Allow-Headers', 'Content-Type');
    res.status(204).send('');
    return;
  }

  // Extract required query parameters
  const { identity, roomName } = req.query;

  // Validate input to avoid bad requests
  if (!identity || !roomName) {
    return res.status(400).send('Missing required parameters: identity and roomName are both needed');
  }

  // Create and sign the Twilio access token
  const token = new AccessToken(
    twilioAccountSid,
    twilioApiKeySID,
    twilioApiKeySecret,
    { ttl: MAX_ALLOWED_SESSION_DURATION }
  );
  token.identity = identity;

  const videoGrant = new VideoGrant({ room: roomName });
  token.addGrant(videoGrant);

  // Send the JWT token as response
  res.send(token.toJwt());
  console.log(`Issued token for ${identity} in room ${roomName}`);
});

Step 2: Set Up Environment Variables in Firebase

Never hardcode credentials! Store your Twilio secrets securely in Firebase's environment config with these terminal commands:

# Set your Twilio Account SID
firebase functions:config:set envs.twilio_account_sid="YOUR_TWILIO_ACCOUNT_SID"

# Set your Twilio API Key SID
firebase functions:config:set envs.twilio_api_key_sid="YOUR_TWILIO_API_KEY_SID"

# Set your Twilio API Key Secret
firebase functions:config:set envs.twilio_api_key_secret="YOUR_TWILIO_API_KEY_SECRET"

Step 3: Update Firebase Hosting Rewrites (Cleaner Frontend Requests)

To let your frontend use a clean relative path like /token instead of the full Cloud Function URL, add a rewrite rule to your firebase.json file:

{
  "hosting": {
    "public": "build",
    "rewrites": [
      {
        "source": "/token",
        "function": "generateTwilioToken"
      },
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}

This routes all /token requests to your Cloud Function, while serving your static app for all other paths.

Step 4: Deploy and Test

  1. Deploy your function and hosting config:
firebase deploy --only functions,hosting
  1. Test the endpoint directly to verify it works:
curl "https://YOUR_PROJECT_REGION-YOUR_PROJECT_ID.cloudfunctions.net/generateTwilioToken?identity=testUser&roomName=testRoom"

You should get a valid JWT token in response. If not, check Firebase Functions logs with firebase functions:log to debug credential or setup issues.

Key Fixes for "Invalid Token" Errors

  • Verify Twilio permissions: Ensure your Twilio API Key has the Video permission enabled in the Twilio Console.
  • Check token validity: Use a JWT decoder to confirm the token's sid, iss, and expiration time match your credentials.
  • CORS enforcement: The code includes CORS handling to prevent browser blockages when your frontend calls the endpoint.

内容的提问来源于stack exchange,提问作者Will Cousin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 13:03:14