A framework for building Slack apps, fast.
npx @tessl/cli install tessl/npm-slack--bolt@4.4.00
# Slack Bolt JavaScript SDK
1
2
Slack Bolt is a comprehensive JavaScript/TypeScript framework specifically designed for building Slack applications with modern platform features. It offers a high-level abstraction for handling Slack's Events API, interactive components, slash commands, shortcuts, and OAuth flows through an intuitive event-driven architecture.
3
4
## Package Information
5
6
- **Package Name**: @slack/bolt
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @slack/bolt`
10
11
## Core Imports
12
13
```typescript
14
import { App } from "@slack/bolt";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { App } = require("@slack/bolt");
21
```
22
23
## Basic Usage
24
25
```typescript
26
import { App } from "@slack/bolt";
27
28
// Initialize your app with your bot token and signing secret
29
const app = new App({
30
token: process.env.SLACK_BOT_TOKEN,
31
signingSecret: process.env.SLACK_SIGNING_SECRET,
32
});
33
34
// Listen for a slash command invocation
35
app.command("/hello", async ({ command, ack, respond }) => {
36
// Acknowledge the command request
37
await ack();
38
39
await respond(`Hey there <@${command.user_id}>!`);
40
});
41
42
// Listen for a message containing "hello"
43
app.message("hello", async ({ message, say }) => {
44
await say(`Hey there <@${message.user}>!`);
45
});
46
47
// Start your app
48
(async () => {
49
await app.start(3000);
50
console.log("⚡️ Bolt app is running!");
51
})();
52
```
53
54
## Architecture
55
56
Slack Bolt is built around several key components:
57
58
- **App Class**: Core application instance that manages listeners, middleware, and request handling
59
- **Receivers**: HTTP and WebSocket adapters for different deployment scenarios (Express, Lambda, Socket Mode)
60
- **Middleware System**: Extensible request processing pipeline with built-in filtering and matching
61
- **Context System**: Request-scoped data management with bot tokens, user information, and custom properties
62
- **Type Safety**: Complete TypeScript definitions for all Slack events, payloads, and API responses
63
64
## Capabilities
65
66
### Core Application
67
68
Main App class for building Slack applications with comprehensive event handling, middleware support, and flexible deployment options.
69
70
```typescript { .api }
71
class App {
72
constructor(options?: AppOptions);
73
74
// Properties
75
readonly client: WebClient;
76
readonly logger: Logger;
77
get webClientOptions(): WebClientOptions;
78
79
// Initialization
80
init(): Promise<void>;
81
82
// Event listeners
83
event<EventType extends string>(
84
eventType: EventType,
85
...listeners: Middleware<SlackEventMiddlewareArgs<EventType>>[]
86
): void;
87
88
message(
89
pattern?: string | RegExp,
90
...listeners: Middleware<SlackEventMiddlewareArgs<'message'>>[]
91
): void;
92
93
action<ActionId extends string>(
94
actionId: ActionId,
95
...listeners: Middleware<SlackActionMiddlewareArgs>[]
96
): void;
97
98
command(
99
commandName: string,
100
...listeners: Middleware<SlackCommandMiddlewareArgs>[]
101
): void;
102
103
shortcut<CallbackId extends string>(
104
callbackId: CallbackId,
105
...listeners: Middleware<SlackShortcutMiddlewareArgs>[]
106
): void;
107
108
view<CallbackId extends string>(
109
callbackId: CallbackId,
110
...listeners: Middleware<SlackViewMiddlewareArgs>[]
111
): void;
112
113
options<Source extends OptionsSource>(
114
actionId: string | RegExp | OptionsConstraints<Source>,
115
...listeners: Middleware<SlackOptionsMiddlewareArgs<Source>>[]
116
): void;
117
118
// Advanced features
119
assistant(assistant: Assistant): this;
120
step(workflowStep: WorkflowStep): this;
121
function(
122
callbackId: string,
123
...listeners: Middleware<SlackCustomFunctionMiddlewareArgs>[]
124
): this;
125
126
// Global middleware and error handling
127
use(...middlewares: Middleware<AnyMiddlewareArgs>[]): void;
128
error(errorHandler: (error: CodedError) => Promise<void>): void;
129
130
// Application lifecycle
131
start(port?: number | (() => void), ...args: any[]): Promise<unknown>;
132
stop(): Promise<unknown>;
133
}
134
135
interface AppOptions {
136
/** Bot token starting with xoxb- */
137
token?: string;
138
/** App-level token starting with xapp- (required for Socket Mode) */
139
appToken?: string;
140
/** Signing secret for request verification */
141
signingSecret?: string | (() => PromiseLike<string>);
142
/** Custom receiver for handling HTTP requests */
143
receiver?: Receiver;
144
/** Custom authorization function */
145
authorize?: Authorize<boolean>;
146
/** Custom logger instance */
147
logger?: Logger;
148
/** Log level for built-in logger */
149
logLevel?: LogLevel;
150
/** Ignore events from the bot itself */
151
ignoreSelf?: boolean;
152
/** Web API client options */
153
clientOptions?: WebClientOptions;
154
/** Conversation state store */
155
convoStore?: ConversationStore | false;
156
/** Enable Socket Mode connection */
157
socketMode?: boolean;
158
/** Enable developer mode with additional logging */
159
developerMode?: boolean;
160
/** Enable token verification */
161
tokenVerificationEnabled?: boolean;
162
/** Defer app initialization until init() is called */
163
deferInitialization?: boolean;
164
/** Enable extended error handler format */
165
extendedErrorHandler?: boolean;
166
/** Attach function execution token to context */
167
attachFunctionToken?: boolean;
168
/** HTTP server port */
169
port?: number;
170
/** HTTP server endpoints configuration */
171
endpoints?: string | { [endpointType: string]: string };
172
/** Process events before sending HTTP response */
173
processBeforeResponse?: boolean;
174
/** Enable request signature verification */
175
signatureVerification?: boolean;
176
/** OAuth client ID */
177
clientId?: string;
178
/** OAuth client secret */
179
clientSecret?: string;
180
/** State parameter secret for OAuth */
181
stateSecret?: string;
182
/** OAuth redirect URI */
183
redirectUri?: string;
184
/** Installation store for OAuth */
185
installationStore?: InstallationStore;
186
/** OAuth permission scopes */
187
scopes?: InstallURLOptions['scopes'];
188
/** Installation provider options */
189
installerOptions?: InstallerOptions;
190
/** Custom HTTP routes */
191
customRoutes?: CustomRoute[];
192
/** HTTP agent for outgoing requests */
193
agent?: Agent;
194
/** TLS options for HTTPS */
195
clientTls?: Pick<SecureContextOptions, 'pfx' | 'key' | 'passphrase' | 'cert' | 'ca'>;
196
/** Bot ID for the application */
197
botId?: string;
198
/** Bot user ID for the application */
199
botUserId?: string;
200
/** Custom properties extractor function */
201
customPropertiesExtractor?: (request: any) => StringIndexed;
202
}
203
```
204
205
[Core Application](./core-application.md)
206
207
### Request Receivers
208
209
HTTP and WebSocket receivers for different deployment scenarios including traditional servers, serverless functions, and Socket Mode connections.
210
211
```typescript { .api }
212
class ExpressReceiver {
213
constructor(options: ExpressReceiverOptions);
214
}
215
216
class SocketModeReceiver {
217
constructor(options: SocketModeReceiverOptions);
218
}
219
220
class HTTPReceiver {
221
constructor(options: HTTPReceiverOptions);
222
}
223
224
class AwsLambdaReceiver {
225
constructor(options: AwsLambdaReceiverOptions);
226
}
227
228
interface ExpressReceiverOptions {
229
signingSecret: string;
230
logger?: Logger;
231
logLevel?: LogLevel;
232
endpoints?: string | { [key: string]: string };
233
processBeforeResponse?: boolean;
234
clientId?: string;
235
clientSecret?: string;
236
stateSecret?: string;
237
scopes?: string[];
238
installerOptions?: InstallProviderOptions;
239
}
240
```
241
242
[Request Receivers](./receivers.md)
243
244
### Built-in Middleware
245
246
Filtering and matching middleware for event processing, message patterns, and request routing.
247
248
```typescript { .api }
249
// Event filtering middleware
250
const onlyActions: Middleware<AnyMiddlewareArgs>;
251
const onlyCommands: Middleware<AnyMiddlewareArgs>;
252
const onlyEvents: Middleware<AnyMiddlewareArgs>;
253
const onlyShortcuts: Middleware<AnyMiddlewareArgs>;
254
255
// Matching middleware
256
function matchMessage(pattern: string | RegExp): Middleware<SlackEventMiddlewareArgs<'message'>>;
257
function matchCommandName(pattern: string | RegExp): Middleware<SlackCommandMiddlewareArgs>;
258
function matchConstraints<T>(constraints: ActionConstraints): Middleware<SlackActionMiddlewareArgs>;
259
260
// Utility middleware
261
const ignoreSelf: Middleware<AnyMiddlewareArgs>;
262
```
263
264
[Built-in Middleware](./middleware.md)
265
266
### Advanced Features
267
268
AI Assistant integration and workflow step handling for complex Slack application scenarios.
269
270
```typescript { .api }
271
class Assistant {
272
constructor(config: AssistantConfig);
273
}
274
275
interface AssistantConfig {
276
threadContextStore?: AssistantThreadContextStore;
277
threadStarted: AssistantThreadStartedMiddleware | AssistantThreadStartedMiddleware[];
278
threadContextChanged?: AssistantThreadContextChangedMiddleware | AssistantThreadContextChangedMiddleware[];
279
userMessage: AssistantUserMessageMiddleware | AssistantUserMessageMiddleware[];
280
}
281
282
class WorkflowStep {
283
constructor(config: WorkflowStepConfig);
284
}
285
```
286
287
[Advanced Features](./advanced-features.md)
288
289
### Custom Functions
290
291
Slack custom functions for workflow and automation scenarios.
292
293
```typescript { .api }
294
class CustomFunction {
295
constructor(
296
callbackId: string,
297
listeners: Middleware<SlackCustomFunctionMiddlewareArgs>[]
298
);
299
300
getListeners(): Middleware<AnyMiddlewareArgs>[];
301
}
302
303
type FunctionCompleteFn = (
304
params?: FunctionCompleteArguments
305
) => Promise<FunctionsCompleteSuccessResponse>;
306
307
type FunctionFailFn = (
308
params: FunctionFailArguments
309
) => Promise<FunctionsCompleteErrorResponse>;
310
311
function createFunctionComplete(
312
context: Context,
313
client: WebClient
314
): FunctionCompleteFn;
315
316
function createFunctionFail(
317
context: Context,
318
client: WebClient
319
): FunctionFailFn;
320
321
interface SlackCustomFunctionMiddlewareArgs extends AllMiddlewareArgs {
322
complete: FunctionCompleteFn;
323
fail: FunctionFailFn;
324
inputs: FunctionInputs;
325
}
326
```
327
328
### Conversation Store
329
330
State management for multi-turn conversations and workflow tracking.
331
332
```typescript { .api }
333
interface ConversationStore<ConversationState = any> {
334
set(
335
conversationId: string,
336
value: ConversationState,
337
expiresAt?: number
338
): Promise<unknown>;
339
340
get(conversationId: string): Promise<ConversationState>;
341
}
342
343
class MemoryStore<ConversationState = any>
344
implements ConversationStore<ConversationState> {
345
346
set(
347
conversationId: string,
348
value: ConversationState,
349
expiresAt?: number
350
): Promise<void>;
351
352
get(conversationId: string): Promise<ConversationState>;
353
}
354
355
function conversationContext<ConversationState = any>(
356
store: ConversationStore<ConversationState>
357
): Middleware<AnyMiddlewareArgs>;
358
```
359
360
### Request Verification
361
362
Request signature verification and authentication utilities for secure Slack app development.
363
364
```typescript { .api }
365
function verifySlackRequest(options: RequestVerificationOptions): boolean;
366
function isValidSlackRequest(options: RequestVerificationOptions): boolean;
367
368
interface RequestVerificationOptions {
369
signingSecret: string;
370
body: string;
371
headers: { [key: string]: string | string[] | undefined };
372
}
373
```
374
375
[Request Verification](./request-verification.md)
376
377
### Authorization
378
379
OAuth and authorization interfaces for app installation and token management.
380
381
```typescript { .api }
382
type Authorize<IsEnterpriseInstall extends boolean = false> = (
383
source: AuthorizeSourceData<IsEnterpriseInstall>,
384
body?: AnyMiddlewareArgs['body']
385
) => Promise<AuthorizeResult>;
386
387
interface AuthorizeSourceData<IsEnterpriseInstall extends boolean = false> {
388
teamId: IsEnterpriseInstall extends true ? string | undefined : string;
389
enterpriseId: IsEnterpriseInstall extends true ? string : string | undefined;
390
userId?: string;
391
conversationId?: string;
392
isEnterpriseInstall: IsEnterpriseInstall;
393
}
394
395
interface AuthorizeResult {
396
botToken?: string;
397
userToken?: string;
398
botId?: string;
399
botUserId?: string;
400
userId?: string;
401
teamId?: string;
402
enterpriseId?: string;
403
[key: string]: any;
404
}
405
```
406
407
## Types
408
409
### Core Types
410
411
```typescript { .api }
412
// Middleware system
413
type Middleware<Args, CustomContext = StringIndexed> = (
414
args: Args & AllMiddlewareArgs<CustomContext>
415
) => Promise<void>;
416
417
interface AllMiddlewareArgs<CustomContext = StringIndexed> {
418
context: Context & CustomContext;
419
logger: Logger;
420
client: WebClient;
421
next: NextFn;
422
}
423
424
// Request context
425
interface Context extends StringIndexed {
426
botToken?: string;
427
userToken?: string;
428
botId?: string;
429
botUserId?: string;
430
userId?: string;
431
teamId?: string;
432
enterpriseId?: string;
433
isEnterpriseInstall: boolean;
434
functionBotAccessToken?: string;
435
functionExecutionId?: string;
436
functionInputs?: FunctionInputs;
437
retryNum?: number;
438
retryReason?: string;
439
}
440
441
// Utility functions
442
type AckFn = () => Promise<void>;
443
type SayFn = (message: string | SayArguments) => Promise<SayResult>;
444
type RespondFn = (response: string | RespondArguments) => Promise<void>;
445
type NextFn = () => Promise<void>;
446
```
447
448
### Event-Specific Types
449
450
```typescript { .api }
451
// Event middleware arguments
452
type SlackEventMiddlewareArgs<EventType extends string = string> = {
453
event: KnownEventFromType<EventType>;
454
body: EnvelopedEvent<KnownEventFromType<EventType>>;
455
payload: EnvelopedEvent<KnownEventFromType<EventType>>;
456
message: EventType extends 'message' ? GenericMessageEvent : never;
457
} & AllMiddlewareArgs;
458
459
// Action middleware arguments
460
type SlackActionMiddlewareArgs = {
461
action: SlackAction;
462
body: SlackActionBody;
463
payload: SlackAction;
464
} & AllMiddlewareArgs;
465
466
// Command middleware arguments
467
type SlackCommandMiddlewareArgs = {
468
command: SlashCommand;
469
body: SlashCommand;
470
payload: SlashCommand;
471
} & AllMiddlewareArgs;
472
473
// View middleware arguments
474
type SlackViewMiddlewareArgs = {
475
view: SlackViewAction;
476
body: SlackViewBody;
477
payload: SlackViewAction;
478
} & AllMiddlewareArgs;
479
480
// Options middleware arguments
481
type SlackOptionsMiddlewareArgs<Source extends OptionsSource = OptionsSource> = {
482
options: KnownOptionsPayloadFromType<Source>;
483
body: KnownOptionsPayloadFromType<Source>;
484
payload: KnownOptionsPayloadFromType<Source>;
485
} & AllMiddlewareArgs;
486
487
// Shortcut middleware arguments
488
type SlackShortcutMiddlewareArgs = {
489
shortcut: SlackShortcut;
490
body: SlackShortcut;
491
payload: SlackShortcut;
492
} & AllMiddlewareArgs;
493
```
494
495
### Error Types
496
497
```typescript { .api }
498
interface CodedError extends Error {
499
code: string;
500
original?: Error;
501
originals?: Error[];
502
missingProperty?: string;
503
}
504
505
enum ErrorCode {
506
AppInitializationError = 'slack_bolt_app_initialization_error',
507
AssistantInitializationError = 'slack_bolt_assistant_initialization_error',
508
AssistantMissingPropertyError = 'slack_bolt_assistant_missing_property_error',
509
AuthorizationError = 'slack_bolt_authorization_error',
510
ContextMissingPropertyError = 'slack_bolt_context_missing_property_error',
511
InvalidCustomPropertyError = 'slack_bolt_context_invalid_custom_property_error',
512
CustomRouteInitializationError = 'slack_bolt_custom_route_initialization_error',
513
ReceiverMultipleAckError = 'slack_bolt_receiver_ack_multiple_error',
514
ReceiverAuthenticityError = 'slack_bolt_receiver_authenticity_error',
515
ReceiverInconsistentStateError = 'slack_bolt_receiver_inconsistent_state_error',
516
MultipleListenerError = 'slack_bolt_multiple_listener_error',
517
HTTPReceiverDeferredRequestError = 'slack_bolt_http_receiver_deferred_request_error',
518
UnknownError = 'slack_bolt_unknown_error',
519
WorkflowStepInitializationError = 'slack_bolt_workflow_step_initialization_error',
520
CustomFunctionInitializationError = 'slack_bolt_custom_function_initialization_error',
521
CustomFunctionCompleteSuccessError = 'slack_bolt_custom_function_complete_success_error',
522
CustomFunctionCompleteFailError = 'slack_bolt_custom_function_complete_fail_error'
523
}
524
525
// Error Classes
526
class AppInitializationError extends Error implements CodedError {
527
code: ErrorCode.AppInitializationError;
528
original?: Error;
529
}
530
531
class AssistantInitializationError extends Error implements CodedError {
532
code: ErrorCode.AssistantInitializationError;
533
original?: Error;
534
}
535
536
class AssistantMissingPropertyError extends Error implements CodedError {
537
code: ErrorCode.AssistantMissingPropertyError;
538
missingProperty?: string;
539
}
540
541
class AuthorizationError extends Error implements CodedError {
542
code: ErrorCode.AuthorizationError;
543
original?: Error;
544
}
545
546
class ContextMissingPropertyError extends Error implements CodedError {
547
code: ErrorCode.ContextMissingPropertyError;
548
missingProperty?: string;
549
}
550
551
class InvalidCustomPropertyError extends Error implements CodedError {
552
code: ErrorCode.InvalidCustomPropertyError;
553
missingProperty?: string;
554
}
555
556
class CustomRouteInitializationError extends Error implements CodedError {
557
code: ErrorCode.CustomRouteInitializationError;
558
original?: Error;
559
}
560
561
class ReceiverMultipleAckError extends Error implements CodedError {
562
code: ErrorCode.ReceiverMultipleAckError;
563
}
564
565
class ReceiverAuthenticityError extends Error implements CodedError {
566
code: ErrorCode.ReceiverAuthenticityError;
567
}
568
569
class ReceiverInconsistentStateError extends Error implements CodedError {
570
code: ErrorCode.ReceiverInconsistentStateError;
571
}
572
573
class HTTPReceiverDeferredRequestError extends Error implements CodedError {
574
code: ErrorCode.HTTPReceiverDeferredRequestError;
575
}
576
577
class MultipleListenerError extends Error implements CodedError {
578
code: ErrorCode.MultipleListenerError;
579
originals?: Error[];
580
}
581
582
class UnknownError extends Error implements CodedError {
583
code: ErrorCode.UnknownError;
584
original?: Error;
585
}
586
587
class WorkflowStepInitializationError extends Error implements CodedError {
588
code: ErrorCode.WorkflowStepInitializationError;
589
original?: Error;
590
}
591
592
class CustomFunctionInitializationError extends Error implements CodedError {
593
code: ErrorCode.CustomFunctionInitializationError;
594
original?: Error;
595
}
596
597
class CustomFunctionCompleteSuccessError extends Error implements CodedError {
598
code: ErrorCode.CustomFunctionCompleteSuccessError;
599
original?: Error;
600
}
601
602
class CustomFunctionCompleteFailError extends Error implements CodedError {
603
code: ErrorCode.CustomFunctionCompleteFailError;
604
original?: Error;
605
}
606
```