Looking to hire Laravel developers? Try LaraJobs

laravel-sibling-cookies maintained by knvillena

Description
Per-app XSRF and remember-me cookie names for Laravel apps that share a parent cookie domain, plus a setup checker.
Author
Last update
2026/11/28 15:47 (dev-main)
License
Downloads
4

Comments
comments powered by Disqus

Laravel Sibling Cookies

Per-app XSRF and remember-me cookie names for Laravel 13 apps that share a parent cookie domain, plus an Artisan setup checker.

The problem

When multiple Laravel apps live under one parent domain and set SESSION_DOMAIN=.example.test so their SPAs can read cookies, every app issues cookies with the same default names to the same domain. Each app encrypts its cookies with its own APP_KEY, so one app's cookies overwrite or break the other's.

Cookie Default name Symptom when shared
XSRF token XSRF-TOKEN Sibling app overwrites the cookie with its own encrypted token; writes on the first app fail with 419 CSRF token mismatch when Laravel checks the token.
Remember-me remember_web_<sha1> Identical in every app using the web guard. Signing in with "remember me" on one app overwrites the other app's cookie, silently dropping remember-me.
Session laravel_session Collides if APP_NAME was never changed. Set a unique APP_NAME or SESSION_COOKIE per app.

For example, suppose two SPAs share .example.test:

  • App 1: frontend at https://app1.example.test, API at https://app1-api.example.test, SESSION_DOMAIN=.example.test
  • App 2: frontend at https://app2.example.test, API at https://app2-api.example.test, SESSION_DOMAIN=.example.test

With this package installed in both backends, set XSRF_COOKIE=app1_xsrf in App 1 and XSRF_COOKIE=app2_xsrf in App 2, and configure each frontend to read its matching cookie name. Remember-me cookies are automatically prefixed per app (app1_remember_web, app2_remember_web).

A sibling-host 419 clears after a GET through that API (or /sanctum/csrf-cookie) re-issues the cookie. In nested cookie domains (for example .example.test and .staging.example.test), the deeper app can end up seeing two XSRF-TOKEN cookies at once and stay stuck on 419 until cookies are cleared. To spot this, open DevTools → Application → Cookies and look for two XSRF-TOKEN rows with different Domain values.

Do you need this?

Same-host HTTPS apps (serving the page and API from one host, such as Inertia or Blade with axios) do not get the XSRF 419 in browsers that send Sec-Fetch-Site (tested on Chromium), because Laravel 13 accepts Sec-Fetch-Site: same-origin without checking the CSRF token.

Who needs it

For the XSRF cookie name:

  • A SPA whose API is on a sibling host (app1.example.test calling app1-api.example.test), unless allowSameSite is enabled.
  • Nested cookie domains (.example.test and .staging.example.test) with the API on a sibling host.
  • Plain-HTTP local development on non-localhost hosts (such as http://myapp.test), where Chromium sends no Sec-Fetch-Site header and Laravel checks the token.
  • SPA and API on different localhost ports: Chromium sends Sec-Fetch-Site: same-site, so Laravel checks the token, and cookies are not isolated by port.
  • Apps that do not want to trust every sibling subdomain (for example, setups with user-content subdomains or third-party apps under the same parent domain).

For the remember-me cookie name:

  • Any apps that share a cookie domain and use "remember me". allowSameSite does not affect remember-me cookies.

Who does not need it

  • One app per registrable domain, or apps that do not set SESSION_DOMAIN and do not share a host.
  • APIs that use only bearer tokens (no cookies).
  • For the XSRF part only: apps serving page and API from one HTTPS host in browsers that send Sec-Fetch-Site.
  • HTTPS-only setups that accept preventRequestForgery(allowSameSite: true) and do not use remember-me. With allowSameSite: true, Laravel accepts Sec-Fetch-Site: same-site without checking the CSRF token, which avoids the sibling-host 419. The trade-off is that every sibling subdomain is trusted to make state-changing requests, it only works over HTTPS or localhost (where browsers send Sec-Fetch-Site), and it does nothing for remember-me cookie collisions.

Requirements

  • PHP 8.3+
  • Laravel 13
  • Laravel Sanctum 4

Install

composer require knvillena/laravel-sibling-cookies

Optionally publish the config file:

php artisan vendor:publish --tag=sibling-cookies-config

Configure

Set XSRF_COOKIE (and optionally REMEMBER_COOKIE) in .env and .env.example:

APP_NAME="App One"
SESSION_DOMAIN=.example.test
SESSION_COOKIE=app1_session
XSRF_COOKIE=app1_xsrf
REMEMBER_COOKIE=app1_remember
  • XSRF_COOKIE defaults to XSRF-TOKEN so installing the package does not break your frontend before both sides are updated.
  • REMEMBER_COOKIE defaults to Str::slug(APP_NAME, '_') . '_remember', with _<guard> appended (for example app_one_remember_web).
  • Make sure APP_NAME / SESSION_COOKIE are unique across apps. Environments of the same app on one parent domain (such as staging and production) share APP_NAME by default, so give each environment its own XSRF_COOKIE, REMEMBER_COOKIE and SESSION_COOKIE.
  • If you cache configuration, run php artisan config:cache after changing env values.

Frontend

Search your frontend codebase for XSRF-TOKEN and update every occurrence to read from an environment variable (for example VITE_XSRF_COOKIE or NEXT_PUBLIC_XSRF_COOKIE) matching the backend's XSRF_COOKIE:

grep -rn "XSRF-TOKEN"

The request header name stays X-XSRF-TOKEN; only the cookie name changes.

axios

Configure every axios instance you create (not just axios.defaults):

import axios from 'axios';

export const api = axios.create({
    baseURL: import.meta.env.VITE_API_URL,
    withCredentials: true,
    withXSRFToken: true, // required for cross-origin sibling hosts
    xsrfCookieName: import.meta.env.VITE_XSRF_COOKIE ?? 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
});

fetch / ofetch / ky

Read the cookie by the configured name, decodeURIComponent it, and send it in X-XSRF-TOKEN with credentials: 'include':

function getCookie(name) {
    const prefix = `${name}=`;
    const match = document.cookie
        .split('; ')
        .find((row) => row.startsWith(prefix));

    return match ? decodeURIComponent(match.slice(prefix.length)) : null;
}

await fetch(`${API_URL}/api/items`, {
    method: 'POST',
    credentials: 'include',
    headers: {
        'Content-Type': 'application/json',
        'X-XSRF-TOKEN': getCookie(import.meta.env.VITE_XSRF_COOKIE ?? 'XSRF-TOKEN') ?? '',
    },
    body: JSON.stringify({ name: 'Example' }),
});

Other frontend integrations

  • Nuxt / Next Sanctum modules: set the module's CSRF cookie name option to match XSRF_COOKIE.
  • Server-side proxies / BFFs / SSR: forward the renamed cookie when proxying requests or reading the token on the server.
  • Laravel Echo / broadcasting:
    • If broadcast auth routes run in the web group, Broadcast::routes() excludes CSRF via withoutMiddleware(), so nothing changes.
    • If broadcast auth routes run under api / auth:sanctum through Sanctum's stateful pipeline, they are CSRF-checked because route-level exclusions do not reach Sanctum's inner pipeline. Configure Echo with a custom authorizer that posts through your configured axios instance (or sends X-XSRF-TOKEN from the renamed cookie).
  • Inertia: configure xsrfCookieName on the axios instance Inertia uses.
  • Unaffected: Blade forms using @csrf / _token, <meta> X-CSRF-TOKEN, and the remember-me cookie (which is HttpOnly).

What the package changes

In SiblingCookiesServiceProvider::register():

  • Binds Illuminate\Foundation\Http\Middleware\PreventRequestForgery, ValidateCsrfToken and VerifyCsrfToken to Knvillena\SiblingCookies\Http\Middleware\SiblingPreventRequestForgery. This covers both the web middleware group and Sanctum's stateful pipeline without editing bootstrap/app.php or config/sanctum.php.
  • Extends the built-in session auth guard driver with Knvillena\SiblingCookies\Auth\SiblingSessionGuard.
  • Preserves SessionGuard's session key (login_<guard>_<sha1(SessionGuard::class)>) so existing logged-in sessions survive the upgrade.
  • Nothing else is touched: preventRequestForgery(except:, allowSameSite:, originOnly:), withoutMiddleware(PreventRequestForgery::class), config:cache, and Sanctum's AuthenticateSession all keep working unchanged.

If you use your own CSRF middleware subclass (for example App\Http\Middleware\VerifyCsrfToken), extend Knvillena\SiblingCookies\Http\Middleware\SiblingPreventRequestForgery instead of PreventRequestForgery.

Optional explicit wiring

If you prefer wiring the CSRF middleware explicitly instead of relying on container bindings, replace it in bootstrap/app.php and set it in config/sanctum.php:

// bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
    $middleware->web(replace: [
        \Illuminate\Foundation\Http\Middleware\PreventRequestForgery::class => \Knvillena\SiblingCookies\Http\Middleware\SiblingPreventRequestForgery::class,
    ]);
})
// config/sanctum.php
'middleware' => [
    'validate_csrf_token' => \Knvillena\SiblingCookies\Http\Middleware\SiblingPreventRequestForgery::class,
    // ...
],

Check your setup

Run the built-in Artisan checker against your frontend origin(s) (defaults to config('app.frontend_url')):

php artisan sibling-cookies:check --origin=https://app1.example.test

Sample output:

  domain.app App host app1-api.example.test matches session domain example.test .... PASS
  domain.frontend SPA at https://app1.example.test can read cookies for example.test PASS
  INFO  domain.shared Cookies are shared with every host under example.test; names below must be unique per app.
  xsrf.wiring CSRF middleware resolves to SiblingPreventRequestForgery ............. PASS
  names.xsrf-default XSRF cookie name is app1_xsrf ................................. PASS
  names.app-name Session and remember cookie names are not using the default APP_NAME PASS
  names.guards All session guards use SiblingSessionGuard .......................... PASS
  names.unique Session, XSRF and remember cookie names are distinct ................ PASS
  flags.secure Session secure flag matches app.url scheme .......................... PASS
  flags.same-site Session SameSite is lax .......................................... PASS
  sanctum.stateful Sanctum stateful domains configured (1) ......................... PASS
  sanctum.origin https://app1.example.test is stateful ............................. PASS
  cors.credentials CORS supports_credentials is enabled ............................ PASS
  cors.origin https://app1.example.test is allowed by CORS ......................... PASS
  cors.headers CORS allows X-XSRF-TOKEN header ..................................... PASS
  cors.csrf-path CORS covers /sanctum/csrf-cookie .................................. PASS
  cors.api-paths CORS covers all api routes ........................................ PASS

  INFO  Effective cookie names: session=app1_session, xsrf=app1_xsrf, remember=web=app1_remember_web.
  INFO  This command sees only this app's configuration. Run it in every app on example.test and make sure no two apps print the same name.

Exit codes:

  • 0: all checks passed (warnings do not fail the command).
  • 1: one or more checks reported FAIL.

The checker inspects only the current app's configuration. Run it in every app sharing the domain and verify that no two apps print the same cookie names.

Upgrading / deploying

  • XSRF cookie:
    1. Set the same cookie name in both backend (XSRF_COOKIE) and frontend.
    2. Deploy the backend first, then the frontend, or deploy both together.
    3. If the frontend deploys first, it reads a cookie that does not exist yet and writes fail with 419.
    4. If only the backend is deployed, the old XSRF-TOKEN cookie keeps working until the session token regenerates (next login, remember-me sign-in, or expiry), after which writes return 419.
    5. The old XSRF-TOKEN cookie expires after session.lifetime; no manual cleanup is needed.
  • Remember-me cookie:
    • Active logged-in sessions survive the upgrade unchanged.
    • Users whose session has expired and who rely only on remember-me must sign in once.
    • The old remember_web_<sha1> cookie is ignored and left to expire naturally (up to 400 days). The package intentionally does not delete it because it may belong to a sibling app.
  • Session cookie: the package does not rename the session cookie. If two apps share laravel_session, changing SESSION_COOKIE signs users in that app out once.
  • Config caching: run php artisan config:cache after updating env values.

Local development

  • Ports share cookies: http://localhost:3000 and http://localhost:8000 share cookies in browsers, so XSRF-TOKEN can still collide across local apps even without SESSION_DOMAIN.
  • Plain HTTP on .test hosts: Chromium does not send Sec-Fetch-Site over plain HTTP on .test domains, so Laravel enforces the CSRF token check there.
  • SESSION_DOMAIN on localhost: leave SESSION_DOMAIN empty on localhost (single-label domains like SESSION_DOMAIN=localhost may be rejected by browsers), or use a real multi-label local domain such as .example.test.

Testing your app

Laravel skips CSRF verification when APP_ENV=testing (runningInConsole() && runningUnitTests()), although it still attaches the XSRF cookie to responses. To test 419 responses or X-XSRF-TOKEN validation in a feature test, temporarily switch the environment:

$this->app['env'] = 'local';

$this->withSession(['_token' => 'test-token'])
    ->post('/endpoint')
    ->assertStatus(419);

License

MIT. See LICENSE.