MadMaks's avatar
Level 11

Help with CSRF Error 419 on Different Domains Using Herd on Windows and Next.js Frontend (.test Domain Issue)

I'm encountering a CSRF Error 419 when trying to set up my Laravel backend with Herd on Windows using a .test domain (http://react-backend.test) and a Next.js frontend on http://localhost:3000. Here’s an outline of my setup:

Frontend: Next.js app served at http://localhost:3000 Backend: Laravel app on http://react-backend.test, served by Herd on Windows The error arises because CSRF tokens aren’t being validated properly across the different domains. Here’s what I’ve tried so far:

Environment Variables in Laravel:

SESSION_DOMAIN=react-backend.test SANCTUM_STATEFUL_DOMAINS=localhost:3000 CORS Config in config/cors.php:

Allowed paths include api/*, sanctum/csrf-cookie, login, and register allowed_origins includes http://localhost:3000 supports_credentials is set to true to allow cross-origin cookies. Axios Config in Next.js:

I use initializeCsrf() to retrieve the CSRF token, and I’ve added an Axios interceptor to manually set the X-XSRF-TOKEN header based on the XSRF-TOKEN cookie. Despite these configurations, I keep getting a 419 CSRF error when the Next.js frontend attempts to make authenticated requests to the Laravel backend. The CSRF token is in place, and cookies are being sent, but it seems like something is still missing for cross-domain validation with Herd on Windows.

Does anyone have any additional insights or suggestions on what I could be missing?

0 likes
1 reply
MadMaks's avatar
MadMaks
OP
Best Answer
Level 11

For anyone who are interested in an answer: I found a solution to the CSRF 419 error with a workaround! Instead of using the .test domain (http://react-backend.test), I downloaded PHP and started the Laravel backend using a PHP server at 127.0.0.1:8081. This allowed me to serve the backend locally without the .test domain, which resolved the CSRF validation issues between my Next.js frontend (http://localhost:3000) and Laravel backend.

Here’s a summary of my original setup and the workaround that worked:

Frontend: Next.js app at http://localhost:3000 Backend: Laravel app accessed at 127.0.0.1:8081 using PHP I ran the following command to start the Laravel backend:

php -S 127.0.0.1:8081 -t public I used port 8081 because other common ports were reserved by Herd.

Please or to participate in this conversation.