laravelsession-cookieslaravel-session

How can I prevent Laravel from setting a session cookie when the user is not auth?


By default, Laravel sets a Cookie called [APP_NAME]_session on every request. It's used for features as redirect()->back().

This cookie prevents my cache mechanism to work properly (FastCGI, Varnish, you name it)

If I'm one hundred percent sure I won't need it, is there a way to remove this cookie when the user is not auth, without preventing them to log in as usual ?

I'd like to show a different menu when my user is authed, so I can't apply a different middleware on some routes.


Solution

  • I created a new class, which extends the StartSession Middleware (referenced in app/Middleware/Kernel.php, inside the web group).

    <?php
    
    namespace App\Http\Middleware;
    
    use Illuminate\Contracts\Session\Session;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Cookie;
    use Symfony\Component\HttpFoundation\Response;
    
    class StartSession extends \Illuminate\Session\Middleware\StartSession
    {
        /**
         * Start the session for the given request.
         *
         * @param Request $request
         * @param  Session  $session
         * @return Session
         */
        protected function startSession(Request $request, $session): Session
        {
            return tap($session, function ($session) use ($request) {
                $session->setRequestOnHandler($request);
    
                if (Cookie::get(config("session.cookie"))) {
                    $session->start();
                }
            });
        }
    
        /**
         * Add the session cookie to the application response.
         *
         * @param Response $response
         * @param Session $session
         * @return void
         */
        protected function addCookieToResponse(Response $response, Session $session)
        {
            if (!auth()->check()) {
                return;
            }
    
            if ($this->sessionIsPersistent($config = $this->manager->getSessionConfig())) {
                $response->headers->setCookie(new \Symfony\Component\HttpFoundation\Cookie(
                    $session->getName(), $session->getId(), $this->getCookieExpirationDate(),
                    $config['path'], $config['domain'], $config['secure'] ?? false,
                    $config['http_only'] ?? true, false, $config['same_site'] ?? null
                ));
            }
        }
    }
    

    The two importants part are :

    if (Cookie::get(config("session.cookie"))) {
        $session->start();
    }
    

    This part prevents the session from being created when the user wasn't already authed.

    if (!auth()->check()) {
        return;
    }
    

    This part prevents Laravel from setting the cookie as long as the user is not authed.