# Answering web requests

Serve your own routes from a plugin, like a webhook from another service or a status page, by writing fetch() for the requests your bot receives.

Some plugins need a URL of their own, like a route that GitHub posts webhooks to or a status page. Without a way to answer those from the bot, you'd run a second web server beside it for a route or two.

A plugin can answer those requests itself. Give it a [`fetch()`](https://seedcord.org/docs/packages/core/latest/classes/plugin#fetch) method that takes a web `Request` and returns a `Response`, or `undefined` to pass the request on.

```ts title="src/plugins/Status.ts"
import { Plugin } from '@seedcord/gateway';

const STATUS = new URLPattern({ pathname: '/status' });

export class Status extends Plugin {
    public async init(): Promise<void> {}

    public override fetch(request: Request): Response | undefined {
        if (!STATUS.test(request.url)) return undefined;

        const guilds = this.core.bot.client.guilds.cache.size;
        return Response.json({ guilds });
    }
}
```

`Status` answers `/status` and returns `undefined` for every other path. seedcord doesn't route requests, so you match the path yourself. [`URLPattern`](https://developer.mozilla.org/en-US/docs/Web/API/URLPattern) is built into Node, Bun, and Workers, and `STATUS.test()` returns whether a URL fits the pattern.

## Which step answers

seedcord tries these steps in order, and the first one to return a `Response` answers the request:

{/* prettier-ignore-start */}

| step | gateway                                                                                                         | http                                                                                                            |
| ---- | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| 1    | the [health path](https://seedcord.org/guide/build/server/#the-health-check)                                    | the health path, on a server                                                                                    |
| 2    | each plugin's [`fetch()`](https://seedcord.org/docs/packages/core/latest/classes/plugin#fetch), in attach order | each plugin's [`fetch()`](https://seedcord.org/docs/packages/core/latest/classes/plugin#fetch), in attach order |
| 3    | a 404                                                                                                           | the interactions engine for a POST, a 404 for anything else                                                     |

{/* prettier-ignore-end */}

Keep your routes off the path that your interactions endpoint URL points at. If your `fetch()` answers there, Discord's POSTs never reach the interactions engine.

## Check the path before you await

On an http bot, every interaction passes through your `fetch()` first, and Discord gives the bot [three seconds](https://seedcord.org/guide/replying/) to answer it. An `await` before your path check uses up part of that time on every interaction. Check the path and the method, return `undefined` for anything that isn't yours, and await only after that.

```ts title="src/plugins/GithubHooks.ts"
const PUSH = new URLPattern({ pathname: '/github/:repo/push' });

export class GithubHooks extends Plugin {
    public async init(): Promise<void> {}

    public override async fetch(
        request: Request
    ): Promise<Response | undefined> {
        if (request.method !== 'POST') return undefined;
        const repo = PUSH.exec(request.url)?.pathname.groups.repo;
        if (!repo) return undefined;

        const body = await request.text();
        this.logger.info(`push to ${repo}, ${body.length} bytes`);
        return new Response(null, { status: 204 });
    }
}
```

The two `return undefined` lines run before the `await`. `:repo` in the pattern matches one part of the path, and `exec()` returns it under `pathname.groups`. You read `body` as text because [GitHub signs the exact payload](https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries) that it sends. Check the request's `X-Hub-Signature-256` header against `body` before you trust it because anyone can post to a public route.

## Reading the body

> **Warning**
>
> A request's body can only be read once. If you read it in `fetch()`, or call `getReader()` on it, and then return `undefined`, the plugins after yours can't read it. Neither can the interactions engine, which checks Discord's signature against those exact bytes. seedcord stops that request with an error:
>
> ```txt output
> [1241] GithubHooks at hooks read or locked the body of a request to /interactions without answering it. The steps after it can't read that body again. Check the path in fetch before you touch the body.
> ```

`GithubHooks` avoids it by reading the body only after both checks pass. To look at a body before you decide, read a copy with `await request.clone().text()`.

## When `fetch()` throws

seedcord logs the error on your plugin's logger, with the method and the path, and answers the request with a 500. The plugins after yours and the interactions engine never get that request.

On an http bot every interaction gets a 500 if your `fetch()` throws before its path check. Make sure you always do the path check first.

## Linking to your route

Sometimes your plugin has to tell someone where one of its routes is, like the webhook URL that you paste into GitHub. For that, it needs the address people reach the bot at. Read it from [`core.url`](https://seedcord.org/docs/packages/core/latest/interfaces/core-base#url):

```ts title="src/plugins/GithubHooks.ts"
export class GithubHooks extends Plugin {
    public async init(): Promise<void> {
        const url = new URL('github/seedcord/push', this.core.url);
        this.logger.info(`add this webhook in GitHub: ${url.href}`);
    }
}
```

`core.url` always ends in a slash. For a bot at `https://example.com/bot`, `GithubHooks` logs `https://example.com/bot/github/seedcord/push`. The bot's author sets that address as [`server.url`](https://seedcord.org/guide/build/server/#your-bots-address). If they haven't, `core.url` throws an error that tells them the line to add, and reading it in `init()` makes that happen at startup.

## Where requests arrive

A bot on Node or Bun serves web requests on its [web server](https://seedcord.org/guide/build/server/#the-web-server), which listens on port 3000 unless the bot sets `server.port`. A bot inside [your own server](https://seedcord.org/guide/build/embed/) gets whatever paths your server passes to `bot.fetch()`.

Set up whatever your `fetch()` reads in `init()`. Every `init()` finishes before the first request reaches `fetch()` unless you moved it to the Ready phase. A `ready()` can still be running when a request arrives. [The lifecycle page](https://seedcord.org/guide/plugins/lifecycle/#where-each-one-runs) has the full order.

> **Cloudflare Workers only**
>
> Once a plugin has `fetch()`, the first request of any kind starts the bot in its isolate so the plugin can answer it. A crawler's request counts too. Without a plugin that has `fetch()`, the Worker answers anything besides a POST with a 404 before the bot starts.
