This website collects cookies to deliver better user experience
Laravel Sessions with Vue.js
Laravel Sessions with Vue.js
I'm working on an app that uses a Laravel REST API on the back-end and Vue.js 3 with Typescript on the front-end. My issue was keeping the session after a new request. I got it working with Postman, but it took me a while to figure out why it wasn't working with Vue.js. I didn't find much info on the web (maybe my search queries were poor) and what I found was mostly about using Laravel Passport or Sanctum, but that's used with authentication and not necessary for my app. The session id gets stored in a cookie, but I didn't know in the beginning that Laravel actually handles setting the cookie for you when things are set up properly. These are the steps taken that ended up working.
Laravel:
1) In Kernel.php add StartSession to the middleware:
2) Set the session when calling the store endpoint in SelectController:
public function store(SelectionRequest $request)
{
$userSelection = $this->objectRepository->getObjectByName($request->selection);
Session::flush();
Session::put("selection", $userSelection);
...
}
3) In config/cors.php one needs to set allow supporting credentials:
'supports_credentials' => true,
Vue.js with Typescript
After comparing the header in Laravel of the Postman request and the Vue.js request I finally figured out that I needed to add credentials: 'include' to the Post request as Vue.js otherwise didn't send the cookie. This is the blog post that saved me: http://niraj-meegama.info/vue-js-cookie-not-set-request-headers (thanks Niraj!).
I have this helper function in a TypeScript file called http.ts: