Cookies
Introduction
Cookies let your application store small pieces of data in a visitor's browser and read them back on later requests, such as their preferred color theme or whether they dismissed a product tour. You read incoming cookies from the Request and attach outgoing cookies to the response your handler returns.
Routes in the web middleware group automatically encrypt and sign cookies so visitors can't read or tamper with them. Routes outside the web group, such as those in src/routes/api.rs, send cookies unencrypted. For data that should stay on your server, use the session instead.
Reading cookies
To retrieve a cookie from an incoming request, call cookie on the Request. It returns Option<String>, or None if the browser didn't send that cookie:
1use laravel::prelude::*;23pub async fn show(request: Request) -> String {4 let theme = request.cookie("theme").unwrap_or_else(|| "light".to_owned());56 format!("Your theme is {theme}")7}1use laravel::prelude::*;23pub async fn show(request: Request) -> String {4 let theme = request.cookie("theme").unwrap_or_else(|| "light".to_owned());56 format!("Your theme is {theme}")7}
On routes in the web middleware group, request.cookie(...) automatically returns the decrypted value. If a cookie's value was modified by the client and fails decryption, cookie returns None.
Sending cookies
To attach a cookie to an outgoing response, call with_cookie. Passing a (name, value) tuple creates a session-scoped cookie that lasts until the user closes their browser:
1use laravel::prelude::*;23pub async fn update() -> Response {4 Response::new("Saved").with_cookie(("theme", "dark"))5}1use laravel::prelude::*;23pub async fn update() -> Response {4 Response::new("Saved").with_cookie(("theme", "dark"))5}
Every response type supports with_cookie, including redirects, views, and Json. For example, a handler that redirects after updating settings may attach the cookie directly to the Redirect:
1pub async fn update() -> Redirect {2 Redirect::to("/settings").with_cookie(("theme", "dark"))3}1pub async fn update() -> Redirect {2 Redirect::to("/settings").with_cookie(("theme", "dark"))3}
Attaching a cookie replaces any cookie already on the response with the same name, path, and domain. Middleware may also attach cookies to the response returned by next.run(request).
Cookie attributes
To give a cookie a lifetime or customize its attributes, build a Cookie instead of passing a tuple. Lifetimes are passed as a span, such as 30.days():
1use laravel::cookie::{Cookie, SameSite};2use laravel::prelude::*;34pub async fn update() -> Response {5 Response::new("Saved")6 .with_cookie(Cookie::new("theme", "dark").max_age(30.days()))7 .with_cookie(Cookie::new("cookie_consent", "accepted").forever())8 .with_cookie(Cookie::new("embed", "1").same_site(SameSite::None).secure(true))9}1use laravel::cookie::{Cookie, SameSite};2use laravel::prelude::*;34pub async fn update() -> Response {5 Response::new("Saved")6 .with_cookie(Cookie::new("theme", "dark").max_age(30.days()))7 .with_cookie(Cookie::new("cookie_consent", "accepted").forever())8 .with_cookie(Cookie::new("embed", "1").same_site(SameSite::None).secure(true))9}
| Method | Attribute | Effect |
|---|---|---|
max_age(span) |
Max-Age |
Keeps the cookie for this long. |
expires(time) |
Expires |
Keeps the cookie until a time, such as laravel::now().end_of_day()?. |
forever() |
Max-Age |
Keeps the cookie for 400 days, the longest that browsers allow. |
path(path), domain(domain) |
Path, Domain |
Where the browser sends the cookie. |
secure(bool) |
Secure |
Sends the cookie only over HTTPS. |
http_only(bool) |
HttpOnly |
Hides the cookie from JavaScript. Pass false to let scripts read it. |
same_site(SameSite) |
SameSite |
Whether the browser sends the cookie with requests from other sites: Lax, Strict, or None. |
Unless you override them, new cookies inherit the Path, Domain, Secure, and SameSite defaults from your session configuration, and have HttpOnly enabled. Those defaults are safe for most cookies, so you'll usually only need to set a lifetime.
Deleting cookies
To remove a cookie from the browser, call without_cookie on the response. Laravel sends an expired cookie in its place so the browser deletes it:
1use laravel::prelude::*;23pub async fn dismiss() -> Response {4 Response::new("Dismissed").without_cookie("tour")5}1use laravel::prelude::*;23pub async fn dismiss() -> Response {4 Response::new("Dismissed").without_cookie("tour")5}
If the cookie was originally set with a custom path or domain, the browser only deletes it when the removal cookie specifies the same path and domain. In that case, pass a Cookie with those attributes:
1use laravel::cookie::Cookie;23Response::new("Dismissed").without_cookie(Cookie::new("tour", "").path("/admin"))1use laravel::cookie::Cookie;23Response::new("Dismissed").without_cookie(Cookie::new("tour", "").path("/admin"))
Cookies and encryption
The EncryptCookies middleware runs first in the web middleware group and encrypts every outgoing cookie using your application's encryption key. When the browser sends those cookies back on subsequent requests, EncryptCookies decrypts them before your handler runs. If a cookie fails decryption because a visitor tampered with it, EncryptCookies discards it and request.cookie(...) returns None.
EncryptCookies encrypts only the cookies on responses that pass back through it. A middleware that runs outside the web group, such as a global middleware, sends its cookies unencrypted.
Excluding cookies from encryption
Sometimes JavaScript or another application needs to read a cookie, such as a script that applies the visitor's color theme before the page renders. To exclude specific cookies from encryption, replace EncryptCookies inside with_middleware in src/app.rs:
1use laravel::cookie::EncryptCookies;2use laravel::prelude::*;34Application::configure()5 .with_middleware(|middleware, _| {6 middleware.replace(EncryptCookies::except(["theme"]));7 })1use laravel::cookie::EncryptCookies;2use laravel::prelude::*;34Application::configure()5 .with_middleware(|middleware, _| {6 middleware.replace(EncryptCookies::except(["theme"]));7 })
For JavaScript to read the cookie in the browser, also disable HttpOnly when you attach it:
1Response::new("Saved").with_cookie(Cookie::new("theme", "dark").http_only(false))1Response::new("Saved").with_cookie(Cookie::new("theme", "dark").http_only(false))
Only exclude cookies that don't contain sensitive data. Visitors can read and modify an unencrypted cookie, so always treat its value as untrusted input.
Testing
In tests, send an incoming cookie with cookie, and assert outgoing cookies with assert_cookie and assert_cookie_expired. Both work with plain values, so you don't need to encrypt or decrypt cookies yourself:
1use laravel::testing::prelude::*;23#[laravel::test]4async fn the_theme_can_be_changed(app: Application) {5 app.get("/").cookie("theme", "dark").await.assert_see("Your theme is dark");67 app.post("/theme").await.assert_cookie("theme", "dark");89 app.post("/tour/dismiss").await.assert_cookie_expired("tour");10}1use laravel::testing::prelude::*;23#[laravel::test]4async fn the_theme_can_be_changed(app: Application) {5 app.get("/").cookie("theme", "dark").await.assert_see("Your theme is dark");67 app.post("/theme").await.assert_cookie("theme", "dark");89 app.post("/tour/dismiss").await.assert_cookie_expired("tour");10}
To learn more about carrying cookies from one response to the next request with with_cookies_from, check out the testing guide's section on cookies and sessions.