Secure Flag Cookies in Laravel: Setup and Configuration
In this article
To set the secure flag on cookies in Laravel, you must modify the secure option within the config/session.php file or set the SESSION_SECURE_COOKIE variable in your .env file to true. Setting the secure flag ensures that cookies are only transmitted over encrypted connections (HTTPS), preventing them from being sent in plain text over HTTP, which protects sensitive session data from man-in-the-middle attacks and packet sniffing.
What You'll Need
- A running Laravel installation (version 5.x through 11.x).
- Access to the project's root directory and configuration files.
- An SSL certificate installed on your server (required for the browser to actually send the secure cookie back to the server).
- A code editor or terminal access to modify the
.envfile.
Step-by-Step
-
Locate your Environment File: Navigate to the root directory of your Laravel project and open the
.envfile. This is the preferred method for managing environment-specific settings without changing the version-controlled configuration files. -
Add or Update the Secure Cookie Variable: Look for a variable named
SESSION_SECURE_COOKIE. If it exists, change its value totrue. If it does not exist, add the following line to the file:SESSION_SECURE_COOKIE=true -
Verify the Configuration File: Open
config/session.php. Ensure that the'secure'key is mapped to the environment variable. It should look like this:
This ensures that Laravel checks the'secure' => env('SESSION_SECURE_COOKIE', false),.envfile first, but defaults tofalseif the variable is missing (which is useful for local development). -
Clear the Configuration Cache: Laravel caches configuration files for performance. For the changes to take effect, you must clear the cache. Run the following command in your terminal:
Alternatively, usephp artisan config:clearphp artisan config:cacheto clear and then re-cache the settings. - Test the Implementation: Open your application in a browser using HTTPS. Open the Developer Tools (F12), go to the Application tab, and select Cookies. Locate your session cookie (usually named `laravel_session`) and verify that the Secure column is checked.
Common Mistakes
- Enabling Secure Flag on Localhost: Enabling the secure flag on a local development environment that does not use HTTPS will cause the browser to refuse to store the cookie. This results in users being unable to stay logged in or session data disappearing on every page refresh.
- Forgetting to Clear Cache: Many developers update the
.envfile but forget to runphp artisan config:clear. Because Laravel reads from the cachedbootstrap/cache/config.phpfile in production, the changes will not be applied until the cache is refreshed. - Confusing Secure with HttpOnly: The
secureflag only controls how the cookie is transmitted (HTTPS only). Thehttp_onlyflag (also found inconfig/session.php) controls who can access the cookie (preventing JavaScript access). Both should be enabled for maximum security, but they serve different purposes.
Tips
- Use Environment-Specific Settings: Always keep
SESSION_SECURE_COOKIE=falsein your local.envandSESSION_SECURE_COOKIE=truein your production.env. Never hardcodetruedirectly intoconfig/session.phpif you intend to share the code across multiple environments. - Combine with SameSite: In
config/session.php, set the'same_site'attribute to'lax'or'strict'. This works alongside the secure flag to prevent Cross-Site Request Forgery (CSRF) attacks. - Force HTTPS: If you are enforcing secure cookies, you should also force all traffic to HTTPS using a middleware or server-level redirect (via .htaccess or Nginx config) to ensure no parts of your app are served over insecure connections.
Troubleshooting
If you have set the secure flag to true but your sessions are not persisting (you are logged out immediately after logging in), check the following:
- Verify HTTPS: Ensure you are accessing the site via
https://. If you are usinghttp://, the browser will ignore the cookie because the secure flag is set. - Check Load Balancers: If your app is behind a load balancer or proxy (like Cloudflare or AWS ALB), the request might reach Laravel as HTTP even if the user is using HTTPS. In this case, you must configure the
TrustProxiesmiddleware to ensure Laravel recognizes theX-Forwarded-Protoheader and treats the request as secure. - Browser Cache: Sometimes old, non-secure cookies persist in the browser. Clear your browser cookies and try logging in again.
Frequently Asked Questions
What happens if I set the secure flag but don't have SSL?
The browser will refuse to store the cookie. Since the cookie is marked as secure, it can only be set and sent back over an encrypted connection. If the connection is plain HTTP, the session will fail to initialize.
Does this affect all cookies or just the session cookie?
The setting in config/session.php specifically affects the Laravel session cookie. If you are creating custom cookies using the Cookie::make() helper, you must pass the secure flag as a parameter in the options array.
Is the secure flag enough to prevent XSS attacks?
No. The secure flag prevents interception during transmission. To help mitigate XSS (Cross-Site Scripting) attacks, you should use the http_only flag, which prevents client-side scripts from accessing the cookie.
Can I use the secure flag with a self-signed certificate?
Yes, the browser will generally treat a self-signed certificate as an HTTPS connection for the purpose of the secure flag, although the user will see a security warning in their browser.
How do I check if the secure flag is active without DevTools?
The only reliable way to verify the flag is by inspecting the HTTP response headers (specifically the Set-Cookie header) or using the browser's storage inspector, as the flag is a browser-level instruction and not visible on the page content.