Usage | laravel-og-image-rust | Spatie       

 SPATIE  

laravel-og-image-rust
=====================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-og-image-rust](https://spatie.be/docs/laravel-og-image-rust/v1)  Usage

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-og-image-rust/v1) 

  Usage    
- [ Introduction ](https://spatie.be/docs/laravel-og-image-rust/v1/introduction)
- [ Support us ](https://spatie.be/docs/laravel-og-image-rust/v1/support-us)
- [ Installation ](https://spatie.be/docs/laravel-og-image-rust/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/laravel-og-image-rust/v1/usage)
- [ Testing ](https://spatie.be/docs/laravel-og-image-rust/v1/testing)
- [ Changelog ](https://spatie.be/docs/laravel-og-image-rust/v1/changelog)

 Usage
=====

###  On this page 

1. [ Prepare a page ](#content-prepare-a-page)
2. [ Views and existing images ](#content-views-and-existing-images)
3. [ Preview and image settings ](#content-preview-and-image-settings)
4. [ Capture providers ](#content-capture-providers)
5. [ Generate ahead of time ](#content-generate-ahead-of-time)
6. [ Responses and storage ](#content-responses-and-storage)
7. [ Commands ](#content-commands)
8. [ Customize actions and jobs ](#content-customize-actions-and-jobs)
9. [ Handle errors ](#content-handle-errors)

Prepare a page
--------------------------------------------------------------------------------------------------

- Templates contain trusted HTML. Escape user-supplied text before inserting it.
- Defaults are 1200 × 630 CSS pixels, 2× device scale, and JPEG with the provider's default quality.

```
use spatie_og_image::Template;

let template = Template::new("<h1>My next article</h1>").render()?;
assert!(template.starts_with("<template data-og-image"));
```

Call the service inside an application context:

```
use spatie_og_image::Template;

let card = Template::new("<h1>My next article</h1>").render()?;
let html = format!("<html><head><style>h1 {{ color: red }}</style></head><body>{card}</body></html>");
let fallback = Template::new("<h1>My blog</h1>");

let page = service.prepare(
    "https://blog.example.test/posts/next?draft=42",
    &html,
    Some(&fallback),
).await?;

// Return page.html as an HTML response, not a JSON string.
Ok(page.html)
```

- The fallback template is inserted before the closing body tag only when the page has no `template[data-og-image]`.
- A fragment without a body tag is left unchanged, as is a page with neither a template nor a fallback.
- `Config::fallback_url` is separate. It supplies the image redirect while a queued capture is pending.

Views and existing images
-----------------------------------------------------------------------------------------------------------------------------------

- Render application views using `Template::view(laravel::view::view("og-image.post", data))?`.
- The framework escapes data according to the view engine. Output is rendered once, so user text containing `{{ expression }}` or `@each` is not interpreted a second time.
- Pass `.options(...)` to override capture settings as with inline templates.

Use a direct URL when an image already exists:

```
use spatie_og_image::Template;
let template = Template::url("https://cdn.example.test/card.png?a=1&b=2")?.render()?;
```

- Direct URLs write social tags without caching generation metadata or creating an `Image`. They prevent fallback injection.
- URLs must use HTTP(S) without credentials. Only the first matching OG template is used.
- Override the native screenshot wrapper, `og-image::screenshot`, using view namespace registration or the rendering hook below.

Preview and image settings
--------------------------------------------------------------------------------------------------------------------------------------

- Pass the actual request URL to `prepare`. Adding `?ogimage` selects preview mode. Existing query parameters remain in metadata; the preview parameter name is configurable.
- The first matching template wins, regardless of attribute order or quoting.
- Override dimensions, scale, format, and quality with `Template::options(ImageOptions { ... })`. PNG does not accept quality. Width and height must be 1–8192, scale 1–3, and output must not exceed 64 million pixels.
- Preparation replaces `og:image`, `twitter:image`, and `twitter:card` tags. Parsing and serializing HTML can change insignificant quoting and attribute formatting.
- The cached snapshot is immutable and uses the page URL as its base for relative assets. Keep draft pages and their caches private; an image URL is not an authorization mechanism.

Capture providers
-----------------------------------------------------------------------------------------------------------

Local and remote Chrome use `spatie-browsershot`, not another screenshot implementation:

```
use spatie_og_image::BrowsershotCapture;

let local = BrowsershotCapture::new()
    .configure(|browser| browser.set_chrome_path("/usr/bin/google-chrome"));
let remote = BrowsershotCapture::new()
    .configure(|browser| browser.set_remote_instance("chrome.internal", 9222)
        .throw_on_remote_connection_error(true));
```

- Keep Chrome's sandbox enabled. Only opt out for a trusted disposable environment that cannot support it.
- Capture dimensions and encoding are applied after your callback. Include a revision in template markup when changing other browser settings that affect rendering.

Cloudflare Browser Run uses its account-scoped HTTP screenshot API:

```
use spatie_og_image::{CloudflareCapture, Config, OgImage};
use laravel::{rate_limit::Limit, time::ToSpan};

let mut config = Config::new("https://blog.example.test")?;
config.rate_limit = Some(("screenshots:shared-account".into(), Limit::per(1, 20.seconds())));
let token = std::env::var("CLOUDFLARE_API_TOKEN")?;
let account = std::env::var("CLOUDFLARE_ACCOUNT_ID")?;
let service = OgImage::new(config, CloudflareCapture::new(&account, token)?)?;
```

- Debug output redacts the token. Provider response bodies are not logged because they may echo private HTML.
- HTTP 429, provider code 2001, rate-limit messages, time-limit messages, and 5xx responses return `Error::RetryAfter`. Jobs release for that delay without counting an ordinary error.
- Rate-limit retries default to 60 seconds and time-limit retries to one hour. Numeric `Retry-After` overrides the delay, with a minimum of one second. Invalid headers use the default delay.
- Other HTTP failures retain their status but omit the response body. Transport/browser failures use the job's ordinary retry policy.
- Both providers capture the cached snapshot, not the current contents of the page URL, with a 90-second capture timeout.
- Generation validates encoding, dimensions, and decoding before writing to the framework disk. HTML, corrupt images, and images at the wrong size do not populate storage.

Generate ahead of time
--------------------------------------------------------------------------------------------------------------------------

- Call `service.enqueue(&image.filename).await?` to queue an already prepared image.
- Call `service.generate(&image.filename).await?` to wait for capture inside the async operation and receive errors directly.

To discover a template from a trusted page URL:

```
use spatie_og_image::GenerateOgImageForUrlJob;

GenerateOgImageForUrlJob {
    url: "https://blog.example.test/posts/next".into(),
}.dispatch().await?;
```

- `generate_for_url` fetches the page, requires a successful HTTP status, discovers its first template, and generates it.
- Both jobs share the capture limiter and distributed generation locks. The URL job is not unique because page contents can change. Capture does not repeat once the content-hashed file exists.
- Inspect metadata with `service.metadata(&filename).await?`.
- Do not accept arbitrary visitor URLs or HTML. Page fetches, redirects, stylesheets, images, scripts, and browser navigation can reach private networks or run scripts.
- Restrict generation to trusted application content and enforce network egress policy outside this package.
- Fingerprint assets and include template revisions when changes should invalidate an image.

Responses and storage
-----------------------------------------------------------------------------------------------------------------------

- Successful responses stream from the framework disk with the correct MIME type, `Content-Length`, `X-Content-Type-Options: nosniff`, and `Cache-Control: public, max-age=86400, immutable`.
- Set `max_age` to zero for `no-store`.
- Missing files with cached metadata enqueue one job per filename. Pending responses are a 302 redirect to the fallback URL, or an empty 503 without a fallback. Both send `Cache-Control: no-store` and `Retry-After: 60`.
- Malformed names and missing/expired metadata return 404. Storage and dispatch failures propagate. Stored images remain available after metadata expires.
- Storage backend URLs are never exposed. Use a directory or bucket lifecycle policy to remove old content-hashed files; cache expiration does not delete images.

Commands
--------------------------------------------------------------------------------

- `og-image:generate https://blog.example.test/one https://blog.example.test/two` fetches and generates each URL. It continues after an individual error, prints the summary, and exits unsuccessfully if any URL failed.
- `og-image:clear` deletes files directly in the configured disk/path. It leaves other directories and nested directories alone. Metadata is retained so the next request can regenerate an image.

Customize actions and jobs
--------------------------------------------------------------------------------------------------------------------------------------

Bind a configured `OgImage` in the application's `.with_services(...)` callback to override the provider default. Use a lazy singleton when it needs the final typed config:

```
use laravel::{Application, config::Env};
use spatie_og_image::{service_provider, BrowsershotCapture, Config, OgImage, Template};

let application = Application::configure()
    .replace_env(Env::default())
    .with_providers(|providers| {
        providers.add(service_provider(
            Config::new("https://blog.example.test").unwrap(),
            BrowsershotCapture::new(),
        ));
    })
    .with_services(|services| {
        services.singleton(|app| async move {
            Ok(OgImage::new(app.config().section::<Config>().clone(), BrowsershotCapture::new())?
                .fallback_using(|url| Ok((url.path() != "/private")
                    .then(|| Template::new("<h1>My blog</h1>")))))
        });
    })
    .create();
```

- `fallback_using` receives the normalized page URL and returns a template or `None`. Explicit page templates always win. The callback can render a native view with `Template::view`.
- `resolve_url_using` selects the page URL used for preview metadata and resolving relative assets. The result must be HTTP(S) without credentials. Explicit `prepare` callers can also supply that URL directly.
- `render_using` receives the URL, head, content and resolved image options. Its HTML is the captured snapshot and participates in hashing.
- `response_using` replaces image serving. Call `service.default_response(...)` from the hook to decorate default behavior without recursion.
- `dispatch_using` replaces the dispatch operation. Dispatch your own native `#[job]` type, or set native `on_queue` / `on_connection` options on the supplied job. Await the dispatch and propagate its errors so uniqueness is released if dispatch fails.
- For queue or connection changes alone, set `Config::queue` and `Config::queue_connection`. No custom type is needed.
- Directly dispatched `GenerateOgImageForUrlJob` values accept the framework's dispatch options.
- Custom generation jobs store the supplied `filename` and `owner`, then call `GenerateOgImageJob { filename, owner }.run(&service, attempt).await` in their handler.
- Call `release_pending().await` from the custom job's native `failed` hook to preserve uniqueness across retries and release it on terminal failure.
- The custom type owns its job attributes, timeout, retry policy and middleware. There are no database models to replace.

Handle errors
-----------------------------------------------------------------------------------------------

- Operations return the package's `Error`, which implements `std::error::Error`.
- `Url`, `Attribute`, and `Image` retain their original parsing or decoding errors. `ImageEncoding` and `ImageDimensions` identify provider responses with the wrong format or size.
- `Provider { status }` never contains the provider body. Match the status rather than parsing a message.
- `NotFound` covers malformed filenames consistently across metadata, enqueueing, and generation. A valid filename without cached metadata returns `Ok(None)` from `metadata`.
- Supplied jobs already handle `RetryAfter`. Custom capture callers must apply their shared limiter and retry policy.

```
use spatie_og_image::{Error, Template};

let error = Template::url("not an absolute URL").unwrap_err();
assert!(matches!(error, Error::Url(_)));
```

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
