layercode-node-server-sdk.

Introduction

The Layercode Node.js Backend SDK provides a simple way to handle the Layercode webhook in your backend. In particular, it makes it easy to return SSE events in the Layercode webhook response format. It supports all popular JavaScript runtime environments, including Node.js, Bun, and Cloudflare Workers.

See our Backend Guides for more information about how to use the SDK in your project.

Installation

npm install @layercode/node-server-sdk

Usage

import { streamResponse } from "@layercode/node-server-sdk";

//... inside your webhook request handler ...
return streamResponse(request, async ({ stream }) => {
  stream.tts("Hi, how can I help you today?"); // This text will be sent to Layercode, converted to speech and spoken to the user
  // Call stream.tts() as many times as you need to send multiple pieces of speech to the user
  stream.end(); // This closes the stream and must be called at the end of your response
});
// ...

Reference

streamResponse

The streamResponse function is the main entry point for the SDK. It takes the request body (from the Layercode webhook request) and a handler function as arguments. The handler function receives a stream object that can be used to send SSE events to the client.

function streamResponse(requestBody: Record<string, any>, handler: StreamResponseHandler): Response;

Parameters

  • requestBody: The request body from the client. See Webhook Request Payload.
  • handler: An async function that receives a stream object.

Stream Methods

  • stream.tts(content: string): Sends a text to be spoken to the user (tts stands for text-to-speech).
  • stream.data(content: any): Sends any arbitrary data to the frontend client. Use this for updating your frontend UI.
  • stream.end(): Closes the stream. Must be called at the end of your response.

Examples

Here are some examples of how to use the Node SDK. See the corresponding guides for more details:

import express from "express";
import { streamResponse } from "@layercode/node-server-sdk";

const app = express();
app.use(express.json());

app.post("/agent", async (req, res) => {
  return streamResponse(req.body, async ({ stream }) => {
    stream.tts("Hi, how can I help you today?");
    stream.end();
  });
});

Backend Guides