> ## Documentation Index
> Fetch the complete documentation index at: https://www.voiceflow.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Call a Chat agent from Node.js

> Start a Voiceflow Chat session, send a customer message and read text traces using Node.js fetch and the current session API.

Use Node.js’s built-in `fetch` to call the Chat HTTP API from your server. Session creation uses your API credential; the returned session key authenticates subsequent turns.

## Before you begin

- A supported Node.js release with built-in `fetch`.
- A published Chat agent. [Build and publish one from code](/docs/guides/developers/build-and-publish) if you are starting from an empty workspace.
- A [personal or service key](/docs/api-reference/authentication) authorized for the project’s `project:READ` and `project.versions:READ` actions.

Set `VF_TOKEN` from your server’s secret store, `VF_PROJECT_ID` to the agent’s project ID and `VF_ENVIRONMENT` to the published Environment’s alias. This example uses Voiceflow’s default public runtime. Keep the API credential and session keys out of browser bundles and logs.

## Run a conversation

### 1. Save the server script

Save the following as `chat.mjs`:

```javascript title="chat.mjs"
import { randomUUID } from 'node:crypto';

const { VF_TOKEN, VF_PROJECT_ID, VF_ENVIRONMENT } = process.env;
for (const [name, value] of Object.entries({ VF_TOKEN, VF_PROJECT_ID, VF_ENVIRONMENT })) {
  if (!value) throw new Error(`Set ${name} before running this script`);
}

const base = 'https://general-runtime.voiceflow.com';

async function post(path, credential, body) {
  const response = await fetch(new URL(path, base), {
    method: 'POST',
    headers: {
      Authorization: credential,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(body),
  });
  const text = await response.text();
  if (!response.ok) {
    throw new Error(`Voiceflow HTTP ${response.status}: ${text}`);
  }
  try {
    return JSON.parse(text);
  } catch {
    throw new Error('Voiceflow returned a response that is not valid JSON');
  }
}

const session = await post(
  `/v4/project/${encodeURIComponent(VF_PROJECT_ID)}/environment/${encodeURIComponent(VF_ENVIRONMENT)}/session`,
  VF_TOKEN,
  { userID: `node-quickstart-${randomUUID()}`, versionVariant: 'published' },
);
if (typeof session.sessionKey !== 'string' || !session.sessionKey) {
  throw new Error('Session creation returned no sessionKey');
}

await post('/v4/interact', session.sessionKey, {
  action: { type: 'launch' },
});
const reply = await post('/v4/interact', session.sessionKey, {
  action: { type: 'text', payload: 'Can you help with my order?' },
});
if (!Array.isArray(reply.traces)) throw new Error('The turn returned no traces array');
const messages = reply.traces.filter((trace) => trace.type === 'text');
if (!messages.length) throw new Error('The turn returned no text reply; inspect the agent and its diagnostics');
for (const trace of messages) console.log(trace.payload?.message ?? trace.payload);
```

`JSON.stringify` encodes customer text safely, including quotes and line breaks. Send the returned session key directly in `Authorization`, without adding `Bearer`.

### 2. Run the script

```bash
node chat.mjs
```

The script creates a new conversation, launches the agent, sends one message and prints its text reply. It does not create or publish agent resources.

## Verify the reply

Check that the reply follows your published agent’s instructions. HTTP success and a parsed response do not establish that the agent completed the intended customer task.

In your application, retain each customer conversation’s session key and reuse it for later turns. Calling the session-creation endpoint again starts a new session rather than resuming the previous one. Use [HTTP Streaming](/docs/api-reference/v4interact/interact-non-stream) when your interface needs incremental responses.

## Troubleshooting

| Symptom | Check |
| --- | --- |
| Session creation fails | Confirm the project, Environment alias, published release and credential permissions. |
| A turn is unauthorized | Use the session key returned for that conversation, directly in the header. |
| A successful turn has no text reply | Inspect the agent’s behavior and diagnostic traces; do not treat a diagnostic-only response as a customer answer. |
| A response is not valid JSON | Preserve the failure for investigation. Do not silently delete characters from the response and treat the changed data as a successful result. |

## Related references

- [Chat session contract](/docs/api-reference/v4interact/start-session-specific-environment)
- [Chat responses](/docs/api-reference/agent-runtime/chat/responses)
- [Runtime SDK source: `@voiceflow/sdk-runtime`](https://github.com/voiceflow/webchat/tree/master/libs/sdk-runtime)
