package
Slack adapter for Chat SDK — webhooks, Block Kit cards, OAuth, slash commands, and AI streaming
npm install @chat-adapter/slackGitHub-flavored package documentation.
Across all versions.
Download trend unavailable.
Runtime metadata.
Tagged topics.
vercel-release-bot
infra+release@vercel.com
Slack adapter for Chat SDK. Configure single-workspace or multi-workspace OAuth deployments.
Documentation: chat-sdk.dev/adapters/official/slack · Guides: vercel.com/kb/chat-sdk
pnpm add @chat-adapter/slackTo scaffold a new Slack bot with this adapter preselected:
npx create-chat-sdk@latest my-bot --adapter slack memoryVisit the adapters directory to see other available official and vendor-official adapters.
For managed credentials and webhook verification, see Vercel Connect.
For bots deployed to a single Slack workspace. The adapter auto-detects SLACK_BOT_TOKEN and SLACK_SIGNING_SECRET from environment variables:
import { Chat } from "chat";
import { createSlackAdapter } from "@chat-adapter/slack";
const bot = new Chat({
userName: "mybot",
adapters: {
slack: createSlackAdapter(),
},
});
bot.onNewMention(async (thread, message) => {
await thread.post("Hello from Slack!");
});All options are auto-detected from environment variables when not provided. You can call createSlackAdapter() with no arguments if the env vars are set.
| Option | Required | Description |
|---|---|---|
botToken | No | Bot token (xoxb-...) or a function returning one (sync or async) for rotation/lazy fetch. Auto-detected from SLACK_BOT_TOKEN |
signingSecret | No* | Signing secret for webhook verification. Auto-detected from SLACK_SIGNING_SECRET |
webhookVerifier | No* | Custom verifier (request, body) => unknown | Promise<unknown> used in place of signingSecret. Returning a string substitutes the verified body for downstream parsing |
mode | No | Connection mode: "webhook" (default) or "socket" |
appToken | No** | App-level token (xapp-...) for socket mode. Auto-detected from SLACK_APP_TOKEN |
socketForwardingSecret | No | Shared secret for authenticating forwarded socket events. Auto-detected from SLACK_SOCKET_FORWARDING_SECRET, falls back to appToken |
clientId | No | App client ID for multi-workspace OAuth. Auto-detected from SLACK_CLIENT_ID |
clientSecret | No | App client secret for multi-workspace OAuth. Auto-detected from SLACK_CLIENT_SECRET |
encryptionKey | No | AES-256-GCM key for encrypting stored tokens. Auto-detected from SLACK_ENCRYPTION_KEY |
installationKeyPrefix | No | Prefix for the state key used to store workspace installations. Defaults to slack:installation. The full key is {prefix}:{teamId} (or {prefix}:{enterpriseId} for Enterprise Grid org-wide installs) |
installationProvider | No | External installation lookup { getInstallation(installationId, isEnterpriseInstall) => Promise<SlackInstallation | null> }. When set, bypasses the internal state adapter for token resolution on incoming webhooks. Read-only — manage your own writes externally |
apiUrl | No | Override the Slack Web API base URL (e.g. for GovSlack or a self-hosted gateway). Auto-detected from SLACK_API_URL |
fetch | No | Fetch for response URLs and Socket Mode webhook forwarding; defaults to global fetch |
fileTransport | No | Guarded file download transport; custom transports own connection/DNS policy |
webClientOptions | No | Options forwarded to Slack WebClient instances, excluding slackApiUrl. Supports retryConfig, per-request timeout, and rejectRateLimitedCalls; agent also configures Socket Mode, tls only its HTTP calls |
logger | No | Logger instance (defaults to ConsoleLogger("info")) |
*signingSecret is required for webhook mode — either via config, SLACK_SIGNING_SECRET env var, or a webhookVerifier.
**appToken is required for socket mode — either via config or SLACK_APP_TOKEN env var.
Use Vercel Connect to source the bot token at runtime instead of storing one. The connectSlackAdapter() helper from @vercel/connect/chat wires both a botToken resolver and a webhookVerifier for Connect trigger-forwarded webhooks:
import { createSlackAdapter } from "@chat-adapter/slack";
import { connectSlackAdapter } from "@vercel/connect/chat";
createSlackAdapter({
...connectSlackAdapter("slack/acme-slack"),
});This is equivalent to passing a botToken resolver that calls getToken and a webhookVerifier that validates the Vercel OIDC token Connect attaches. Omit signingSecret / SLACK_SIGNING_SECRET when using it.
Provide SLACK_BOT_TOKEN and SLACK_SIGNING_SECRET as shown in Quick start.
botToken accepts a function returning a string or Promise<string> — the resolver is invoked per API call, so it composes with Slack token rotation (12-hour TTL) or lazy fetch from a secret manager:
createSlackAdapter({
botToken: async () => await secrets.get("slack-bot-token"),
});If the resolver is expensive (e.g. a vault round-trip), implement caching inside the resolver itself.
Pass webhookVerifier to replace the built-in HMAC check — useful when verification runs in a proxy or signing layer ahead of your handler:
createSlackAdapter({
webhookVerifier: async (request, body) => {
if (!(await myProxy.verify(request))) {
throw new Error("invalid");
}
return true; // or return a string to substitute the verified body
},
});If both signingSecret and webhookVerifier are set, webhookVerifier wins — it also takes precedence over the SLACK_SIGNING_SECRET env var, so an env-configured deployment can't silently shadow a verifier you wired up. When using webhookVerifier, you are responsible for replay/timestamp protection — the built-in 5-minute timestamp tolerance only applies to the signingSecret path.
For apps installed across multiple Slack workspaces via OAuth, omit botToken and provide OAuth credentials instead. The adapter resolves tokens dynamically from your state adapter using the team_id from incoming webhooks — or enterprise_id for Enterprise Grid org-wide installs (is_enterprise_install: true).
When you pass any auth-related config (like clientId), the adapter won't fall back to env vars for other auth fields, preventing accidental mixing of auth modes.
import { createSlackAdapter } from "@chat-adapter/slack";
import { createRedisState } from "@chat-adapter/state-redis";
const slackAdapter = createSlackAdapter({
clientId: process.env.SLACK_CLIENT_ID!,
clientSecret: process.env.SLACK_CLIENT_SECRET!,
});
const bot = new Chat({
userName: "mybot",
adapters: { slack: slackAdapter },
state: createRedisState(),
});The adapter handles the full Slack OAuth V2 exchange. Point your OAuth redirect URL to a route that calls handleOAuthCallback:
import { slackAdapter } from "@/lib/bot";
export async function GET(request: Request) {
const { teamId } = await slackAdapter.handleOAuthCallback(request, {
redirectUri: process.env.SLACK_REDIRECT_URI,
});
return new Response(`Installed for team ${teamId}!`);
}If your install flow uses a specific redirect URI, pass the same value here that you used during the authorize step. This is especially useful when one app supports multiple redirect URLs. When no option is provided, the adapter still falls back to redirect_uri on the callback request URL.
For Enterprise Grid org-wide installs (is_enterprise_install), Slack returns no team and the installation is keyed by the enterprise ID instead. The returned teamId is always the storage key — the enterprise ID for org-wide installs — so it round-trips with getInstallation and deleteInstallation for both install types. The result also includes enterpriseId and isEnterpriseInstall when you need to distinguish them.
During webhook handling, the adapter resolves tokens automatically from team_id. Outside that context (e.g. cron jobs or background workers), use getInstallation and withBotToken:
const install = await slackAdapter.getInstallation(teamId);
if (!install) throw new Error("Workspace not installed");
await slackAdapter.withBotToken(
install.botToken,
async () => {
const thread = bot.thread("slack:C12345:1234567890.123456");
await thread.post("Hello from a cron job!");
},
{ installationId: teamId, botUserId: install.botUserId }
);withBotToken uses AsyncLocalStorage under the hood, so concurrent calls with different tokens are isolated. In multi-workspace deployments, pass installationId (the team_id, or enterprise_id for org-wide installs) so per-user caches are scoped to that installation and don't bleed across tenants. Also pass the installation's botUserId: a multi-workspace adapter has no fixed bot user ID, so without it slackAdapter.botUserId is undefined inside the callback and the bot's own messages, such as those returned by fetchMessages, have author.isMe set to false.
await slackAdapter.deleteInstallation(teamId);When a workspace uninstalls the app, Slack sends app_uninstalled and the adapter calls bot.onUninstalled. Add app_uninstalled to your manifest's bot_events to receive it. event.conversationId is the installation key (the team_id, or enterprise_id for org-wide installs), and event.tenantId is the Enterprise Grid enterprise_id when there is one. The adapter doesn't delete the installation itself:
bot.onUninstalled(async (event) => {
if (event.adapter.name !== "slack") return;
await slackAdapter.deleteInstallation(event.conversationId);
});If you read installations through installationProvider, also delete the record from your own store. tokens_revoked doesn't call onUninstalled, because Slack also sends it for revocations that leave the app installed. See Uninstalls.
Pass a base64-encoded 32-byte key as encryptionKey to encrypt bot tokens at rest using AES-256-GCM:
openssl rand -base64 32When encryptionKey is set, setInstallation() encrypts the token before storing and getInstallation() decrypts it transparently.
For deployments that manage Slack tokens in an external system (e.g. Vercel Connect), pass installationProvider to bypass the internal state adapter when resolving tokens for incoming webhooks:
createSlackAdapter({
clientId: process.env.SLACK_CLIENT_ID!,
clientSecret: process.env.SLACK_CLIENT_SECRET!,
installationProvider: {
getInstallation: async (installationId, isEnterpriseInstall) => {
// installationId is enterprise_id when isEnterpriseInstall is true,
// otherwise team_id. Return null if not found.
return await myTokenStore.lookup(installationId, isEnterpriseInstall);
},
},
});When configured, the provider's getInstallation is called for every webhook event, slash command, and interactive payload. It is read-only — the adapter's setInstallation, deleteInstallation, and handleOAuthCallback continue to write to the internal state adapter, so callers using a provider should manage their own writes through their external system.
For Enterprise Grid org-wide installs the adapter handles the Grid-specific mechanics automatically:
enterprise_id and incoming payloads resolve tokens the same way (is_enterprise_install).team_id explicitly — org-wide tokens span every workspace in the org, and Slack requires the ID on workspace-scoped methods.context_team_id), channel-addressed calls echo it back as client_context_team_id.event_id via the state adapter, so Slack's redelivery of slow-acked events doesn't double-process reactions or assistant events.For environments behind firewalls that can't expose public HTTP endpoints, the adapter supports Slack Socket Mode. Instead of receiving webhooks, the adapter connects to Slack over a WebSocket.
import { Chat } from "chat";
import { createSlackAdapter } from "@chat-adapter/slack";
const bot = new Chat({
userName: "mybot",
adapters: {
slack: createSlackAdapter({
mode: "socket",
appToken: process.env.SLACK_APP_TOKEN!,
botToken: process.env.SLACK_BOT_TOKEN!,
}),
},
});connections:write scope — this is your SLACK_APP_TOKEN (xapp-...)Socket mode works with both single-workspace tokens and multi-workspace OAuth: events arriving over the socket (or forwarded from a socket listener) resolve per-installation tokens by
team_id— orenterprise_idfor Enterprise Grid org-wide installs — the same way the webhook path does.
Socket mode requires a persistent WebSocket connection, which doesn't fit the request/response model of serverless functions. The adapter provides a forwarding mechanism to bridge this gap:
// api/slack/socket-mode/route.ts
import { after } from "next/server";
import { bot } from "@/lib/bot";
export const maxDuration = 800;
export async function GET(request: Request) {
const authHeader = request.headers.get("authorization");
if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) {
return new Response("Unauthorized", { status: 401 });
}
await bot.initialize();
const slack = bot.getAdapter("slack");
const webhookUrl = `https://${process.env.VERCEL_URL}/api/webhooks/slack`;
return slack.startSocketModeListener(
{ waitUntil: (task: Promise<unknown>) => after(() => task) },
600_000, // 10 minutes
undefined,
webhookUrl
);
}Schedule the cron job to run every 9 minutes (overlapping with the 10-minute listener duration) to maintain continuous coverage:
// vercel.json
{
"crons": [
{
"path": "/api/slack/socket-mode",
"schedule": "*/9 * * * *"
}
]
}Forwarded events are authenticated using the socketForwardingSecret config option (defaults to SLACK_SOCKET_FORWARDING_SECRET env var, falling back to appToken).
display_information:
name: My Bot
description: A bot built with chat-sdk
features:
bot_user:
display_name: My Bot
always_online: true
oauth_config:
scopes:
bot:
- app_mentions:read
- channels:history
- channels:read
- chat:write
- groups:history
- groups:read
- im:history
- im:read
- mpim:history
- mpim:read
- reactions:read
- reactions:write
- users:read
settings:
event_subscriptions:
request_url: https://your-domain.com/api/webhooks/slack
bot_events:
- app_mention
- message.channels
- message.groups
- message.im
- message.mpim
- member_joined_channel
- assistant_thread_started
- assistant_thread_context_changed
- app_uninstalled
interactivity:
is_enabled: true
request_url: https://your-domain.com/api/webhooks/slack
org_deploy_enabled: false
socket_mode_enabled: false
token_rotation_enabled: falsehttps://your-domain.com/api/webhooks/slack with your deployed webhook URLAfter creating the app, go to Basic Information → App Credentials and copy:
SLACK_SIGNING_SECRETSLACK_CLIENT_ID (multi-workspace only)SLACK_CLIENT_SECRET (multi-workspace only)Single workspace: Go to OAuth & Permissions, click Install to Workspace, and copy the Bot User OAuth Token (xoxb-...) as SLACK_BOT_TOKEN.
Multi-workspace: Enable Manage Distribution under Basic Information and set up an OAuth redirect URL pointing to your callback route.
/feedback)https://your-domain.com/api/webhooks/slackIncoming file attachments expose a lazy fetchData(). Downloads go through a guarded fetcher that limits responses to 25 MB, times out after 30 seconds, and, with the default transport, refuses private and internal addresses (including after redirects). The bot token is sent only to trusted Slack origins and never follows a redirect to another host. Set fileTransport to route downloads through a proxy, or override createFileTransport() in a subclass. A custom transport takes over the destination-address policy, so see Egress proxies for what it must enforce.
Configure each transport your deployment uses. webClientOptions.agent covers Slack Web API calls (including OAuth and all upload phases) and the HTTP/WebSocket connections for both persistent and transient Socket Mode. fetch covers response_url updates and Socket Mode forwarding to your application's webhook. fileTransport covers lazy fetchData() and rehydrated attachments.
For Node.js, install https-proxy-agent and undici in your application. This example assumes a controlled proxy that rejects internal destination addresses and DNS rebinding, including when it resolves CONNECT destinations. A custom file transport replaces the default DNS-pinned transport, which is the only place resolved addresses are checked against the private-range blocklist. Local DNS checks alone cannot enforce the address a remote proxy actually uses, so that policy has to live in the proxy.
import { request } from "node:https";
import {
type AttachmentTransport,
createSlackAdapter,
} from "@chat-adapter/slack";
import { HttpsProxyAgent } from "https-proxy-agent";
import { ProxyAgent } from "undici";
const proxyUrl = process.env.HTTPS_PROXY!;
const agent = new HttpsProxyAgent(proxyUrl);
const dispatcher = new ProxyAgent(proxyUrl);
// Node's native fetch accepts an Undici dispatcher. Keep the standard fetch
// input/output types so Request, Response, and streaming bodies retain parity.
const proxyFetch: typeof globalThis.fetch = (input, init) => {
const options: RequestInit = { ...init };
// Add Node's dispatcher extension separately from the standard fetch options.
Object.assign(options, { dispatcher });
return globalThis.fetch(input, options);
};
const fileTransport: AttachmentTransport = (url, signal, headers) =>
new Promise((resolve, reject) => {
// Return each raw response; the downloader handles redirects and strips
// Slack credentials on untrusted hops.
const req = request(url, { agent, signal, headers }, resolve);
req.on("error", reject);
req.end();
});
const slack = createSlackAdapter({
webClientOptions: { agent },
fetch: proxyFetch,
fileTransport,
});The downloader still validates each URL, limits redirects, sends credentials only to trusted Slack origins, rejects HTML login pages, and limits decoded bodies to 25 MB. The 30-second deadline is enforced by the downloader for both the wait for response headers and the body read, so it holds even if the transport ignores the signal. The transport should still honor the signal so the underlying connection is released promptly. The transport must not follow redirects itself. Existing createFileTransport() subclass overrides take precedence over fileTransport.
Socket Mode receives agent, tls, and apiUrl, but only agent reaches the WebSocket itself; tls and apiUrl apply to its HTTP calls. The Slack SDK opens the WebSocket with the agent alone, so a custom CA or other TLS settings for that connection must be configured on the agent. App-token authentication, headers, and retry options remain SDK defaults, since Web API headers are not Socket Mode headers. Configure routing/bypass in your fetch implementation if the forwarded webhook uses an internal application URL. The adapter does not close caller-owned agents or dispatchers; close them when your application shuts down.
Standalone @chat-adapter/slack/api functions have their own options.fetch parameter and do not inherit adapter configuration. Application callbacks, token resolvers, installation providers, and state adapters also own their network configuration. Proxy authentication, CA trust, WebSocket support, and destination policy must be configured for your deployment.
SLACK_BOT_TOKEN=xoxb-... # Single-workspace only
SLACK_SIGNING_SECRET=... # Required for webhook mode
SLACK_APP_TOKEN=xapp-... # Required for socket mode
SLACK_SOCKET_FORWARDING_SECRET=... # Optional, for socket event forwarding auth
SLACK_CLIENT_ID=... # Multi-workspace only
SLACK_CLIENT_SECRET=... # Multi-workspace only
SLACK_ENCRYPTION_KEY=... # Optional, for token encryption
SLACK_API_URL=... # Optional, for GovSlack or a self-hosted gateway| Feature | Supported |
|---|---|
| Post message | Yes |
| Edit message | Yes |
| Delete message | Yes |
| File uploads | Yes |
| Streaming | Native API |
| Scheduled messages | Yes (native, with cancel) |
| Feature | Supported |
|---|---|
| Card format | Block Kit |
| Buttons | Yes |
| Link buttons | Yes |
| Select menus | Yes |
| Tables | Block Kit data table (paginated, sortable) |
| Charts | Block Kit data visualization (pie, bar, area, line) |
| Fields | Yes |
| Images in cards | Yes |
| Modals | Yes |
| Feature | Supported |
|---|---|
| Slash commands | Yes |
| Mentions | Yes |
| Add reactions | Yes |
| Remove reactions | Yes |
| Typing indicator | Yes |
| DMs | Yes |
| Ephemeral messages | Yes (native) |
| Feature | Supported |
|---|---|
| Fetch messages | Yes |
| Fetch single message | Yes |
| Fetch thread info | Yes |
| Fetch channel messages | Yes |
| List threads | Yes |
| Fetch channel info | Yes |
| Post channel message | Yes |
Incoming message authors include message.author.email when your app has the users:read.email scope (add it to the manifest alongside users:read). Without the scope, or when Slack omits the profile email, the field is undefined. The email comes from the same cached users.info lookup the adapter already performs for display names, so no extra API call is made per message.
| Feature | Supported |
|---|---|
| Assistants API | Yes |
| Member joined channel | Yes |
| App Home tab | Yes |
WebClient accessUse adapter.webClient to get a typed WebClient from @slack/web-api
for any Web API call that isn't wrapped by the SDK's high-level methods.
import type { SlackAdapter } from "@chat-adapter/slack";
bot.onAction("pin-this", async (event) => {
const slack = bot.getAdapter("slack") as SlackAdapter;
await slack.webClient.pins.add({
channel: event.thread!.channel.id.replace(/^slack:/, ""),
timestamp: event.messageId,
});
});The returned client is bound to the bot token resolved in this order:
adapter.withBotToken(token, fn).botToken, when configured as a static string or a
synchronous resolver function.adapter.webClient throws AuthenticationError outside of any context
in multi-workspace mode, or when botToken is configured as an async
resolver function. For both cases, await the token first and bind it
explicitly:
const install = await slackAdapter.getInstallation(teamId);
if (!install) throw new Error("Workspace not installed");
await slackAdapter.withBotToken(install.botToken, async () => {
const me = await slackAdapter.webClient.auth.test();
console.log("Bot user:", me.user_id);
});The previous
.clientgetter still works as a deprecated alias for.webClient.
Internal API calls (postMessage, editMessage, fetchMessages, etc.) are
unaffected — they continue to resolve tokens through the same async path
they always have.
Enable agentView: true for Slack's Agent messaging experience. Slack
deprecated assistant_view and will retire it in February 2027; the adapter
keeps it available as a compatibility path when agentView is false.
Agent Sessions provide lifecycle status, native stop, and session titles.
Pass thread.signal to model APIs so clicking Slack's stop button cancels
upstream generation:
const result = await agent.stream({
prompt: message.text,
abortSignal: thread.signal,
});
await thread.post(result.fullStream);Register handlers on the Chat instance:
bot.onAssistantThreadStarted(async (event) => {
const slack = bot.getAdapter("slack") as SlackAdapter;
await slack.setSuggestedPrompts(event.channelId, event.threadTs, [
{ title: "Summarize", message: "Summarize this channel" },
{ title: "Draft", message: "Help me draft a message" },
]);
});
bot.onAssistantContextChanged(async (event) => {
// User navigated to a different channel with the assistant panel open
});
bot.onAgentSessionStopped(async (event) => {
await releaseExternalResources(event.threadId);
});
bot.onAgentSessionTitleChanged(async (event) => {
await syncTitle(event.threadId, event.title);
});The SlackAdapter exposes these methods:
| Method | Description |
|---|---|
setSuggestedPrompts(channelId, threadTs, prompts, title?) | Show prompt suggestions in the thread |
setSessionStatus(channelId, threadTs, status) | Set processing, active, suspended, or closed |
setAssistantStatus(channelId, threadTs, status) | Compatibility wrapper for session/assistant status |
setAssistantTitle(channelId, threadTs, title) | Rename the session/thread |
publishHomeView(userId, view) | Publish a Home tab view for a user |
startTyping(threadId, status) | Set processing; custom text is legacy-only |
Add these to your Slack app manifest for Assistants API support:
oauth_config:
scopes:
bot:
- assistant:write
- chat:write
settings:
event_subscriptions:
bot_events:
- app_home_opened
- app_context_changed
- agent_session_stopped
- agent_session_title_changedWhen streaming in an assistant thread, attach Block Kit elements to the final message by wrapping the stream in a StreamingPlan and passing endWith:
import { StreamingPlan } from "chat";
await thread.post(
new StreamingPlan(textStream, {
endWith: [
{ type: "actions", elements: [{ type: "button", text: { type: "plain_text", text: "Retry" }, action_id: "retry" }] },
],
})
);handleOAuthCallback throws "Adapter not initialized"await bot.initialize() before handleOAuthCallback() in your callback route.const slackAdapter = bot.getAdapter("slack");
await bot.initialize();
await slackAdapter.handleOAuthCallback(request);SLACK_SIGNING_SECRET is correctwebhookVerifier, the error also surfaces when the verifier throws or returns a falsy valuecreateFileTools factory with approval-gated write tools and a read-only mode.See all guides and templates at chat-sdk.dev/resources.
If you use an AI coding agent such as OpenAI Codex, Claude Code, or Cursor, install the Chat SDK skill so it knows the SDK APIs, adapter patterns, and project conventions before writing code.
npx skills add vercel/chatThe skill references bundled documentation in node_modules/chat/docs, plus adapter guides and starter templates in the published package.
You can also install the Vercel Plugin for a broader agent toolkit — it includes the Chat SDK skill alongside specialist agents, agent slash commands, and more:
npx plugins add vercel/vercel-pluginThe plugin is optional; the skill alone is enough to build with Chat SDK.
For agent-readable documentation, see chat-sdk.dev/llms.txt (page index) or chat-sdk.dev/llms-full.txt (full text).
MIT
Estimated unpacked size across 36 packages.
8.8 MB
Includes dependencies.
4 direct · 2 outdated
4.45.0
4.45.0
^7.18.0
8.4.0
^2.0.5
3.2.0
4.45.0
4.45.0