Skip to main content

Cookies

Reading cookies from the request

Actix 4.9+ 5 min read

# Cookies

Cookies are used to store session identifiers or user preferences. Actix Web allows you to read cookies easily from incoming requests.

#Accessing Cookies

You can access cookies by extracting the HttpRequest and calling the .cookie() method.

code_blocksrust
use actix_web::{get, HttpRequest, HttpResponse};

#[get("/")]
async fn index(req: HttpRequest) -> HttpResponse {
    if let Some(cookie) = req.cookie("session_id") {
        HttpResponse::Ok().body(format!("Your session: {}", cookie.value()))
    } else {
        HttpResponse::Unauthorized().body("No session found")
    }
}

Actix Web uses the cookie crate under the hood, so you have access to a robust API for parsing and verifying cookies.

Was this page helpful?

Reference Implementation

The following code snippet demonstrates the authoritative pattern for this documentation.

src/main.rs
1use actix_web::{get, HttpRequest, App, HttpServer, Responder};
2
3#[get("/auth-check")]
4async fn auth_check(req: HttpRequest) -> impl Responder {
5 if req.cookie("auth_token").is_some() {
6 "Authenticated!"
7 } else {
8 "Please log in."
9 }
10}
11
12#[actix_web::main]
13async fn main() -> std::io::Result<()> {
14 HttpServer::new(|| App::new().service(auth_check))
15 .bind(("127.0.0.1", 8080))?
16 .run()
17 .await
18}
Was this page helpful?