knvillena / laravel-sibling-cookies
Per-app XSRF and remember-me cookie names for Laravel apps that share a parent cookie domain, plus a setup checker.
Package info
github.com/knvillena/laravel-sibling-cookies
pkg:composer/knvillena/laravel-sibling-cookies
Requires
- php: ^8.3
- laravel/framework: ^13.0
- laravel/sanctum: ^4.0
Requires (Dev)
- orchestra/testbench: ^11.0
- pestphp/pest: ^4.4|^5.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-28 14:47:53 UTC
README
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 athttps://app1-api.example.test,SESSION_DOMAIN=.example.test - App 2: frontend at
https://app2.example.test, API athttps://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.testcallingapp1-api.example.test), unlessallowSameSiteis enabled. - Nested cookie domains (
.example.testand.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 noSec-Fetch-Siteheader and Laravel checks the token. - SPA and API on different
localhostports: Chromium sendsSec-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".
allowSameSitedoes not affect remember-me cookies.
Who does not need it
- One app per registrable domain, or apps that do not set
SESSION_DOMAINand 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. WithallowSameSite: true, Laravel acceptsSec-Fetch-Site: same-sitewithout 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 orlocalhost(where browsers sendSec-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_COOKIEdefaults toXSRF-TOKENso installing the package does not break your frontend before both sides are updated.REMEMBER_COOKIEdefaults toStr::slug(APP_NAME, '_') . '_remember', with_<guard>appended (for exampleapp_one_remember_web).- Make sure
APP_NAME/SESSION_COOKIEare unique across apps. Environments of the same app on one parent domain (such as staging and production) shareAPP_NAMEby default, so give each environment its ownXSRF_COOKIE,REMEMBER_COOKIEandSESSION_COOKIE. - If you cache configuration, run
php artisan config:cacheafter 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
webgroup,Broadcast::routes()excludes CSRF viawithoutMiddleware(), so nothing changes. - If broadcast auth routes run under
api/auth:sanctumthrough Sanctum's stateful pipeline, they are CSRF-checked because route-level exclusions do not reach Sanctum's inner pipeline. Configure Echo with a customauthorizerthat posts through your configured axios instance (or sendsX-XSRF-TOKENfrom the renamed cookie).
- If broadcast auth routes run in the
- Inertia: configure
xsrfCookieNameon the axios instance Inertia uses. - Unaffected: Blade forms using
@csrf/_token,<meta>X-CSRF-TOKEN, and the remember-me cookie (which isHttpOnly).
What the package changes
In SiblingCookiesServiceProvider::register():
- Binds
Illuminate\Foundation\Http\Middleware\PreventRequestForgery,ValidateCsrfTokenandVerifyCsrfTokentoKnvillena\SiblingCookies\Http\Middleware\SiblingPreventRequestForgery. This covers both thewebmiddleware group and Sanctum's stateful pipeline without editingbootstrap/app.phporconfig/sanctum.php. - Extends the built-in
sessionauth guard driver withKnvillena\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'sAuthenticateSessionall 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 reportedFAIL.
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:
- Set the same cookie name in both backend (
XSRF_COOKIE) and frontend. - Deploy the backend first, then the frontend, or deploy both together.
- If the frontend deploys first, it reads a cookie that does not exist yet and writes fail with 419.
- If only the backend is deployed, the old
XSRF-TOKENcookie keeps working until the session token regenerates (next login, remember-me sign-in, or expiry), after which writes return 419. - The old
XSRF-TOKENcookie expires aftersession.lifetime; no manual cleanup is needed.
- Set the same cookie name in both backend (
- 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, changingSESSION_COOKIEsigns users in that app out once. - Config caching: run
php artisan config:cacheafter updating env values.
Local development
- Ports share cookies:
http://localhost:3000andhttp://localhost:8000share cookies in browsers, soXSRF-TOKENcan still collide across local apps even withoutSESSION_DOMAIN. - Plain HTTP on
.testhosts: Chromium does not sendSec-Fetch-Siteover plain HTTP on.testdomains, so Laravel enforces the CSRF token check there. SESSION_DOMAINonlocalhost: leaveSESSION_DOMAINempty onlocalhost(single-label domains likeSESSION_DOMAIN=localhostmay 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.