Local Development With Laravel and NextJS to get around the 419 SameSite Error

I took a couple of days Googling and trying different suggestions on how to get my NextJS development environment working with my Laravel backend API. This turned out to be a few settings that needed to be configured.

The Problem

I want to configure Axios in my NextJS app to talk to Laravel on the backend. I’m using Laravel Sanctum for Authentication, but making requests to my server returned a 419 error. Initially I was sending a GET request to /sanctum/csrf-cookie to get my XSRF-Token, but the error response would cause the browser to refuse to save the cookie. I’m writing a multi-tenant app that uses the subdomain for finding the correct tenant and connecting to that database. NextJS launches it’s development server on localhost:3000, but I was attempting to send requests to http://tenant.myapp.com. Part of my problem was that I had configured the Laravel domain as the baseURL in my Axios configuration.

The Solution

To get this working properly, I need to send my API requests to the NextJS development server and allow the Rewrites configuration to proxy this request to the Laravel server. I configured the Rewrite instuctions in the next.config.js file as shown.

image

So I removed the baseURL parameter from my axios configuration, as this will allow the requests now to go to the NodeJS server and then redirect to Laravel.

SameSite was having an issue, but by setting the session.same_site Laravel config option to null, I was able to get rid of that.

And being that I had a SESSION_DOMAIN .env set, I found that I needed to remove that as well to allow the broswer to write my Laravel session cookie.

To get Authentication to work, I also had to add localhost in my .env SANCTUM_STATEFUL_DOMAINS because I was getting a server 500 error that said, “Session store not set on request.”.

Written on May 30, 2022