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

lmartins's avatar

Session expires while doing API requests

Hi,

I've seen something weird happening on a project I'm working on. This project has a frontend that is composed of both regular server-side rendered pages, but also a few components that interact with an API provided by Laravel.

This API uses the same auth middleware as the main routes that render the "base" pages, but unlike full page loads the ajax requests don't seem to keep the session alive.

For policy reasons, project requires to have a short session time of 15 minutes, and one of the components of the project is a quiz like ui, where users can spend more than that interacting with it without doing a full page load. Those interactions make API requests, but what I've noticed was with such requests going out, the user session still expires.

Is there a way around this?

0 likes
2 replies
Snapey's avatar

If you are expecting to use and maintain the session then you should be using routes in web.php for your api and sending the session token with each request.

Calls into routes in the api.php file dont use sessions and unless you are using another authentication method such as JWT then they are unauthenticated and could be coming from anywhere

Since these api calls are not linked to the session, then, yes the session will expire

If these api calls are actually ajax calls from an authenticated user's browser then just moving them into web.php will fix the problem

1 like
lmartins's avatar

Ah interesting. These API routes still go through the auth:api middleware, so I though that would be enough to maintain the session. I'll test your suggestion, thank you!

Please or to participate in this conversation.