
IndexNow for Laravel Rust
Tell search engines a URL changed, the moment it changes.
IndexNow is a small protocol: you publish a key file on your domain, then POST the URLs that changed. Bing, Yandex, Seznam, Naver and Yep consume it, and one submission to the shared endpoint reaches all of them. Google does not participate, so this complements your sitemap, it does not replace it.
This crate wires the protocol into your models, so publishing a post submits its URL and unpublishing it submits the URL again, which is the part most implementations miss.
new.track
That is the whole integration. Nothing is added to the model.
It is the port of LaraIndexNow, the PHP package, to Laravel Rust. It targets Laravel Rust 0.1, which is in beta, and its API follows the framework's changes until 1.0. The behaviour, the names and this document follow the PHP package. Where Laravel Rust has no equivalent, the section says so, and the differences are collected at the end.
Installation
Register the service provider in src/app.rs, with the models you track:
use laraindexnow as indexnow;
use IndexNowServiceProvider;
use Application;
use cratePost;
The crate is imported as laraindexnow; add use laraindexnow as indexnow; if you like the
shorter name used in this document.
The provider adds the configuration, the IndexNow service, the key file route, the commands, the
queue jobs and the model observers. It needs the database feature of Laravel Rust, which your
application already has if it has models.
Laravel Rust 0.1 does not compile its database feature without a backend, so this crate cannot be
built on its own. The sqlite feature exists only for that case (docs.rs, a plain cargo check of
the crate) and an application never needs it.
Getting the key in place
Generate a key:
The command prints the line to add to your configuration, in src/app.rs:
.with_config
Nothing is written for you: Laravel Rust reads settings from typed sections, and the only value this
crate reads from the environment is INDEXNOW_ENABLED, the kill switch. The PHP package's
indexnow:key writes the key to .env or to its config file, and this one does neither, because
there is no file it could edit without guessing.
Worth knowing before you decide where to keep it: unlike most keys this one is public by design, since you publish it as a text file, and it has to match a file that lives in the repository. Keeping it in code means it cannot drift apart from that file and a deploy needs nothing else.
The key has to be publicly readable at https://yourdomain.com/{key}.txt. This crate serves that
route for you, so there is nothing to drop into public/. Laravel Rust 0.1 does not allow text
after a route parameter, so /{key}.txt cannot be a single route: the provider registers one
fixed route per configured key when the application starts. Changing a key therefore needs a
restart, as any change to the configuration does.
If you deploy behind maintenance mode, write a real file as well:
The route and the file cover the same URL, and on an ordinary day the route is enough. The file is
for the days that are not ordinary: a file in public/ is served before the framework answers
anything else, so it survives a deploy that is half done. Commit it, or generate it again on the
server after deploying. The command warns you about a key file left over from a previous key,
which stays claimable until you delete it.
When the host already has a key, the command asks before replacing it. Without a terminal to ask
in, as in a deploy script, it keeps the configured key and says so, and --file writes the file for
that configured key. So the same line works on every deploy:
The address it prints uses the scheme and port of APP_URL, so a local http://localhost:8000
is not reported as https.
Confirm it works before you rely on it:
An unreachable key file is the reason behind almost every 403 from the endpoint, and the
endpoint itself tells you nothing useful about which half failed. In production Laravel Rust only
answers requests for the host in APP_URL and its subdomains, so an application serving other
domains has to add them to its trusted hosts.
The key file response goes through the web middleware group like any other route, so it carries
the session cookies the group sets. Search engines do not care.
Tracking models
Register your models in the provider. Each call to track() builds a Registration:
new.track
| Method | Asks about | Purpose |
|---|---|---|
url(|record| ...) |
The canonical URL of the record, read from its state. Return None and it is never submitted. |
|
url_template("https://example.com/{id}/{slug}") |
The same, as a template filled from the record's columns. | |
url_for_model(|post| ...) |
The same, from the typed model. It sees the state after the write only. | |
previous_url(|record| ...) |
The address a record had before a write, for url_for_model registrations. |
|
when("attr") |
the record now | The attribute holds something true. |
when_holds("attr", value) |
the record now | The value an attribute has to hold. |
when_in("attr", [...]) |
the record now | Any of several values. |
when_compare("attr", Op::Gte, value) |
the record now | Compared: Eq, Ne, Gt, Gte, Lt, Lte. |
when_not("attr") |
the record now | The attribute holds something false. |
when_not_holds("attr", value) |
the record now | Anything but that value. |
when_all([("a", x), ("b", y)]) |
the record now | Several attributes at once. |
when_fn(|record| ...) |
the record now | A closure judges the whole record. |
when_was("attr", value) |
the change | The value the attribute held before this write. |
when_was_in("attr", [...]) |
the change | Any of several previous values. |
when_changed(&["a", "b"]) |
the change | Those attributes changed, whatever their values. |
when_became("attr", value) |
the change | It just took that value, having held something else. |
when_became_in("attr", [...]) |
the change | It just took any of several values. |
when_became_from("attr", to, from) |
the change | The exact transition, both ends pinned down. |
when_left("attr", value) |
the change | It stopped holding that value. |
when_left_in("attr", [...]) |
the change | It stopped holding any of several values. |
when_increments("attr") |
the change | A numeric attribute went up, whatever the amount. |
sets("attr") |
Written on the record once its URL has been handed over. | |
sets_value("attr", value), sets_with("attr", |post| ...) |
The same, with another value. | |
ignoring([...]) |
Attributes whose change is not a content change. | |
affects(|post| vec![...]), affects_urls([...]) |
Other URLs this write left out of date. | |
publishes_at("col"), changes_at("col") |
Make the registration a source for indexnow:due. |
|
policy(Policy) |
Rules in a type of their own. |
Attributes are named by column. Laravel Rust models are typed structs, so a condition cannot read a
field by name, and the registration reads every column through the model's metadata instead. That
is what makes when_was, when_became and the others possible: they need the state the record
held before the write, and Laravel Rust hands that over as a list of changed columns, not as a
model. Closures that judge a record, url and the policy's when therefore receive a Record,
which reads columns by name (record.text("status"), record.int("comment_count"),
record.bool("published")), and the same closure runs on both states. The typed model is passed to
url_for_model, affects and sets_with, which only ever need the state after the write.
Conditions combine with AND, values with OR. Every condition you chain has to hold. Use the
_in variants for several possible values of one attribute, and when_all to declare several
conditions at once:
.when_in // one attribute, several values
.when_all // several attributes
.url_template
.when_became // it just flipped to true
.when_holds; // and this holds right now
Reading an attribute as a flag
Named on its own, an attribute has to hold something true, and when_not() is the opposite. Truth
is read the way PHP reads it, so 1, "1" and true all pass while 0, "0", null and ""
do not. That covers a column stored as an integer, and it covers a counter: when("comment_count")
is "has at least one".
.when // published is true
.when_not // spam is false
.when // has at least one
.when_compare
These ask about the record as it stands, so indexnow:sync can answer them too and a registration
built only from them is not a transition rule.
Submitting once, and remembering it
sets() writes an attribute on the record once its URL has been handed over. The value defaults to
true, which is the flag column case; sets_value() takes another one and sets_with() a closure.
Put the same attribute in the conditions and the record drops out the moment it is marked, which is
how you say "submit this once, ever":
.url_template
.when_not
.when
.sets
It also makes indexnow:sync resumable: each pass only picks up what is left, instead of
resubmitting the whole table. A dry run never writes.
Two things to know. The write is quiet (update_values on a query, which runs no hooks and fires no
model events), because a normal update would fire another event and the record, having just left
the conditions, would be submitted a second time. And marking means handed over, not accepted by a
search engine: the buffer carries URLs and nothing else, so by the time a submission succeeds or
fails there is no record left to point back at. Listen for SubmissionFailed if a failure has to
undo it. Because the write goes straight to the table, it also bumps updated_at.
A flag like this is the wrong tool when a page should be resubmitted after an edit, since a written
record never comes back. For that, declare the edit as its own registration with when_changed().
Several ways in: registrations combine with OR
Conditions on one registration are an AND, and sometimes that is not the shape of the problem. A record can become worth indexing through more than one route, each with conditions of its own, and no single AND describes all of them at once.
Track the same model again and you get a second registration. Registrations are an OR: a write is submitted when any of them wants it.
// A game page is worth indexing once it is approved and has playthroughs.
// Either half can be the one that arrives last, so declare both routes.
new
.track
.track
Writing that as one registration does not work: when_left(...) and when_became(...) on the same
chain would demand both transitions in the same write, which never happens.
Each registration keeps its own url, ignoring, affects and policy, so they are read and
reasoned about separately. The model is observed once however many registrations it has, and a URL
that two of them resolve is submitted once.
Naming the URL
Laravel Rust 0.1 has no named routes, so there is no route('blog.show', $post). A registration
names its URL in one of three ways:
.url_template // filled from the record's columns
.url
.url_for_model
A template is percent encoded, and gives no URL when a placeholder names an empty column. The first
two read a Record, so they also resolve the address the record had before a write, which is how a
changed slug announces the old URL as well as the new one. url_for_model reads the typed model,
which is nicer to write and only knows the state after the write: pair it with previous_url if
the old address matters.
affects_urls() takes a fixed list and affects() a closure over the model:
.affects_urls
.affects
Policy classes
When the rules grow, or you want them testable on their own, implement Policy:
use ;
;
new.track
Only url() is required. previous_url(), ignoring() and affects() are optional, and the
registration's own url and affects win over the policy's.
A registration with neither a URL resolver nor a policy stops the application from booting, and so
does a changes_at() without publishes_at(), because that registration could never be a source.
Catching it when the application starts beats finding out from a submission that never went out.
What actually triggers a submission
With a transition condition, that condition decides, full stop. when_became,
when_became_from, when_left, when_increments, when_changed and when_was all need both
states, so they only apply to writes.
when_increments cares about direction, not amount: a counter going from 3 to 4 matches like one
going from 0 to 90. To catch only the first rise, which is the usual "this page now has enough
content to be worth indexing" case, reach for when_left("attr", 0_i64) instead.
Without one, the default rule applies, and it asks a single question: does this record belong
in the index, before and after? That answer is whatever your when conditions return, as a plain
true or false.
With publishes_at(), the date is part of that answer in both cases: a record with no date, or
with a date still ahead, is not in the index yet. Saving a scheduled post submits nothing, and
indexnow:sync does not list it. indexnow:due announces it when the date comes, and moving the
date into the past by hand counts as entering the index.
when before |
when after |
Submitted |
|---|---|---|
| false | false | no |
| false | true | yes, it entered the index |
| true | true | only if a content attribute changed |
| true | false | yes, it left the index |
That last row is the one most implementations get wrong. A record leaving the index matters as much as one entering it: the URL now 404s and the engines should be told to look. The same goes for a deleted record, and for a changed slug, where both the old and the new URL go out.
Three model events are observed: Created, Updated and Deleted. Laravel Rust 0.1 has no soft
deletes and no Restored event. A model that hides rows with a deleted_at column leaves the
index through an ordinary update, so when_not("deleted_at") covers it, and bringing it back is an
update that enters the index again. An update that changes nothing fires no event and submits
nothing.
Laravel Rust dispatches model events after the surrounding transaction commits, and discards them if it rolls back, so a rolled back write never reaches a search engine. There is nothing to configure.
An error while announcing a write is reported and never returned: announcing a URL is never worth losing the write it was announcing.
The gap you need to know about
Model events do not fire for query builder writes. This publishes a hundred posts and IndexNow hears about none of them:
query
.filter
.update_values
.await?;
The same is true of delete() on a query, insert() and upsert(). No package can intercept
those. That is what indexnow:sync is for:
It walks the table, evaluates the same when conditions the observer uses, and submits everything
that qualifies. Use --dry-run first. The model is named by its struct (post, case insensitive)
or by its full type name.
Content that changes without a write
Submissions come from model events, and two kinds of content never produce one:
- Scheduled content. A post dated for Friday goes live on Friday because the clock moves, not because anything writes to the row. No event fires, so nothing is announced.
- Content that is not in a model. Markdown posts, or any page that is only listed in a sitemap.
indexnow:due covers both. It asks a set of sources which pages became public or changed in the
last few hours and submits them. It runs on the schedule you give it, so nothing has to happen at
the moment the content changes.
Scheduled models
Tell the registration which column holds the moment the record goes public, and optionally which one holds the last content change:
.url_template
.when_holds
.publishes_at
.changes_at
.affects_urls
A registration with publishes_at() is still an observer, exactly as before, and now it is a source
as well. It finds the rows whose publish date or change date falls inside the window and is not in
the future, so a scheduled row is only returned once its date has passed. Each page is dated with
the later of the two dates that fall inside the window.
Everything else about the registration applies. Its when conditions are evaluated for each
record, the same way the observer and indexnow:sync evaluate them, so a draft whose date passed is
not announced. The URL resolver gives the address, and the affects URLs are returned too. Only
conditions about the record as it stands take part, as in indexnow:sync: a transition such as
when_became() needs a write to compare against, and there is none here. sets() is not applied.
changes_at() needs publishes_at(). Without a change column, only the publish date counts, and an
edit made through the query builder is not announced.
Sitemaps and your own sources
There is no Larablog source yet. The PHP package's sources.larablog setting, its noindex
front matter and its larablogUrls() resolver have no counterpart here. Markdown posts go through a
sitemap, or through a source of your own.
A sitemap. Any list of URLs with a modification date:
new.sitemap
or in the configuration, where it needs no code:
config..sources.sitemaps.push;
It fetches the file with Laravel Rust's HTTP client and follows sitemap index files, up to three
levels deep and never the same file twice. A .xml.gz sitemap is read as it is stored. A URL is
returned when its <lastmod> falls inside the window. A <lastmod> is an RFC 3339 date and time,
or a bare date, which means midnight UTC, and one with no offset is read as UTC. URLs without a
<lastmod> are ignored: the sitemap does not say when they changed, and treating them as changed
would announce the whole site on every run. A sitemap that cannot be fetched or read is reported and
makes the command exit with an error, rather than passing for a quiet day.
Your own. Implement Source and register it:
use async_trait;
use ;
use Timestamp;
;
new.source
A source returns the pages that became public or changed between since and now, each with an
absolute URL and the date of the change. Never return a date in the future. indexnow::source()
and indexnow::sitemap() register one while the application runs, and indexnow::sources() lists
what indexnow:due reads.
Running it
The crate does not schedule it for you. Add it where you schedule everything else, in
src/console/mod.rs:
The command has no memory. On every run it collects what became public or changed in the last
--hours hours, up to now and never in the future, and submits it through the same path as
indexnow:submit: batching per host, the environment guard, the transport, logging, events and the
deduplication window all apply. It records nothing.
Make the window a little longer than the interval you schedule it at, so a late run leaves no gap.
The default of 25 hours matches a daily schedule; run it hourly with --hours=2. Submitting a URL
twice does no harm. The trade-off is that a run missed for longer than the window is never made
up for: the pages of that stretch are not announced unless you run the command by hand with a
larger --hours.
Outside the configured environments the command does nothing and exits successfully, so the same schedule can run everywhere. It exits with an error when a submission failed or a source could not be read.
A URL the observers already announced, and that a source also reports, is sent again by
indexnow:due. The deduplication window absorbs it when it is recent enough.
Submitting by hand
submit.await?; // buffered, sent by the queue
submit.await?;
submit_now.await?; // sent inline, returns the results
submit_model.await?; // resolves the URL from the registration
submit and submit_now take one URL or any list of them. They are free functions that resolve the
IndexNow service; a handler or a command can take an Inject<IndexNow> instead and call the same
methods (submit_now there also takes a force flag that ignores the deduplication window).
And when you are importing, seeding or backfilling:
without_submissions
.await?;
Model events fired inside are observed and discarded. Work you spawn with tokio::spawn is not
covered; spawn it with laravel::task::spawn inside the block.
Buffering, queueing and deduplication
Model events do not send HTTP requests. They push URLs into a cache backed buffer and schedule one delayed job to drain it, so saving a hundred rows produces one request rather than a hundred. Exactly one flush job exists per window, no matter how many events arrive.
The same URL is not submitted twice within the deduplication window. Editing a post five times in ten minutes is one submission. Keep that window short (the default is an hour). It is an anti-bounce measure, not a record of what is already indexed, and a long window swallows real edits: publish at 09:00 with a 24 hour window and the correction you make at 15:00 never goes out.
Retries live on the job, not on the transport. A 429 is released with the endpoint's own
Retry-After; a 5xx or a connection failure fails the attempt and the job backs off at 1, 5 and
15 minutes, four attempts in all. A rejected key or a malformed URL (400, 403, 422) is never
retried, because retrying will not fix it. The last attempt fails with the reason the submission
actually failed for, which is what lands in the failed jobs table.
With queue.enabled off, everything is sent inline instead. Both the buffer and the deduplication
window live in the cache store named by buffer.store, or in the default one, so use a shared store
such as redis or database when you run several servers.
Laravel Rust sends every job to the sync connection in tests, so a buffered submission is sent as
soon as its delayed flush is dispatched there. Fake the queue (queue::fake()) to look at the jobs
instead.
Several domains from one application
Map a key per host:
let indexnow = config.;
indexnow.keys.insert;
indexnow.keys.insert;
The key file route answers with the right key for whichever host was requested, submissions are
grouped per host before being sent, and URLs whose host is not configured are dropped rather than
submitted against the wrong key. indexnow:verify checks every host at once.
Commands
Run them with your application's binary, as in cargo run -- indexnow:key.
| Command | |
|---|---|
indexnow:key |
Generate a key and show where it has to be published |
indexnow:verify |
Check the key file is publicly readable and correct |
indexnow:submit {url*} |
Submit URLs by hand, inline by default |
indexnow:sync {model} |
Submit every indexable record of a tracked model |
indexnow:due {--hours=} {--dry-run} |
Submit what became public or changed in the last hours without a write: scheduled models, sitemaps, your own sources |
indexnow:flush |
Send whatever is waiting in the buffer |
indexnow:models |
List the tracked models |
Commands send inline by default, because when you run one you want the status code on screen, not a
queued job. Pass --queue for the opposite.
Options: indexnow:key takes --host, --length and --file; indexnow:verify takes --host;
indexnow:submit takes --queue and --force; indexnow:sync takes --chunk, --batch,
--limit, --queue, --force and --dry-run; indexnow:flush takes --queue.
Testing
let fake = fake.await?;
create!.await?;
fake.assert_submitted;
fake.assert_submitted_count;
fake.assert_nothing_submitted;
fake() swaps the transport and bypasses the queue, so assertions work without a worker. The fake
also has assert_not_submitted, assert_submitted_where, submissions(), submitted() and
reset().
It does not lift the environment guard, though: submissions only happen in the environments listed
in environments, production by default, and that includes faked ones. In the testing
environment nothing is recorded and every assertion fails, so allow it in your test application:
.with_config
The package's own tests use the pattern the Laravel Rust guide describes for packages: a
tests/common/mod.rs that builds an application with for_testing, #[laravel::test(app = ..)] on
each test, client::fake() for the endpoint and queue::fake() for the jobs.
Not submitting from your laptop
Submissions only happen in the environments listed in the configuration, production by default.
This is the guard that stops a development machine from asking search engines to crawl URLs that
only resolve locally, and it is the first thing to check when nothing is going out.
For a staging machine that should exercise the whole path without talking to the endpoint, set
driver to Driver::Null and log to LogMode::Log.
To stop submissions in production without deploying, set INDEXNOW_ENABLED=false and restart. That
is the only setting this crate reads from the environment: it is an operational kill switch, not
configuration.
Configuration
Everything lives in IndexNowConfig, a configuration section with the defaults below. Change what
you need in src/app.rs:
use ;
configure.with_config
The settings worth knowing about:
| Field | Default | |
|---|---|---|
enabled |
true |
Master switch, the only setting reading the environment (INDEXNOW_ENABLED) |
environments |
["production"] |
Where submissions may happen. Empty means everywhere |
endpoint |
https://api.indexnow.org/indexnow |
The shared endpoint |
timeout |
10 |
Seconds to wait for the endpoint |
driver |
Driver::Http |
Http or Null |
key / keys |
None / {} |
Single key, or one per host |
key_location |
None |
Only when the key file is hosted outside the root of the domain |
serve_key_file |
true |
Serve /{key}.txt from the application |
hosts |
[] |
Allowed hosts, derived from the keys (or from APP_URL) when empty |
queue.enabled |
true |
Buffer and queue, or send inline |
queue.connection, queue.queue |
None |
Where the jobs go |
buffer.store |
None |
The cache store, or the default one |
buffer.key |
indexnow:buffer |
The cache key of the buffer |
buffer.delay |
60 |
Seconds before the buffer is drained |
buffer.max_urls |
10000 |
The buffer flushes early when it holds this many URLs |
dedupe.enabled, dedupe.ttl, dedupe.prefix |
true, 3600, indexnow:sent: |
The deduplication window, in seconds |
ignored_attributes |
remember_token, views, view_count, last_seen_at |
Changes limited to these are not a content change |
log |
LogMode::Null |
Null or Log (written through tracing) |
due.hours |
25 |
Hours indexnow:due looks back, overridden by --hours |
sources.models |
true |
Read the models tracked with publishes_at in indexnow:due |
sources.sitemaps |
[] |
Sitemaps indexnow:due reads |
The timestamp columns of each model are always ignored. The PHP package's log_channel and
table settings and its database log mode do not exist here: tracing decides where the log
goes, and there is no migration to publish.
Events
UrlsSubmitted and SubmissionFailed, both carrying the SubmissionResult with the host, the
URLs, the status code and a message written to be read by a human. SubmissionFailed also carries
the error of a failure that will be retried.
use SubmissionFailed;
use ;
async
Differences from the PHP package
- Models are typed. Conditions name columns and read a
Record, URLs come from a template or a closure over the record, and the typed model is available where only the state after the write matters. There are no named routes in Laravel Rust 0.1, so there is no route name as a URL. - Registrations go in the provider, not in a facade call, because the observers are registered
on the event dispatcher while the application is built.
indexnow::track::<Post>()builds the registration andIndexNowServiceProvider::tracktakes it. - The key is not written for you (see the key).
- No
restoredevent, no Larablog source, no database logger. Laravel Rust 0.1 has no soft deletes, the Larablog source is not in the Rust version yet, and the log goes throughtracing. - Submissions are always a
POSTwith the JSON body. The PHP package sends a single URL as aGET. The protocol accepts both and one code path is easier to reason about. - The key file is one route per configured key.
publishes_at()decides on its own as well. In the PHP package it only makes the model a source forindexnow:due, so a scheduled post that passeswhenis submitted on save unless a condition checks the date. Here a date still ahead keeps the record out of the index for the observer andindexnow:synctoo.indexnow:keywithout a terminal keeps the configured key and writes its file with--file. The PHP package stops at the question and writes nothing.- The environment guard reads the application's environment name,
APP_ENV, asenvironmentslists it.
Sponsors
IndexNow for Laravel Rust is supported by the following sponsors. Thank you for keeping it growing:
Author
Created by Edu Lazaro
License
IndexNow for Laravel Rust is open-sourced software licensed under the MIT license.