Cannot set expire in private cookie Rocket-Rust

I encountered this same problem and I think I've figured it out:

  • Rocket uses both the cookie and time packages internally
  • The example code in the Rocket docs for rocket::http::Cookie actually comes from the cookie package and therefor confusingly uses use cookies::Cookie; instead of use rocket::http::Cookie.
  • Key thing: The docs at https://api.rocket.rs/v0.5-rc/ appear to be newer that the code that's in crates.io, and use different versions of the cookie and time crates.

So you need to use the same version or cookie or time that Rocket is using. If you're using rocket 0.5.0-rc.1 from crates.io then you need cookie 0.15 or time 0.2.11.

I was able to get my code working with these lines in my Cargo.toml:

rocket = { version = "0.5.0-rc.1", features = ["secrets", "json"] }
time = "0.2.11"

Your example code would then become:

use rocket::http::{Cookie, CookieJar};
use time::{Duration, OffsetDateTime};

fn handler(jar: &CookieJar<'_>) {
    let mut cookie = Cookie::new("name", "value");

    let mut now = OffsetDateTime::now_utc();
    now += Duration::days(1);
    cookie.set_expires(now);

    jar.add_private(cookie);
}

Alternatively, I think if you use version 0.15 of cookie (you might be using 0.16.0-rc.1) then your code should work as you have it. I think it's cleaner to import Duration and OffsetTime directly from the time package though.

It looks like the latest version of Rocket in Github exposes time as rocket::time so we should be able to switch to that when final 0.5 release comes out.