# Publishing to the edge

Put a changed page at the edge without a release, keep your redirects at bunny.net and answer searches there, so your container can sleep.


The [edge cache](/running/edge-cache) keeps the public pages of your application at bunny.net, and a release puts them there. Between releases a page changes when someone saves it in your CMS, and until now the edge kept the old one until its cache time ran out, or until the next deploy. With `edge.publish` your application tells Brewless which addresses changed, and Brewless empties them at the edge and asks them again, a minute later and without a release. The same setting lets your application keep its redirect table at the edge, and `edge.search` lets the edge answer searches of your pages. Each of these is a request your container no longer gets.

Your container was awake anyway when it publishes: somebody just saved something in it.

## Switching it on

```yaml
environments:
  production:
    edge:
      keep_pages: true
      publish: true
```

At the next deploy every container of the environment gets three variables: `BREWLESS_EDGE_KEY`, a key of this environment that Brewless makes once and keeps, `BREWLESS_API_URL` and `BREWLESS_ENVIRONMENT`. `brewless/laravel` reads them. Without them, as on your own machine or in your tests, publishing does nothing at all.

`keep_pages` is not needed to publish pages, but it is for redirects and search, and with it a published page is kept in your storage zone as well.

## Publishing a page

```php
use Brewless\Laravel\Facades\Edge;

Edge::publish(['/blog/my-post', '/blog', '/sitemap.xml'], 'entry.saved');
```

Name every address the change shows on: the page itself, the lists it appears in, the sitemap. An address is a path (`/blog/my-post`), which is published on every domain of the environment, or a full `https://` address on one of its own domains. A query string is not published: the edge keeps such an address apart, and it is your container's.

`Edge::publish()` hands the work to your queue, after the database transaction it was called in is committed, so the page Brewless asks for is the saved one. When Brewless cannot be reached the job tries again later, five times in all; your site keeps serving the page it had in the meantime. On the command line, or in a release command:

```bash
php artisan brewless:publish /blog/my-post /blog --reason=entry.saved
```

For every address Brewless then:

1. takes the page out of your storage zone, with `keep_pages`, so the edge cannot hand out the old one in the moment between the next two steps;
2. empties the address at the edge, and its Markdown (`/blog/my-post.md`), and waits until bunny.net says it is done;
3. asks the address once through the edge, without a cookie, as the [warm-up](/running/edge-cache#warmed-after-every-release) does. Your container answers and the edge keeps the new page;
4. keeps that page in your storage zone, with `keep_pages`, under [the same rules as a release](/running/edge-cache#what-is-never-kept): a page that sets a cookie or is not `public` never goes in.

A page that now answers 404, 410 or a redirect is emptied at the edge and taken out of the zone. So publish the address of a page you deleted, too. bunny.net does not empty every edge server at the same moment; an answer that still comes out of the edge's own cache is asked again a few times, and is never kept.

Addresses that come in while a publish runs wait for the next one: a CMS that saves ten times in a minute starts one or two publishes, not ten. One publish takes at most 50 addresses; the rest go on in the next straight after.

### Recipe: an Eloquent model

The two recipes below say which addresses changed, and nothing more. Your Antlers and Blade templates stay as they are: your container renders the page, the edge keeps it.


An observer publishes the post, the list it is in and the sitemap whenever a published post is saved or deleted:

```php app/Observers/PublishPostToEdge.php
namespace App\Observers;

use App\Models\Post;
use Brewless\Laravel\Facades\Edge;

class PublishPostToEdge
{
    public function saved(Post $post): void
    {
        // A draft that was a draft before is on no page: nothing at the edge changed.
        if (! $post->published && ! $post->getOriginal('published')) {
            return;
        }

        $paths = [route('posts.show', $post, false), route('posts.index', absolute: false), '/sitemap.xml'];

        // A new slug leaves the old address behind: publish it too, so the edge lets it go.
        if ($post->wasChanged('slug')) {
            $paths[] = route('posts.show', $post->getOriginal('slug'), false);
        }

        Edge::publish($paths, 'post.saved');
    }

    public function deleted(Post $post): void
    {
        if ($post->getOriginal('published')) {
            Edge::publish([route('posts.show', $post, false), route('posts.index', absolute: false), '/sitemap.xml'], 'post.deleted');
        }
    }
}
```

```php app/Models/Post.php
use App\Observers\PublishPostToEdge;
use Illuminate\Database\Eloquent\Attributes\ObservedBy;

#[ObservedBy(PublishPostToEdge::class)]
class Post extends Model
```

A draft publishes nothing. A post taken back to draft, or deleted, is published once more: your container answers 404 and the edge lets the page go, and the list is asked again without it. `false` in `route()` gives the path without the domain, so the post is published on every domain of the environment.

### Recipe: Statamic

One subscriber listens to what Statamic tells about its content. Statamic 6 sends these events:

| Event | What is published |
| --- | --- |
| `EntrySaved` | The entry, the page its collection is mounted on, `/` and `/sitemap.xml`. Statamic sends it once for every localization it saves. |
| `EntryDeleted` | The same, for a published entry. |
| `EntryScheduleReached` | The same, when the date of a scheduled entry comes. |
| `TermSaved`, `TermDeleted` | The term in every site, its taxonomy page and `/sitemap.xml`. |
| `GlobalVariablesSaved`, `NavTreeSaved`, `CollectionTreeSaved` | Everything: globals and a navigation show on every page, and a new order of a collection changes its lists and addresses. |

```php app/Listeners/PublishContentToEdge.php
namespace App\Listeners;

use Brewless\Laravel\Facades\Edge;
use Statamic\Contracts\Entries\Entry as EntryContract;
use Statamic\Events\CollectionTreeSaved;
use Statamic\Events\EntryDeleted;
use Statamic\Events\EntrySaved;
use Statamic\Events\EntryScheduleReached;
use Statamic\Events\GlobalVariablesSaved;
use Statamic\Events\NavTreeSaved;
use Statamic\Events\TermDeleted;
use Statamic\Events\TermSaved;
use Statamic\Facades\Entry;
use Statamic\Facades\Taxonomy;

class PublishContentToEdge
{
    /**
     * @return array<class-string, string>
     */
    public function subscribe(): array
    {
        return [
            EntrySaved::class => 'entrySaved',
            EntryDeleted::class => 'entryDeleted',
            EntryScheduleReached::class => 'entryScheduleReached',
            TermSaved::class => 'termChanged',
            TermDeleted::class => 'termChanged',
            GlobalVariablesSaved::class => 'everything',
            NavTreeSaved::class => 'everything',
            CollectionTreeSaved::class => 'everything',
        ];
    }

    /** Statamic sends this once for every localization it saved. */
    public function entrySaved(EntrySaved $event): void
    {
        $entry = $event->entry;

        // A draft that was a draft before is on no page: nothing at the edge changed.
        if (! $entry->published() && ! $entry->getOriginal('published')) {
            return;
        }

        Edge::publish($this->entryPaths($entry), 'entry.saved');
    }

    public function entryDeleted(EntryDeleted $event): void
    {
        if ($event->entry->published()) {
            Edge::publish($this->entryPaths($event->entry), 'entry.deleted');
        }
    }

    /** A scheduled entry whose date has come: it is on the site from now on. */
    public function entryScheduleReached(EntryScheduleReached $event): void
    {
        Edge::publish($this->entryPaths($event->entry), 'entry.scheduled');
    }

    public function termChanged(TermSaved|TermDeleted $event): void
    {
        $term = $event->term;

        Edge::publish([
            ...$term->localizations()->map->urlWithoutRedirect()->all(),
            $term->taxonomy()->urlWithoutRedirect(),
            '/sitemap.xml',
        ], 'term.saved');
    }

    /** Globals, a navigation and the order of a collection show on every page: publish them all. */
    public function everything(): void
    {
        $entries = Entry::query()->whereStatus('published')->get()->map->urlWithoutRedirect();
        $taxonomies = Taxonomy::all()->flatMap(fn ($taxonomy) => [
            $taxonomy->urlWithoutRedirect(),
            ...$taxonomy->queryTerms()->get()->map->urlWithoutRedirect(),
        ]);

        Edge::publish([...$entries, ...$taxonomies, '/sitemap.xml'], 'statamic.everything');
    }

    /**
     * The entry, the page its collection is mounted on, the home page and the sitemap.
     *
     * @return list<string|null>
     */
    private function entryPaths(EntryContract $entry): array
    {
        return [
            $entry->urlWithoutRedirect(),
            $entry->collection()->mount()?->in($entry->locale())?->urlWithoutRedirect(),
            '/',
            '/sitemap.xml',
        ];
    }
}
```

Register it, and publish everything once a day as a safety net for whatever the events missed:

```php app/Providers/AppServiceProvider.php
use App\Listeners\PublishContentToEdge;
use Illuminate\Support\Facades\Event;

public function boot(): void
{
    Event::subscribe(PublishContentToEdge::class);
}
```

```php routes/console.php
use App\Listeners\PublishContentToEdge;
use Illuminate\Support\Facades\Schedule;

Schedule::call(fn () => resolve(PublishContentToEdge::class)->everything())
    ->name('publish-everything-to-the-edge')
    ->dailyAt('05:00');
```

`urlWithoutRedirect()` is the entry's own address: `url()` gives the target of an entry that redirects. An address that comes out `null`, such as an entry in a collection without a route, is skipped.

A few things to know about Statamic:

- **Drafts.** A draft that was a draft before publishes nothing. Statamic knows what an entry was before the save only when its Stache cache store hands out copies, as the `file`, `database` and `redis` stores do. The `array` store hands out the object itself, and then an entry taken back to draft is not published. In your tests, set `statamic.stache.cache_store` to `file`.
- **Scheduled entries.** `EntryScheduleReached` comes from a job that Statamic puts in your schedule to run every minute, as long as `statamic.system.handle_scheduled_entries` is on, which it is by default. Brewless then calls your worker every minute, and it never sleeps (see [How the worker is called](/running/queues-and-schedule#how-the-worker-is-called)). When a post may appear a few hours late, switch it off with `STATAMIC_HANDLE_SCHEDULED_ENTRIES: false` under `variables` in `brewless.yml`. The daily run then publishes it the next morning.
- **Everything is many addresses.** The daily run, globals and a navigation publish every published entry and term. Brewless takes 50 addresses per publish and goes on with the next straight after, so a large site takes a while; your site serves the pages it had in the meantime.

### A page at a set moment

Outside Statamic, a page that should change at a set moment, such as a post planned for tomorrow morning, is published by a scheduled task that runs once a day around that moment. Do not publish on a schedule every few minutes: a schedule wakes a container each time it runs, which is what this is meant to avoid.

### In your tests

```php
Edge::fake();

// ... save a post ...

Edge::assertPublished('/blog/my-post');
```

## Redirects at the edge

A site that moved keeps a table of old addresses, and every crawler that still knows them wakes your container for a redirect. Put the table at the edge instead:

```php
Edge::redirects([
    '/old-page' => '/new-page',
    ['from' => '/docs/*', 'to' => 'https://docs.example.com/', 'status' => 308],
]);
```

Or keep it in a file in your repository and send it with every release:

```csv redirects.csv
/old-page,/new-page,301
/docs/*,https://docs.example.com/,308
```

```yaml
release:
  - migrate --force
  - brewless:redirects --from=redirects.csv
```

The whole table replaces the one before; an empty one (`brewless:redirects --clear`) removes them all. The release that turns on `edge.publish` and `edge.keep_pages` may already send it: while its release commands run, Brewless goes by the file of that release as well as by the one that is live. A command that is refused stops the release and says why. Brewless keeps it in your storage zone, and the edge script answers it when the edge misses, before it looks for a page:

- An exact `from` wins; a path with a slash at the end finds the rule without it.
- A `from` that ends in `*` is a prefix. The longest one wins, and when `to` ends in `/` the rest of the path goes after it: `/docs/install` becomes `https://docs.example.com/install`.
- The query string goes along, unless `to` has one of its own. A redirect that carries the visitor's query string is not kept by the edge, because the cache key may leave the query out ([`edge.vary_query`](/running/edge-cache#links-with-a-query-string)) and the next visitor would get this one's parameters; the edge script answers it every time instead.
- The status is 301, 302, 307 or 308; 301 when you leave it out.
- At most 10,000 redirects. Paths under `/_ops`, `/.well-known` and `/_brewless` cannot be redirected: Brewless and the providers need them.

After a new table Brewless empties at the edge every `from` of the old table and the new one, so a page the edge kept for an address that now redirects does not linger. A prefix is emptied as one wildcard. When more than 2,000 addresses changed, the whole edge is emptied instead.

The edge keeps a redirect without a query string like a page. The edge script reads the table at most once a minute in each of its instances, so a new table can take a minute to reach every point of presence.

## Search without your container

A search box is answered differently for every query, so the edge cannot keep it and every search wakes your container. With `edge.search` the edge answers it itself:

```yaml
environments:
  production:
    edge:
      keep_pages: true
      search: true
```

The warm-up of every release makes an index of the pages it keeps, one per domain, in your storage zone, and a published page goes into it straight away. A warm-up that stops before the end of your sitemap still leaves an index of the pages it got to. What goes in is the page's title, its meta description and its text: the element marked `data-brewless-search`, or else `<main>`, or else `<body>`, without scripts, navigation, headers, footers, forms and anything marked `data-brewless-search-ignore`. The text is cut at 1,500 characters per page. A page with `<meta name="robots" content="noindex">` is left out.

Your page asks `/_brewless/search?q=…` (and `&limit=`, at most 20) on its own domain and gets JSON:

```json
{"query": "edge", "results": [{"url": "/blog/edge-caching", "title": "Edge caching", "description": "…", "excerpt": "…"}]}
```

A result holds every word of the query; the last word may be the start of one, so a box can ask while the visitor types. A word in the title counts most, then in the description, then in the text. The answer is never kept by the edge: its cache key may leave the query string out. Until the first warm-up with `search: true` has run there is no index, and the edge answers `404` with `{"results": [], "unavailable": true}` itself, never kept, so a search box can fall back to something of its own.

```html
<input type="search" id="q">
<ul id="results"></ul>
<script>
document.getElementById('q').addEventListener('input', async (event) => {
    const answer = await fetch('/_brewless/search?q=' + encodeURIComponent(event.target.value));
    const { results } = await answer.json();
    document.getElementById('results').replaceChildren(...results.map((result) => {
        const item = document.createElement('li');
        const link = Object.assign(document.createElement('a'), { href: result.url, textContent: result.title });
        item.append(link);
        return item;
    }));
});
</script>
```

This searches the words of your pages, nothing more: no filters, no facets, no spelling correction. A search that needs your database still belongs to your container.

## In the console

The environment page shows **Publishing to the edge**: whether it is on, when the last publish ran and how it came out, how many redirects the edge keeps, and the last 20 addresses your application published, with what became of each. Every publish and every new table is an operation of its own in the list of operations. [What reaches the container](/running/edge-cache#what-keeps-your-container-awake) counts a search or a redirect the edge answered as the edge's.

## What it costs

Brewless charges nothing for it. The edge script is the one `keep_pages` already runs, billed by bunny.net per request and per second of processor time; a search adds a little of both, because the script answers it every time. The index and the table sit in the storage zone you already pay for. Asking a published page again costs your container one request, while it is awake anyway.

## The edge door

`brewless/laravel` does this for you. For another framework, the requests are signed like those of the [capacity API](/running/capacity-api): an HMAC-SHA256 with `BREWLESS_EDGE_KEY` over the method, the path, the time and the SHA-256 of the body, each on a line of its own, in `X-Brewless-Signature`, with `X-Brewless-Environment` and `X-Brewless-Timestamp`.

| Request | Body | Answer |
| --- | --- | --- |
| `POST /api/runtime/edge/publish` | `{"paths": ["/blog/my-post"], "reason": "entry.saved"}`, 1 to 100 addresses | 202 with the operation |
| `PUT /api/runtime/edge/redirects` | `{"redirects": [{"from": "/old", "to": "/new", "status": 301}]}` | 202 with the operation |
| `GET /api/runtime/edge/status` | none | 200 with what the console shows: on or off, the last publish, the last 20 addresses and the redirect count |

A wrong signature is a 401, a release without `edge.publish: true` a 403, redirects without `keep_pages` a 409. At most 60 requests a minute per environment.

## Switching it off

`publish: false`, or leaving it out, shuts the door at the next deploy: the key stays with the environment but is refused, and the containers no longer get it. A redirect table you sent stays in your storage zone, and the edge keeps answering it for as long as `keep_pages` is on: send an empty one first (`brewless:redirects --clear`) to stop that. `search: false` stops making the index; the last one stays in the zone. Nothing of yours is removed without being asked.
