I've developed a Slack app that monitors messages sent to a specific channel. When a message is detected, it triggers an event to a URL (route) hosted on my frontend system (Next.js), which then sends a POST request to the backend to retrieve a response. Once the response is obtained, it's sent back to Slack as a message.
The code in the route looks like this:
import { WebClient } from '@slack/web-api'
const web = new WebClient(process.env.SLACK_TOKEN)
export async function POST(req: Request) {
const data = await req.json()
console.log(data)
if (data.type === 'url_verification') {
return Response.json({ challenge: data.challenge })
}
if (
!data.event.thread_ts &&
!data.event.parent_user_id &&
data.event.type === 'message' &&
data.type === 'event_callback' &&
data.event.channel === 'C06GGJVRMCK'
) {
const response = await fetch(process.env.AWS_BACKEND_ENDPOINT || '', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
message: [
{
role: 'user',
content: data.event.text
}
]
})
}
)
const json = await response.json()
await web.chat.postMessage({
text: json.data.content,
thread_ts: data.event.ts,
channel: data.event.channel
})
return new Response(data.challenge, {
status: 200
})
}
return new Response('Ok', {
status: 200
})
}
However, I've noticed that multiple submissions occur every time a single message is sent to the channel. Consequently, this leads to multiple repeated responses from the backend, which are also sent back to Slack. For every single message that is sent, I receive approximately 3 to 4 POST requests in the backend, resulting in the delivery of 3 to 4 response messages on Slack.
I'm seeking advice and suggestions on how to prevent these multiple POST requests triggered by Slack messages and ensure that only one response is sent for each message received.
Any insights or alternative approaches to handle this situation would be greatly appreciated. Thank you in advance for your assistance!
I tried to send an early response with status 200 'OK' but I still get multiple events.
Expected Outcome:
Ideally, I expected to implement a solution that would effectively prevent multiple POST requests from being triggered by a single Slack message. This would ensure that only POST request is sent to the Backend and also one response is sent back to Slack for each incoming message, thereby eliminating redundancy and improving the user experience.
So the solution that I found was using
waitUntil()from RequestContext (vercel/edge), which allowed me to run code after response submission & execute the fetch from backend and the postMessage to Slack on another route.And on
process-events.tsI have this:Note: I only get one submission from Slack, since the first route sends immediately the 200 OK reply.