Skip to main content

Cookie

Struct Cookie 

Source
pub struct Cookie {
    pub name: String,
    pub value: String,
    pub max_age: Option<i64>,
    pub path: Option<String>,
    pub domain: Option<String>,
    pub secure: bool,
    pub http_only: bool,
    pub same_site: Option<SameSite>,
}
Expand description

A cookie to set in the response.

Fields§

§name: String

Cookie name.

§value: String

Cookie value.

§max_age: Option<i64>

Max-Age in seconds (None = session cookie).

§path: Option<String>

Path (defaults to /).

§domain: Option<String>

Domain.

§secure: bool

Secure flag.

§http_only: bool

HttpOnly flag.

§same_site: Option<SameSite>

SameSite attribute.

Implementations§

Source

pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self

Create a new cookie with name and value.

Source

pub fn max_age(self, seconds: i64) -> Self

Set the Max-Age attribute.

Source

pub fn path(self, path: impl Into<String>) -> Self

Set the Path attribute.

Source

pub fn domain(self, domain: impl Into<String>) -> Self

Set the Domain attribute.

Source

pub fn secure(self, secure: bool) -> Self

Set the Secure flag.

Source

pub fn http_only(self, http_only: bool) -> Self

Set the HttpOnly flag.

Source

pub fn same_site(self, same_site: SameSite) -> Self

Set the SameSite attribute.

Source

pub fn to_header_value(&self) -> String

Convert to Set-Cookie header value.

§Security

Cookie names, values, and attribute values are sanitized to prevent attribute injection attacks. Characters that could be interpreted as attribute delimiters (;, \r, \n, \0) are removed.

Source

pub fn session( name: impl Into<String>, value: impl Into<String>, production: bool, ) -> Self

Create a session cookie with secure defaults.

Session cookies are:

  • HttpOnly (not accessible to JavaScript)
  • Secure (HTTPS only, unless production is false)
  • SameSite=Lax (sent with top-level navigations)
  • Path=/ (accessible site-wide)
§Arguments
  • name - Cookie name
  • value - Cookie value
  • production - If true, sets Secure flag; if false, omits it for local development
§Example
use fastapi_core::extract::Cookie;

// Production session cookie
let cookie = Cookie::session("session_id", "abc123", true);

// Development session cookie (no Secure flag)
let cookie = Cookie::session("session_id", "abc123", false);
Source

pub fn auth( name: impl Into<String>, value: impl Into<String>, production: bool, ) -> Self

Create an authentication cookie with strict security.

Auth cookies are:

  • HttpOnly (not accessible to JavaScript)
  • Secure (HTTPS only, unless production is false)
  • SameSite=Strict (only sent in first-party context)
  • Path=/ (accessible site-wide)

Use this for authentication tokens that should never be sent in cross-site requests.

§Arguments
  • name - Cookie name
  • value - Cookie value
  • production - If true, sets Secure flag; if false, omits it for local development
§Example
use fastapi_core::extract::Cookie;

let cookie = Cookie::auth("auth_token", "jwt_here", true)
    .max_age(86400); // 1 day
Source

pub fn csrf( name: impl Into<String>, value: impl Into<String>, production: bool, ) -> Self

Create a CSRF token cookie.

CSRF cookies are:

  • NOT HttpOnly (must be readable by JavaScript to include in requests)
  • Secure (HTTPS only, unless production is false)
  • SameSite=Strict (only sent in first-party context)
  • Path=/ (accessible site-wide)

The CSRF token must be accessible to JavaScript so it can be included in request headers or form data for validation.

§Arguments
  • name - Cookie name (commonly “csrf_token” or “_csrf”)
  • value - The CSRF token value
  • production - If true, sets Secure flag; if false, omits it for local development
§Example
use fastapi_core::extract::Cookie;

let cookie = Cookie::csrf("csrf_token", "random_token_here", true);
Source

pub fn host_prefixed(name: impl Into<String>, value: impl Into<String>) -> Self

Create a cookie with the __Host- prefix.

The __Host- prefix enforces that the cookie:

  • MUST have the Secure flag
  • MUST NOT have a Domain attribute
  • MUST have Path=/

This provides the strongest cookie security by preventing the cookie from being set by subdomains or accessed across different paths.

§Arguments
  • name - Cookie name (without the __Host- prefix - it will be added)
  • value - Cookie value
§Example
use fastapi_core::extract::Cookie;

// Creates cookie named "__Host-session"
let cookie = Cookie::host_prefixed("session", "abc123")
    .http_only(true)
    .same_site(SameSite::Strict);
Source

pub fn secure_prefixed( name: impl Into<String>, value: impl Into<String>, ) -> Self

Create a cookie with the __Secure- prefix.

The __Secure- prefix enforces that the cookie:

  • MUST have the Secure flag

Unlike __Host-, this allows Domain and Path attributes.

§Arguments
  • name - Cookie name (without the __Secure- prefix - it will be added)
  • value - Cookie value
§Example
use fastapi_core::extract::Cookie;

// Creates cookie named "__Secure-token"
let cookie = Cookie::secure_prefixed("token", "abc123")
    .domain(".example.com")
    .http_only(true);
Source

pub fn validate_prefix(&self) -> Result<(), CookiePrefixError>

Validate that the cookie meets its prefix requirements.

Returns Ok(()) if valid, or Err with a description of the violation.

  • __Host-: Must have Secure=true, Path=“/”, and no Domain
  • __Secure-: Must have Secure=true
§Example
use fastapi_core::extract::Cookie;

let cookie = Cookie::host_prefixed("session", "abc123");
assert!(cookie.validate_prefix().is_ok());

// This would fail validation
let invalid = Cookie::new("__Host-session", "abc123")
    .domain("example.com"); // __Host- cannot have Domain
assert!(invalid.validate_prefix().is_err());
Source

pub fn has_security_prefix(&self) -> bool

Check if this cookie has a security prefix.

Source

pub fn prefix(&self) -> Option<CookiePrefix>

Get the security prefix type, if any.

Trait Implementations§

Source§

fn clone(&self) -> Cookie

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, _span: NoopSpan) -> Self

Instruments this future with a span (no-op when disabled).
Source§

fn in_current_span(self) -> Self

Instruments this future with the current span (no-op when disabled).
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ResponseProduces<T> for T