When building web applications with Laravel, securing user authentication is critical. One powerful and often overlooked way to enhance security is through the proper use of cookies—especially HttpOnly, Secure, and SameSite cookies.

In this post, I'll explore how cookies work in Laravel, how to safely store authentication tokens, and why you should consider using cookies over localStorage.


🔐 Why Cookies Matter for Security

By default, many frontend apps store tokens (like JWTs) in localStorage or sessionStorage. While convenient, this leaves tokens vulnerable to XSS attacks, since JavaScript can access them.

Cookies, especially those marked as HttpOnly, are more secure because:

  • JavaScript cannot read HttpOnly cookies
  • Cookies are automatically sent with each request to the same origin
  • With Secure and SameSite flags, they’re safe against many common attacks

🛠️ Using Cookies in Laravel

Laravel makes working with cookies easy. You can attach cookies to responses and read them from requests with just a few lines of code.


📥 Setting a Cookie in Laravel

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Symfony\Component\HttpFoundation\Response;

public function login(Request $request)
{
    // After authenticating the user and generating a token (JWT or session)
    $token = 'your-generated-token';

    return response()->json(['message' => 'Login successful'])
        ->cookie(
            'token', $token, 60 * 24, // Expires in 1 day
            '/', null, true, true, false, 'Strict' // path, domain, secure, httpOnly, raw, sameSite
        );
}

✅ Breakdown of Options:

  • token: name of the cookie
  • $token: value
  • 60 * 24: duration in minutes (1 day)
  • true: Secure — only sent over HTTPS
  • true: HttpOnly — not accessible via JavaScript
  • 'Strict': SameSite — prevents CSRF from other origins

📤 Reading a Cookie

To access the token from a request:

public function getProfile(Request $request)
{
    $token = $request->cookie('token');
    // validate and use token
}

⚙️ Laravel Middleware: CORS & Cookies

If your frontend is on a different domain (e.g., vueapp.com calling api.laravelapp.com), make sure to update cors.php:

// config/cors.php
return [
    'supports_credentials' => true,
    'allowed_origins' => ['https://your-frontend.com'],
    'allowed_headers' => ['*'],
    'allowed_methods' => ['*'],
];

And on your frontend (e.g. Vue + Axios):

axios.defaults.withCredentials = true;

⚠️ Common Mistakes

  1. Storing sensitive data in localStorage: Avoid this for access/refresh tokens.
  2. Not using HTTPS: Secure cookies require HTTPS.
  3. Forgetting CORS setup: Cross-origin cookies require proper CORS headers and withCredentials.

🎯 When to Use Cookies

Use cookies when:

  • You want to secure tokens with HttpOnly protection
  • You prefer automatic session management
  • You need to handle long-lived sessions (e.g., “Remember Me” logins)
  • You want to prevent XSS access to your tokens