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

ms1987's avatar

Stateless API with JWT cookie invalidation

Hi All,

I have been playing for a couple of days with a stateless Laravel API with JWT based authentication, where I store the token in a cookie.

All is well, except for the cookie (in)validation...

I set my cookie like so

Cookie::queue(Cookies::NAME, $token, (int) env('COOKIE_VALIDITY'), Cookies::PATH, env('COOKIE_DOMAIN'), env('COOKIE_SECURE'), Cookies::HTTPONLY, Cookies::RAW, Cookies::SAMESITE);

$redirectUrl = $request->query('redirectTo') ?? route('home');
 return redirect($redirectUrl);

This works, it does set the cookie. However, my cookie Expires/Max-Age seems to be one hour behind, always. 2019-10-12T08:51:35.737Z (when it is actually 9:51)

The cookies gets sent correctly on all subsequent requests though.

The biggest problem however, is cookie invalidation. My logout action looks like this

return redirect('/login')->withCookies([Cookie::forget(Cookies::NAME)]);

The action gets called to, but the cookie remains unchanged. I also tried with the cookie()->forget() helper, this has the same result.

Any clues to what I am doing wrong here?

Ps: I do see that laravel by default adds a session cookie as well, I suppose this is normal, due to the fact that I reach the site as an anonymous user and therefor receive a session for that? Im asking because the challange for me is to have a full stateless API that only uses server side rendered login page and then redirects back to some kind of SPA.

All help is much appreciated.

0 likes
1 reply
ms1987's avatar
ms1987
OP
Best Answer
Level 1

To whom it may concern, I have found the problem. Apparently, specifying the cookie name is not sufficient.

return redirect('/login')->withCookies([Cookie::forget(Cookies::NAME, Cookies::PATH, env('COOKIE_DOMAIN'))]);

Works perfectly.

Please or to participate in this conversation.