1. Backend: Generate a Signed JWT
Do not share your Vapi Private API Key with the frontend. Instead, use your backend to generate a signed JWT (JSON Web Token) using your Vapi Private Key. This allows the frontend to connect to Vapi without exposing your secrets.
You will need a library like jsonwebtoken in your Node/TypeScript backend.
TypeScript
import jwt from 'jsonwebtoken';
// API Endpoint: /api/start-interview
app.post('/api/start-interview', async (req, res) => {
const { userId, username } = req.body;
// 1. Verify User Subscription (Your custom logic)
const isSubscribed = await checkUserSubscription(userId);
if (!isSubscribed) {
return res.status(403).json({ error: "Subscription required" });
}
// 2. Generate Vapi JWT
// Get your Vapi Private Key and Org ID from Vapi Dashboard
const API_KEY = process.env.VAPI_PRIVATE_KEY;
const ORG_ID = process.env.VAPI_ORG_ID;
const payload = {
orgId: ORG_ID,
// "public" scope allows the token to be used for web calls
token: {
tag: "public",
}
};
const token = jwt.sign(payload, API_KEY, {
algorithm: 'HS256',
expiresIn: '1h', // Token expires in 1 hour
});
// 3. Return the Token and Context to Frontend
res.json({
token: token,
assistantId: "YOUR_ASSISTANT_ID", // ID of the assistant using the workflow
userData: {
username: username,
userid: userId
}
});
});