Skip to content

Instantly share code, notes, and snippets.

@marianomat
marianomat / Postman-pre-request-script-csrf-token-laravel-sanctum.js
Created October 1, 2023 16:44 — forked from janzikmund/Postman-pre-request-script-csrf-token-laravel-sanctum.js
Postman Pre-Request script to append CSRF token in header for POST requests in Laravel Sanctum authenticated SPA. Requires active environment with {{url}} variable defined for main app domain.
/**
* Postman Pre-Request script to append CSRF token in header for POST requests in Laravel
* Sanctum authenticated SPA. Requires active environment with {{url}} variable defined
* for main app domain.
*
* Postman Interceptor allows appending cookies from browser, but Laravel CSRF middleware
* only validates CSRF in headers or in _token form field, not in cookies. Axios automatically
* appends the CSRF from cookie to headers, but Postman cannot access intercepted cookies
* and use them, so we have to do one pre-request to get the CSRF token, store it
* in environment so it can be reused, and then append it to headers.