LaraIndexNow Rust

LaraIndexNow Rust implements the IndexNow protocol in Laravel Rust. You publish a key file on your domain, and from then on every model write that changes what is on a page submits that URL to Bing, Yandex, Seznam, Naver and Yep in one request. Google does not participate in IndexNow, so this sits next to your sitemap rather than replacing it. Bing's index also grounds AI search: Copilot draws on the same crawling and indexing as Bing, and OpenAI names Bing among the search providers behind ChatGPT search.
Written against version 0.1, which targets Laravel Rust 0.1 (in beta). Its API follows the framework's changes until 1.0.
This is the port of LaraIndexNow, the PHP package, and its behaviour and names follow it. This page is about running it: the key, tracking models, the commands, the config and what to check when nothing goes out. The crate is on crates.io and its API reference is on docs.rs. For a step-by-step tutorial in Spanish, see Cómo usar IndexNow en Laravel Rust on Neoguias.
Installation
cargo add laraindexnow
cargo run -- indexnow:key --file
cargo run -- indexnow:verify
Register the provider in src/app.rs with the models you track. Nothing goes on the model itself:
use laraindexnow as indexnow; use laraindexnow::IndexNowServiceProvider; use laravel::Application; use crate::models::Post; pub fn configure() -> ApplicationBuilder { Application::configure().with_providers(|providers| { providers.add( IndexNowServiceProvider::new().track( indexnow::track::<Post>() .url_template("https://example.com/blog/{slug}") .when_holds("status", "published"), ), ); }) }
The crate is imported as laraindexnow; use laraindexnow as indexnow; gives the shorter name used on this page. 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 the 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.
The key file is the whole authentication
There is no account and no token. If you can publish text at https://yourdomain.com/{key}.txt, the domain is yours. indexnow:key generates a key and prints the line to add to your configuration, in src/app.rs:
.with_config(|config, _| { config.section_mut::<IndexNowConfig>().key = Some("ecd5c0c8f2ad4b0e9a0d1f2c3b4a5968".into()); })
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. Unlike most keys this one is public by design and has to match a file that lives in the repository, so keeping it in code means the two cannot drift apart and a deploy needs nothing else.
The crate serves the key file 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, and changing a key needs a restart.
Generate the file as well with indexnow:key --file. A real file in public/ is handed over by nginx without booting the framework, so it keeps answering while the application is half deployed. Commit it, or generate it again on the server. The command warns you about a key file left over from a previous key, which stays claimable until you delete it.
indexnow:verify checks that the key file is publicly readable. 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 address it prints uses the scheme and port of APP_URL, so a local http://localhost:8000 is not reported as https.
Several domains from one application
Map a key per host and the crate picks the right one for each URL:
let indexnow = config.section_mut::<IndexNowConfig>(); indexnow.keys.insert("example.com".into(), "ecd5c0c8f2ad4b0e9a0d1f2c3b4a5968".into()); indexnow.keys.insert("example.org".into(), "5f3a9d7e1b2c4a6d8e0f1a2b3c4d5e6f".into());
The key file route answers with the right key for whichever host was requested, and URLs whose host is not configured are dropped rather than submitted against the wrong key. indexnow:verify checks every host at once.
Tracking models
Each call to track() builds a Registration. Laravel Rust 0.1 has no named routes, so a registration names its URL in one of three ways:
.url_template("https://example.com/blog/{slug}") .url(|post| Some(format!("https://example.com/blog/{}", post.text("slug")?))) .url_for_model(|post: &Post| Some(format!("https://example.com/blog/{}", post.slug)))
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 and only knows the state after the write: pair it with previous_url if the old address matters.
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. Closures that judge a record receive a Record, which reads columns by name: record.text("status"), record.int("comment_count"), record.bool("published").
The conditions ask either about the record as it stands or about the change:
- The record now.
when("attr"),when_not("attr"),when_holds,when_not_holds,when_in,when_compare("attr", Op::Gte, value),when_allandwhen_fn. - The change.
when_was,when_changed,when_became,when_became_from,when_leftandwhen_increments.
Conditions combine with AND, values with OR. Use the _in variants for several values of one attribute:
indexnow::track::<Post>() .url_template("https://example.com/blog/{slug}") .when_became("published", true) .when_holds("review", "correct")
Beyond conditions, a registration also takes ignoring([...]) for attributes whose change is not a content change, affects_urls([...]) and affects(|post| ...) for other URLs a write leaves out of date, and sets("attr") to write a flag once the URL has been handed over, which is how you say "submit this once, ever".
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, and a URL that two of them resolve is submitted once.
When the rules grow, implement Policy. Only url() is required:
use laraindexnow::{Policy, Record}; struct PostIndexNow; impl Policy<Post> for PostIndexNow { fn url(&self, post: &Post) -> Option<String> { Some(format!("https://example.com/blog/{}", post.slug)) } fn when(&self, record: &Record) -> bool { record.text("status") == Some("published") } }
IndexNowServiceProvider::new().track(indexnow::track::<Post>().policy(PostIndexNow))
A registration with neither a URL resolver nor a policy stops the application from booting, and so does a changes_at() without publishes_at().
What triggers a submission
With a transition condition, that condition decides. Without one, the default rule asks whether the record belongs in the index before and after:
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 |
The last row is the one most implementations get wrong: a record leaving the index matters as much as one entering it, because the URL now 404s. 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. Events are dispatched after the transaction commits, so a rolled back write never reaches a search engine.
Model events do not fire for query builder writes. Post::query().filter(...).update_values(...) instantiates no model, so no observer runs. That is the framework, not this crate: indexnow:sync walks the table, evaluates the same conditions and submits what qualifies.
Content that changes without a write
Two kinds of content never fire a model event. A scheduled post goes public only because its date arrives, and a page that is only listed in a sitemap is not a model at all. indexnow:due covers both: it is a command that asks every source for what became public or changed in the last hours and submits it.
#[schedule::tasks] fn schedule(schedule: &mut Schedule) { schedule.command("indexnow:due").daily_at("00:05").without_overlapping(); }
The crate does not schedule it for you. It keeps no record: each run looks back --hours hours, 25 by default, a little more than the schedule interval so a late run leaves no gap, and submitting a URL twice is harmless. The cost of having no memory is that a run missed for longer than the window is never made up for.
The sources:
-
Models with a date. Add the columns to the registration you already have, and its
whenconditions and URL apply as they are:indexnow::track::<Post>() .url_template("https://example.com/blog/{slug}") .when_holds("status", "published") .publishes_at("published_at") .changes_at("content_updated_at")
-
A sitemap.
IndexNowServiceProvider::new().sitemap("https://example.com/sitemap.xml")submits the URLs whose<lastmod>falls inside the window. Sitemap index files are followed and a.xml.gzsitemap is read as it is stored. URLs without<lastmod>are ignored. -
Your own. Anything that implements
Source, registered withIndexNowServiceProvider::new().source(DocsSource). It returns the pages that became public or changed since a moment, each with an absolute URL and the date of the change.
Run it with --dry-run first to see what it would send. Outside the configured environments it does nothing and exits successfully, so the same schedule can run everywhere.
Commands
Run them with your application's binary, as in cargo run -- indexnow:key.
indexnow:key |
Generate a key. --host, --length, --file |
indexnow:verify |
Check the key file is publicly readable. --host |
indexnow:models |
List the tracked models |
indexnow:submit {url*} |
Submit URLs by hand. --queue, --force |
indexnow:sync {model} |
Submit every indexable record of a tracked model. --chunk, --batch, --limit, --queue, --force, --dry-run |
indexnow:flush |
Send whatever is sitting in the buffer. --queue |
indexnow:due |
Submit what became public or changed in the last hours without a write. --hours, --dry-run |
Commands send inline by default, because when you run one you want the status code on screen. Pass --queue for the opposite.
Configuration
Everything lives in IndexNowConfig, a configuration section. Change what you need in src/app.rs:
use laraindexnow::{Driver, IndexNowConfig, LogMode}; Application::configure().with_config(|config, _| { let indexnow = config.section_mut::<IndexNowConfig>(); indexnow.key = Some("ecd5c0c8f2ad4b0e9a0d1f2c3b4a5968".into()); indexnow.environments = vec!["production".into(), "staging".into()]; indexnow.log = LogMode::Log; })
enabled |
Kill switch, reads INDEXNOW_ENABLED. Turn submissions off during an incident without a deploy |
environments |
Where submissions may happen. production only, by default. Empty means everywhere |
driver |
Driver::Http talks to the endpoint, Driver::Null runs the whole pipeline and drops the request at the last step |
key / keys |
A single key, or one per host |
key_location |
Only when the key file is hosted outside the root of the domain |
serve_key_file |
Serve /{key}.txt from the application |
hosts |
Allowed hosts. Derived from the keys, or from APP_URL, when empty |
queue.enabled |
Model events buffer and one delayed job sends the batch. Disabling it sends inline |
buffer.delay, buffer.max_urls |
Seconds before flushing and URLs before flushing early. The protocol allows 10000 per request |
dedupe.ttl |
The same URL is not sent twice within this many seconds. One hour by default |
ignored_attributes |
Attributes whose change is not a content change. Each model's timestamps are always ignored |
log |
LogMode::Null or LogMode::Log, written through tracing |
due.hours |
How far back indexnow:due looks, 25 hours by default |
sources.models, sources.sitemaps |
The models with publishes_at and the sitemaps indexnow:due reads |
A staging machine that should exercise the whole path without talking to the endpoint is driver at Driver::Null plus log at LogMode::Log. Keep the deduplication window short: it absorbs bursts, it is not a record of what is already indexed.
Retries live on the job. A 429 is released with the endpoint's own Retry-After and a 5xx backs off at 1, 5 and 15 minutes, four attempts in all. A rejected key or a malformed URL is never retried, because retrying will not fix it. To react to a failure, listen for SubmissionFailed; UrlsSubmitted is its counterpart.
For seeding and imports, where you want the writes but not the noise, wrap them in indexnow::without_submissions(async { ... }).await?.
Testing
let fake = indexnow::fake().await?; create!(Post { slug: "hello", title: "Hello", status: "published" }).await?; fake.assert_submitted("https://example.com/blog/hello"); fake.assert_submitted_count(2); fake.assert_nothing_submitted();
fake() swaps the transport and bypasses the queue, but it does not lift the environment guard: in the testing environment nothing is recorded and every assertion fails. Allow it in your test application:
.with_config(|config, _| { config.section_mut::<IndexNowConfig>().environments = vec!["testing".into()]; })
Differences from the PHP package
- Models are typed. Conditions name columns and read a
Record, and URLs come from a template or a closure, because there are no named routes in Laravel Rust 0.1. - Registrations go in the provider, not in a facade call, because the observers are registered while the application is built.
- The key is not written for you.
indexnow:keyprints the line to add tosrc/app.rs. - 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. Markdown posts go through a sitemap or a source of your own. - Submissions are always a
POSTwith the JSON body. The PHP package sends a single URL as aGET. - The key file is one route per configured key.
When nothing is submitted
In the order worth checking:
- The environment.
environmentsisproductionby default, so a laptop submits nothing on purpose. INDEXNOW_ENABLED, and whether the application was restarted after it changed.- The key file.
indexnow:verify. An unreachable or stale key file is behind almost every403. - The host. URLs whose host is not allowed are dropped silently.
- Query builder writes. Use
indexnow:sync. - The worker. Buffered URLs need the queue to drain them.
indexnow:flushsends what is waiting. - The deduplication window, which is doing its job when a second edit within the hour goes quiet.
- Scheduled content. It has no write, so only
indexnow:dueannounces it. Check that the command is scheduled and that the date falls inside its window.
built and maintained by Edu Lazaro · MIT license