Laravel adds two cookies by default when you create a fresh project.
- XSRF-TOKEN ( stores current CSRF token )
- laravel_session ( stores session data ). Read more
These cookies have encrypted data. Laravel takes care of encryption and decryption for us.
Where to find their implementation?
Laravel comes with many middlewares out of the box. You can see them in App/Http/Kernel.php
.
Two such middleware classes are:
\App\Http\Middleware\VerifyCsrfToken::class
\Illuminate\Session\Middleware\StartSession::class
VerifyCsrfToken::class
extend a base class of same name.
Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class
Above base class from framework contains the implementation fo XSRF-TOKEN cookie.
XSRF-TOKEN cookie implementation
/**
* Add the CSRF token to the response cookies.
*
* @param \Illuminate\Http\Request $request
* @param \Symfony\Component\HttpFoundation\Response $response
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function addCookieToResponse($request, $response)
{
$config = config('session');
if ($response instanceof Responsable) {
$response = $response->toResponse($request);
}
$response->headers->setCookie(
new Cookie(
'XSRF-TOKEN', $request->session()->token(), $this->availableAt(60 * $config['lifetime']),
$config['path'], $config['domain'], $config['secure'], false, false, $config['same_site'] ?? null
)
);
return $response;
}
Session cookie implementation
\Illuminate\Session\Middleware\StartSession::class
contains the same method as above.
/**
* Add the session cookie to the application response.
*
* @param \Symfony\Component\HttpFoundation\Response $response
* @param \Illuminate\Contracts\Session\Session $session
* @return void
*/
protected function addCookieToResponse(Response $response, Session $session)
{
if ($this->sessionIsPersistent($config = $this->manager->getSessionConfig())) {
$response->headers->setCookie(new Cookie(
$session->getName(), $session->getId(), $this->getCookieExpirationDate(),
$config['path'], $config['domain'], $config['secure'] ?? false,
$config['http_only'] ?? true, false, $config['same_site'] ?? null
));
}
}
Let me know if I missed a cookie 🍪 Happy coding with Laravel.
Top comments (3)
I'm actually getting 3 cookies:
Is this a fresh Laravel application?
I was actually facing this problem and tried to debug it.
Are you using any 3rd party packages? 🤔
Ah, it was because I had SESSION_DRIVER set to 'cookie', so of course it's passing back the session data in a cookie, changing to 'file' will keep all this server side.