Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Marre86's avatar

Conflicting session middlewares for 'web' and 'api'

I am working on ecommerce Laravel project. I decided to use darryldecode Cart package for my Cart.

The problem is that it stores its data in session. And it works smoothly as far as I deal with 'web' part of my app.

But when I implement my API, I need to add Illuminate\Session\Middleware\StartSession::class, in my Kernel.php, in'api' middlewareGroups, because otherwise data isn't stored in the Cart.

But inclusion of this line in Kernel.php triggers a problem with web part of my application. When I add an item in the Cart in my browser - 419 Page expired pops up.

So, it seems that these two session-related middlewares are conflicting when I use them both. Please, help me to find a solution...

0 likes
4 replies
Snapey's avatar

Why do you need to put API routes in the API file ?

If the requests are coming from a browser that has an authenticated user, put the routes in web.php

Marre86's avatar

@Snapey why do I need to keep API routes in the API file?

  1. Because it is supposed to be like that
  2. Because division web routes and api routes in two files - elegant and logic
  3. Because my WEB routes file doesn't look like a mess if I unload all my api routes there.
  4. Beacuse I don't have to manually input prefix to my api routes ('api/v1/') if I keep them in API route file

I tried it, though, it seems to work. but only if I remove \App\Http\Middleware\VerifyCsrfToken::class, from "web" middlewareGroup in Kernel.php. It seems it can cause some safety issues, right?

Definetily don't like this approach. It smells like unwashed rat. Please help me with a better idea.

Marre86's avatar

Meanwhile I found the solution. All I had to do was just remove Illuminate\Session\Middleware\StartSession::class from 'web' middlewareGroup and insert into into global middleware stack...

Snapey's avatar

@Marre86

Because it is supposed to be like that

Yes api routes should be stateless

but then you modify it to be stateful

As for segregation and tidyness, you could easily start a new file and add it under web middleware. what you have now is confusing for future development since api is now stateful

And yes, Post routes from authenticated sessions are vulnerable to CRSF attacks so you should not bypass it

1 like

Please or to participate in this conversation.