DEV Community

Philip Perry
Philip Perry

Posted on

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:

$app->middleware([
    App\Http\Middleware\StartSession::class,
Enter fullscreen mode Exit fullscreen mode

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);
       ...
 }
Enter fullscreen mode Exit fullscreen mode

3) In config/cors.php one needs to set allow supporting credentials:

'supports_credentials' => true,
Enter fullscreen mode Exit fullscreen mode

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:

export async function post<T>(
    request: any,
    body: any
  ): Promise<T> {
    const response = await fetch(process.env.VUE_APP_BACKEND + request, {
      method: 'post',
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Request-Headers': '*',
        'Access-Control-Request-Method': '*',
      },
      credentials: 'include',
      body: JSON.stringify(body)
    });

    return await response.json();
  }
Enter fullscreen mode Exit fullscreen mode

Now everything works. If anything remains unclear or you know of a better way, then please let me know in the comments.

Top comments (0)