5. Announcements from outside

HTTP routes for scripts and webhooks, secrets in environment variables.

2 MIN READView Markdown ↗

Not every caller is your app. A script, a CI job or a payment provider speaks plain HTTP. In this chapter, anyone with a token can post an announcement into the chat with curl.

The backend#

Add type Routes to the import, and export routes below setTyping:

TypeScript
import { ApiError, caller, event, files, online, type Routes } from 'arkapi/server'
TypeScript
export const routes: Routes = {
  'POST /announce': async (req) => {
    const token = process.env.ANNOUNCE_TOKEN
    if (!token || req.headers.get('Authorization') !== `Bearer ${token}`) {
      throw new ApiError('UNAUTHORIZED', 'Wrong token')
    }
    save('announcement', await req.text(), null)
    return new Response('ok')
  },
}
  • Keys are METHOD /path; a path like /items/:id passes id in a second params argument. The handler gets a standard Request and returns a Response.
  • The URL is the backend's address plus /http, so this one is http://localhost:3000/http/announce for now.
  • The message is saved with the device announcement, which has no row in people. That is why getMessages falls back to the name Announcement.
  • A route refreshes live queries like a mutation, so the announcement appears on every screen.

Try it#

The token comes from an environment variable. Stop watch, and start it again with one:

Terminal
ANNOUNCE_TOKEN=pizza bunx arkapi watch
Terminal
curl -X POST http://localhost:3000/http/announce \
  -H 'Authorization: Bearer pizza' -d 'Pizza in the kitchen'

The app shows the announcement from "Announcement". With a wrong token the answer is 401 and nothing is saved. On the hosted service you set the token with bunx arkapi env set, in the last chapter.

Next: clean up every hour.

Tab to navigate results · Enter to open · Esc to close