This backend example is part of a full-stack example that also includes a web voice agent React frontend. We recommend also reading the Next.js frontend guide to get the most out of this example.
Prerequisites
- Node.js 18+
- Next.js (App Router recommended)
- A Layercode account and agent (sign up here)
- (Optional) An API key for your LLM provider (we recommend Google Gemini)
Setup
Install dependencies:GOOGLE_GENERATIVE_AI_API_KEY
- Your Google AI API keyLAYERCODE_API_KEY
- Your Layercode API key found in the Layercode dashboard settingsLAYERCODE_WEBHOOK_SECRET
- Your Layercode agent’s webhook secret, found in the Layercode dashboard (go to your agent, click Edit in the Your Backend Box and copy the webhook secret shown)NEXT_PUBLIC_LAYERCODE_AGENT_ID
- The Layercode agent ID for your voice agent. Find this ID in Layercode dashboard
Create Your Next.js API Route
Here’s a simplified example of the core functionality needed to implement the Layercode webhook endpoint. See the GitHub repo for the full example.app/api/agent/route.ts
How It Works
- /api/agent webhook endpoint: Receives POST requests from Layercode with the user’s transcribed message, session, and turn info. The webhook request is verified as coming from Layercode.
- LLM call: Calls Google Gemini Flash 2.0 with the system prompt and user’s new transcribed message.
- SSE streaming: As soon as the LLM starts generating a response, the backend streams the output back as SSE messages to Layercode, which converts it to speech and delivers it to the frontend for playback in realtime.
Running Your Backend
Start your Next.js app:Configure the Layercode Webhook endpoint
In the Layercode dashboard, go to your agent settings. Under Your Backend, click edit, and here you can set the URL of the webhook endpoint. If running this example locally, setup a tunnel (we recommend cloudflared which is free for dev) to your localhost so the Layercode webhook can reach your backend. Follow our tunnelling guide.Test Your Voice Agent
There are two ways to test your voice agent:- Use the Layercode playground tab, found in the agent in the Layercode dashboard.
- As this example is a full-stack example, you can visit http://localhost:3000 in your browser and speak to the voice agent in your browser using the React frontend included.