Authenticate your SPA with Laravel Sanctum where SPA & Laravel API are on two different repositories. In this video, you will learn how to authenticate your NextJS SPA, how to protect the dashboard from unauthorized access & how to configure cors for Laravel correctly.
🤝 You can support me by giving my videos a 👍 & by subscribing to the channel ✔️
-- Next.JS SPA Front-End Source Code --
https://github.com/ggelashvili/nextjs...
-- Laravel Sanctum API Back-End Source Code --
https://github.com/ggelashvili/nextjs...
-- Note --
This works for Laravel versions 7.x & up. If you are trying to do this on earlier versions then make sure to pull in the https://github.com/fruitcake/laravel-... package, this is included in Laravel's core since 7.x.
Also at 3:23, my SESSION_DRIVER is set to cookie. This is not important and it is up to you what session driver you want to use. There were a lot of devs who had issues authenticating their SPAs that were on different ports locally and changing file to cookie was the solution. I had the same issue which is why I have it set to 'cookie'. So if you are having such issues you can try setting driver to the cookie & see if that helps. Note that having SESSION_DRIVER set to a cookie will expose encrypted session to the browser. In production, I recommend using Redis as the session driver which is what I use on my apps.
-- Table of Contents --
00:00 - Intro
00:42 - Install Laravel Sanctum
02:23 - CORS/Session Configuration
04:57 - CSRF Protection
08:02 - Client-Side Login (Keeping User Logged In Using Custom Cookie)
08:50 - Protection Against User Manually Creating Cookie (Axios Interceptors)
10:42 - Server Side Redirect To Prevent Flashing Of Unauthorized Page