# Keep cookies between requests

**For:** Rust developers talking to a site that logs you in with a cookie.

You turn on a client's cookie store so a cookie one response sets is sent on the requests after it, the way a browser keeps you logged in.

Before you start: you need Rust with Cargo. fibre_http comes from crates.io as `fibre_http = "0"`.

## Set up the project

Start a new binary crate.

```sh
cargo new cookies
cd cookies
```

Put this in the `[dependencies]` section of `Cargo.toml`:

```toml title="Cargo.toml"
[dependencies]
fibre_http = { version = "0", features = ["cookies", "json"] }
serde_json = "1"
```

The `cookies` feature adds the cookie store. The `json` feature is only there to read httpbin's answer.

## The program

httpbin.org's `/cookies/set` answers with a `Set-Cookie` header. Its `/cookies` endpoint shows which cookies your request carried. Replace `src/main.rs` with this:

```rust title="src/main.rs"
use fibre_http::SyncClient;
use serde_json::Value;

fn main() -> Result<(), fibre_http::Error> {
    let plain = SyncClient::new();
    plain.get("https://httpbin.org/cookies/set?session=abc123").send()?;
    let seen: Value = plain.get("https://httpbin.org/cookies").send()?.json()?;
    println!("without a cookie store: {}", seen["cookies"]);

    let client = SyncClient::builder().cookie_store(true).build_sync()?;
    client.get("https://httpbin.org/cookies/set?session=abc123").send()?;
    let seen: Value = client.get("https://httpbin.org/cookies").send()?.json()?;
    println!("with a cookie store: {}", seen["cookies"]);
    Ok(())
}
```

Run it:

```shell-session
$ cargo run
without a cookie store: {}
with a cookie store: {"session":"abc123"}
```

## What each part does

A plain client ignores `Set-Cookie`, so the second request goes out with no cookies.

`cookie_store(true)` gives the client an in-memory store. It saves every cookie a response sets, including responses to redirects it follows on the way. Later requests carry the cookies that match their domain and path.

The store lives as long as the client and the clients cloned from it. If you set a `Cookie` header on a request yourself, that request keeps yours.

## Where to go next

The usage guide shows a login form posted with `form` and a page fetched after it: [https://github.com/excsn/fibre/blob/main/http/README.USAGE.md](https://github.com/excsn/fibre/blob/main/http/README.USAGE.md)
