Installation | laravel-analytics-rust | Spatie       

 SPATIE  

laravel-analytics-rust
======================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-analytics-rust](https://spatie.be/docs/laravel-analytics-rust/v1)  Installation

 Version   v1      

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

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

 Installation
============

###  On this page 

1. [ Install the crate ](#content-install-the-crate)
2. [ Give the service account access ](#content-give-the-service-account-access)
3. [ Register the package ](#content-register-the-package)
4. [ Construct a client directly ](#content-construct-a-client-directly)
5. [ HTTP and authentication ](#content-http-and-authentication)
6. [ Framework cache ](#content-framework-cache)

Install the crate
-----------------------------------------------------------------------------------------------------------

- Requires Rust 1.99 or newer, Tokio, and `laravel-rust =0.1.0`.
- Install from a local checkout or a Git dependency pinned to a reviewed revision. This crate is not published to crates.io.
- Framework default features are disabled. Enable any additional framework features in your application.

```
[dependencies]
spatie-laravel-analytics = { path = "../laravel-analytics-rust" }
laravel-rust = { version = "=0.1.0", default-features = false }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
```

Give the service account access
-----------------------------------------------------------------------------------------------------------------------------------------------------

1. Enable the Google Analytics Data API in the service account's Google Cloud project.
2. Create a service-account JSON key. Grant its `client_email` at least Viewer access to the GA4 property.
3. Use the numeric property ID, not a `G-...` measurement ID.
4. Store the key on a private storage disk or secret mount, outside your repository and public assets.

Register the package
--------------------------------------------------------------------------------------------------------------------

- Add `service_provider()` to load environment-backed configuration and register a lazy `Analytics` singleton using package-tools.
- Registration and boot do not read credentials or contact Google. The first resolution reads the configured storage disk; the first report exchanges a token.
- Application configuration and service bindings override the provider's defaults.

```
use spatie_analytics::{Config, service_provider};

let app = laravel::Application::configure()
    .with_providers(|providers| { providers.add(service_provider()); })
    .create();
app.boot().await?;
```

- `ANALYTICS_PROPERTY_ID`: numeric property ID, required when constructing or resolving a client.
- `ANALYTICS_CREDENTIALS_DISK`: private storage disk, default `local`.
- `ANALYTICS_CREDENTIALS_PATH`: disk-relative path, default `analytics/service-account-credentials.json`.
- `ANALYTICS_CACHE_STORE`: optional named cache store. Unset disables report caching.
- `ANALYTICS_CACHE_LIFETIME_IN_MINUTES`: default 1440. Zero disables caching without resolving the cache store.

Resolve inside an application scope, request, or command. This example compiles but needs a configured property and service-account file to execute:

```
use spatie_analytics::Analytics;

app.scope(async || {
    let analytics = laravel::container::resolve::<Analytics>().await?;
    assert!(!analytics.property_id().is_empty());
    Ok::<_, laravel::Error>(())
}).await?;
```

Construct a client directly
-----------------------------------------------------------------------------------------------------------------------------------------

- `Analytics::from_service_account_file(config, path)` reads a secret mount.
- `Analytics::from_service_account_json(config, json)` accepts caller-supplied secret JSON.
- `Analytics::from_config(config).await` reads framework storage and attaches the configured cache. It needs an application scope.
- Direct file and JSON constructors validate credentials without network access. They do not attach a cache from config; use `with_cache` explicitly.
- No constructor searches gcloud credentials or the metadata service.

HTTP and authentication
-----------------------------------------------------------------------------------------------------------------------------

- Defaults are Google's GA4 v1beta endpoint, a 30-second request timeout, and 10,000 rows per page.
- `Config::page_size` accepts 1 through 250,000. `Config::timeout` requires a positive duration. Waiting for another task's token exchange is outside that timeout.
- `Config::endpoint` accepts a trusted HTTPS origin or loopback HTTP origin for fixtures, without credentials, paths, queries, or fragments.
- Treat the credential JSON's `token_uri` as trusted configuration: it receives the signed assertion. HTTPS is required except for loopback fixtures. Neither HTTP transport follows redirects.
- Authentication requests only `https://www.googleapis.com/auth/analytics.readonly`. Keep the system clock synchronized and disable credential/body tracing in HTTP middleware.
- Clones share the HTTP pool and token cache. Concurrent reports serialize token exchanges; tokens renew within 20 seconds of expiry. Separately constructed clients have separate token caches.
- Authentication and report failures propagate. No request retries automatically; the application chooses its backoff policy.

Framework cache
-----------------------------------------------------------------------------------------------------

- Pass a `laravel::cache::Repository` and `Duration` to `with_cache`. Zero disables caching.
- Use cache repositories inside an application scope, request, or command. The framework panics outside its application context.
- Keys separate service accounts, token and report origins, properties, result types, query options, dates, limits, and offsets.
- Successful empty reports are cached. Errors and partially fetched reports are not. Cache errors propagate.
- The memory store is process-local. Configure a shared store for multi-process deployments. Cache expiry uses the framework clock; OAuth expiry uses real time.
- Applications own stale-on-error and refresh coordination policies.

 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)
