PHPackages                             trivolink/unified-api - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. trivolink/unified-api

ActiveLibrary[HTTP &amp; Networking](/categories/http)

trivolink/unified-api
=====================

Unified JSON API contract for Inertia-powered Laravel backends — serve web, mobile and desktop clients from one set of routes.

v1.0.1(today)05↑2900%MITPHPPHP ^8.2CI passing

Since Aug 27Pushed todayCompare

[ Source](https://github.com/trivolink/unified-api)[ Packagist](https://packagist.org/packages/trivolink/unified-api)[ Docs](https://github.com/trivolink/unified-api)[ RSS](/packages/trivolink-unified-api/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (5)Versions (3)Used By (0)

trivolink/unified-api
=====================

[](#trivolinkunified-api)

[![Tests](https://github.com/trivolink/unified-api/actions/workflows/tests.yml/badge.svg)](https://github.com/trivolink/unified-api/actions/workflows/tests.yml)[![Packagist Version](https://camo.githubusercontent.com/07486ccfb89ef17e7661287471a245eb077249b5c2335a35a8d6d32a38188df4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f747269766f6c696e6b2f756e69666965642d617069)](https://packagist.org/packages/trivolink/unified-api)[![License](https://camo.githubusercontent.com/aa824d6d63c1dc63f4103f4fa7156bb6c346a7c2ebacdec2c04726b722b4f824/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f747269766f6c696e6b2f756e69666965642d617069)](LICENSE)

One Laravel backend, three clients. Web keeps Inertia SSR HTML (SPA + SEO); mobile and desktop apps receive a standardized JSON envelope — from the same URLs and the same controllers.

New here and deciding? Read [docs/ANALYSIS.md](docs/ANALYSIS.md) — the problem, the alternatives compared, honest trade-offs, and when this package is the wrong tool.

Response matrix
---------------

[](#response-matrix)

RequestResponse`Accept: text/html`Inertia SSR HTML (unchanged)`X-Inertia: true`Inertia page object (unchanged SPA navigation)`Accept: application/json`Envelope: `{data, meta, message, version}````
{
    "data": { "users": 5, "auth": { "user": "Tania" } },
    "meta": { "component": "Dashboard", "url": "/dashboard" },
    "message": "Profile updated.",
    "version": "v1"
}
```

- `data` — fully resolved page props (shared + page props, eager: deferred/optional props included)
- `meta` — `component` (screen hint) and `url`, each disableable via `unified-api.meta.*`; always a JSON object, never an array
- `message` — flashed `message` key when present, else `null`
- `version` — API contract version (`UNIFIED_API_VERSION`, default `v1`)

POST endpoints that redirect respond `200` (configurable) with `meta.redirect` instead of a 302/303, so native clients never silently follow redirects. Validation and HTTP errors keep their status code and arrive wrapped: `{data: null, message, errors?, version}` — including exception-rendered responses (401 unauthenticated, 404, validation 422, throttle 429, server 5xx).

Install
-------

[](#install)

```
composer require trivolink/unified-api
```

Publish config (optional):

```
php artisan vendor:publish --tag=unified-api-config
```

Auth: Sanctum dual-mode
-----------------------

[](#auth-sanctum-dual-mode)

```
composer require laravel/sanctum
php artisan install:api
```

Swap the auth middleware on your shared (web) route group:

```
Route::middleware(['auth:sanctum', ...]) // was: 'auth'
```

Sanctum's guard checks `Authorization: Bearer ` first (issue personal access tokens to your mobile/desktop apps) and falls back to the web session for browsers — your existing Fortify/session flow keeps working untouched.

### Getting a first token: `POST /api/token`

[](#getting-a-first-token-post-apitoken)

Mobile/desktop clients bootstrap their bearer token with an email + password exchange (stateless, throttled to 5/min by default):

```
POST /api/token
{"email": "tania@example.com", "password": "...", "device_name": "iphone-15"}
```

```
{"data": {"token": "1|abc123..."}, "meta": {}, "message": null, "version": "v1"}
```

Wrong credentials get the 422 envelope with `errors.email`. The route requires the user model to use `Laravel\Sanctum\HasApiTokens` and can be configured or disabled under `unified-api.token_endpoint`:

```
'token_endpoint' => [
    'enabled' => env('UNIFIED_API_TOKEN_ENDPOINT', true),
    'path' => env('UNIFIED_API_TOKEN_PATH', 'api/token'),
    'middleware' => ['throttle:5,1'],
],
```

CSRF
----

[](#csrf)

Browser POSTs still require CSRF tokens (Inertia sends them automatically). Stateless JSON clients must not be blocked by CSRF, so swap the framework middleware in `bootstrap/app.php`:

```
->withMiddleware(function (Middleware $middleware) {
    $middleware->validateCsrfTokens(except: [
        // ... your existing exceptions
    ]);
    // Laravel 13+ (the web group ships PreventRequestForgery):
    $middleware->replaceInGroup(
        'web',
        \Illuminate\Foundation\Http\Middleware\PreventRequestForgery::class,
        \Trivium\UnifiedApi\Middleware\ValidateCsrfTokenExceptApiClients::class,
    );
    // On Laravel 11-12, target ValidateCsrfToken::class instead.
})
```

This is CSRF-safe: the exemption requires the custom `Accept: application/json` header, which cross-site forms can never set and cross-origin fetches cannot send without passing a CORS preflight. Bearer-authenticated requests carry no ambient cookie credentials for an attacker to ride.

Mobile/Desktop client checklist
-------------------------------

[](#mobiledesktop-client-checklist)

1. Send `Accept: application/json` on every request.
2. Bootstrap: `POST /api/token` with email + password, store `data.token`.
3. Authenticate every request with `Authorization: Bearer `.
4. Read `version`; when it differs from your compiled-in contract (e.g. you shipped `v1`, server now sends `v2`), prompt the user to update.
5. On `meta.redirect`, navigate explicitly — do not rely on HTTP redirect following.

Why not just send X-Inertia from mobile?
----------------------------------------

[](#why-not-just-send-x-inertia-from-mobile)

The Inertia page object is a UI protocol, not an API contract: `component` names refer to React/Vue page components the native app does not have, `url`/`version` exist for browser history and asset hashing, and partial-reload/deferred/merge semantics assume the Inertia JS client. The envelope is a stable, minimal contract purpose-built for native consumers.

Testing your app
----------------

[](#testing-your-app)

Everything Inertia offers keeps working (`assertInertia` etc.). For unified clients, assert on the envelope:

```
$this->get('/dashboard', ['Accept' => 'application/json'])
    ->assertOk()
    ->assertJsonPath('version', 'v1')
    ->assertJsonPath('data.users', 5);
```

Contract testing
----------------

[](#contract-testing)

The envelope's `data` is your resolved page props — for native clients, those props ARE the API. Freeze their **shape** with snapshot tests so a web refactor that renames, retypes or drops a prop fails CI instead of silently breaking shipped apps:

```
use function envelopeSnapshot; // global helper, autoloaded

test('dashboard envelope contract', function () {
    $user = User::factory()->create();

    envelopeSnapshot('dashboard', fn () => $this
        ->actingAs($user)
        ->get(route('dashboard'), ['Accept' => 'application/json']));
});
```

The first run writes `tests/Snapshots/UnifiedApi/dashboard.json` (shape only — key tree plus JSON types; values never recorded, so factory data and timestamps cannot flake). Later runs compare. Non-2xx responses fail immediately: error envelopes are not contracts.

When a snapshot diff appears in a PR, the change rule is two lines:

- **additive** (new keys only) — regenerate: `ENVELOPE_SNAPSHOT_UPDATE=1 vendor/bin/pest`
- **breaking** (remove/rename/retype) — bump `UNIFIED_API_VERSION`, update consumers, and regenerate in the same commit

Store the snapshot path override for unusual layouts with `EnvelopeSnapshot::usingSnapshotPath(...)`; the default is `base_path('tests/Snapshots/UnifiedApi')`.

Development
-----------

[](#development)

```
composer install
composer test      # phpunit
composer lint      # pint
```

Before tagging a release, follow [docs/PUBLISHING.md](docs/PUBLISHING.md)(license, metadata, lock handling, CI, Packagist).

###  Health Score

42

—

FairBetter than 88% of packages

Maintenance100

Actively maintained with recent releases

Popularity5

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

0d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/133030649?v=4)[Firoz Anam](/maintainers/firozanam)[@firozanam](https://github.com/firozanam)

---

Top Contributors

[![firozanam](https://avatars.githubusercontent.com/u/133030649?v=4)](https://github.com/firozanam "firozanam (29 commits)")

---

Tags

jsonapilaravelrestmobiledesktopsanctuminertiacontent negotiationinertiajsenvelope

###  Code Quality

TestsPHPUnit

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/trivolink-unified-api/health.svg)

```
[![Health](https://phpackages.com/badges/trivolink-unified-api/health.svg)](https://phpackages.com/packages/trivolink-unified-api)
```

###  Alternatives

[marcin-orlowski/laravel-api-response-builder

Helps building nice, normalized and easy to consume Laravel REST API.

852505.1k4](/packages/marcin-orlowski-laravel-api-response-builder)[erag/laravel-lang-sync-inertia

A powerful Laravel package for syncing and managing language translations across backend and Inertia.js (Vue/React/Svelte) frontends, offering effortless localization, auto-sync features, and smooth multi-language support for modern Laravel applications.

5031.3k](/packages/erag-laravel-lang-sync-inertia)[guanguans/laravel-api-response

Normalize and standardize Laravel API response data structure. - 规范化和标准化 Laravel API 响应数据结构。

486.4k](/packages/guanguans-laravel-api-response)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
