warp icon indicating copy to clipboard operation
warp copied to clipboard

Set cookies in responses

Open geigerzaehler opened this issue 4 years ago • 3 comments

It would be great to have a filter that allows you to set cookies on responses. At the moment the work around is to set the Set-Cookie header through the header APIs. However, this requires you to encode the cookie value manually, which is error-prone. In addition, this approach only allows you to set one cookie per response (#609).

geigerzaehler avatar Oct 15 '20 10:10 geigerzaehler

This filter could also make it easy to "delete" cookies. Currently, I have to write code to set the cookie Expires time to be in the past. Would be nice if this functionality was available off the shelf.

Edit: I'm a rust noob but would love to take a stab at this if someone could provide a little guidance!

Clee681 avatar Dec 11 '20 04:12 Clee681

This filter could also make it easy to "delete" cookies. Currently, I have to write code to set the cookie Expires time to be in the past. Would be nice if this functionality was available off the shelf.

Edit: I'm a rust noob but would love to take a stab at this if someone could provide a little guidance!

The server can only make a cookie expire to achieve the goal of deleting a cookie on the client side. The server cannot directly delete a client's cookie, but can only make it expire. Consider renaming "expiration" as "deletion" to reflect this.

zy010101 avatar Jul 04 '23 02:07 zy010101

It would be great to have a filter that allows you to set cookies on responses. At the moment the work around is to set the Set-Cookie header through the header APIs. However, this requires you to encode the cookie value manually, which is error-prone. In addition, this approach only allows you to set one cookie per response (#609).

Now it is possible to accomplish it using the Response from reply:

async fn response() -> Result<impl warp::Reply, warp::Rejection> {
    // Serialization
    let data = json!(r#"{"msg": "OK"}"#);
    let data = data.to_string();
    // Place the serialized data into the response body
    let res = warp::reply::json(&data);
        // Insert response headers
    let res = warp::reply::with_header(res, "key", "value");
    let res = warp::reply::with_header(res, "content-type", "application/json");
    // Set cookies
    let res = warp::reply::with_header(res, "set-cookie", "a=12345");
    let res = warp::reply::with_header(res, "set-cookie", "b=67890");
    // Set status code
    let res = warp::reply::with_status(res, warp::http::StatusCode::BAD_REQUEST);
    Ok(res)
}

zy010101 avatar Jul 04 '23 02:07 zy010101