Laravel 6 Session and CSRF Cookies Not Being Set -- New Entry in Session DB for Each Page Load

Viewed 1817

I'm new to Laravel and have a Laravel 6 app where the session isn't acting as expected. It's causing a 419 - page expired error anytime I submit a form.

@csrf is included with every form, so that's not the issue.

Instead, what I'm seeing is that neither the Session cookie nor the XSRF-TOKEN cookie are being set in the browser. However, I do see the session creating a new ID in the database for every page load.

The sessions.php config file is the default one:

    'driver' => env('SESSION_DRIVER', 'file'),
    'expire_on_close' => false,
    'encrypt' => false,
    'files' => storage_path('framework/sessions'),
    'connection' => env('SESSION_CONNECTION', null),
    'table' => 'sessions',
    'store' => env('SESSION_STORE', null),
    'cookie' => env(
        'SESSION_COOKIE',
        Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
    ),
    'path' => '/',
    'domain' => env('SESSION_DOMAIN', null),
    'secure' => env('SESSION_SECURE_COOKIE', false),
    'http_only' => true,
    'same_site' => null,

The VerifyCsrfToken.php Middleware file is the default one:

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * Indicates whether the XSRF-TOKEN cookie should be set on the response.
     *
     * @var bool
     */
    protected $addHttpCookie = true;

    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        //
    ];
}

The only session variables I've changed in the .env are:

SESSION_DRIVER=database
SESSION_COOKIE=lsession
SESSION_LIFETIME=43200

Other than confirming the @crsf token is included in every form, I've tried:

  • testing in multiple browsers
  • restarting my machine and trying again
  • clearing the cache with php artisan cache:clear && php artisan config:cache
  • switching back and forth between file and database session drivers

None of it works.

What else could be causing the session/csrf cookies to not be set?

Thanks so much in advance!

2 Answers

It wasn't anything to do with the form. It was a bonehead move on my end, so posting this answer in case anyone else stumbles upon the same issue.

I had a space before an opening <?php tag in one of my files. That space was being sent to the browser before the HTTP header, so none of the cookies were ever being set.

Doh!

In the <head>, preferably in your head.blade.php, which is included in every Blade file you load, try adding:

<meta name="csrf-token" content="{{ csrf_token() }}">
Related