Slack Bolt app that can also server web pages

I beat my head against this question for a while and was about to ask for help here. Then I figured it out and almost abandoned my question. Instead, let me be a good citizen and both ask it and answer it!

Say you have a Slack app built with Slack’s Bolt package, which I believe is Slack’s recommendation for Slack apps built nowadays (as of 2021). But you want the app to also serve web pages. Or maybe respond to other webhooks or whatever. Your app in Glitch is not strictly for responding to events from Slack, is the point.

So how do you make it do both?

Here is how:

First, include these dependencies in your package.json:

"@slack/bolt": "^3.8.1",
"express": "^4.17.2"

Then create a webpage, public/index.html, and then do the following in your app to create and start the server listening for events:

const express = require('express')
const { App, ExpressReceiver } = require("@slack/bolt")
const receiver = new ExpressReceiver({ 
  signingSecret: process.env.SLACK_SIGNING_SECRET
})
receiver.router.use(express.static('public'))
//receiver.router.use(express.json()) // if we wanted more than static pages
const app = new App({ token: process.env.SLACK_BOT_TOKEN, receiver })

;(async () => { 
  await app.start(process.env.PORT || 3000)
  console.log('App is running; listening for events from Slack / the web')
})()

Finally, you can add the code for your Slack app. For example, the following listens for people saying “ping” and replies with “pong”:

app.message(/^ping$/i, async ({ context, say }) => {
  await say("pong")
})

That’s it!

PS: I guess the cool kids use Fastify rather than Express these days. If anyone knows how to do this with Fastify, I’d love to see!

PPS: See also discussion in Slack’s GitHub: https://github.com/slackapi/bolt-js/issues/212

2 Likes

> PS: I guess the cool kids use Fastify rather than Express these days. If anyone knows how to do this with Fastify, I’d love to see!

I stopped using Express a couple of years ago, converted to Fastify and within a month or two converted it all to Hapi. https://hapi.dev Developers identify with some frameworks better than others but I found Fastify needlessly confusing and I am so glad I made the jump to Hapi.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.