Skip to content

Use req_cookie_set() to set client side cookies that are sent to the server.

By default, httr2 uses a clean slate for every request meaning that cookies are not automatically preserved across requests. To preserve cookies, use req_cookie_preserve() along with the path to cookie file that will be read before and updated after each request.

Usage

req_cookie_preserve(req, path)

req_cookies_set(req, ...)

Arguments

req

A httr2 request object.

path

A path to a file where cookies will be read from before and updated after the request.

...

<dynamic-dots> Name-value pairs that define query parameters. Each value must be an atomic vector, which is automatically escaped. To opt-out of escaping, wrap strings in I().

Examples

# Use `req_cookies_set()` to set client-side cookies
request(example_url()) |>
  req_cookies_set(a = 1, b = 1) |>
  req_dry_run()
#> GET / HTTP/1.1
#> Host: 127.0.0.1:42691
#> User-Agent: httr2/1.0.6.9000 r-curl/6.0.1 libcurl/7.81.0
#> Accept: */*
#> Accept-Encoding: deflate, gzip, br, zstd
#> Cookie: a=1;b=1
#> 

# Use `req_cookie_preserve()` to preserve server-side cookies across requests
path <- tempfile()

# Set a server-side cookie
request(example_url()) |>
  req_cookie_preserve(path) |>
  req_template("/cookies/set/:name/:value", name = "chocolate", value = "chip") |>
  req_perform() |>
  resp_body_json()
#> $cookies
#> $cookies$chocolate
#> [1] "chip"
#> 
#> 

# Set another sever-side cookie
request(example_url()) |>
  req_cookie_preserve(path) |>
  req_template("/cookies/set/:name/:value", name = "oatmeal", value = "raisin") |>
  req_perform() |>
  resp_body_json()
#> $cookies
#> $cookies$chocolate
#> [1] "chip"
#> 
#> $cookies$oatmeal
#> [1] "raisin"
#> 
#> 

# Add a client side cookie
request(example_url()) |>
  req_url_path("/cookies/set") |>
  req_cookie_preserve(path) |>
  req_cookies_set(snicker = "doodle") |>
  req_perform() |>
  resp_body_json()
#> $cookies
#> $cookies$chocolate
#> [1] "chip"
#> 
#> $cookies$oatmeal
#> [1] "raisin"
#> 
#> $cookies$snicker
#> [1] "doodle"
#> 
#> 

# The cookie path has a straightforward format
cat(readChar(path, nchars = 1e4))
#> # Netscape HTTP Cookie File
#> # https://curl.se/docs/http-cookies.html
#> # This file was generated by libcurl! Edit at your own risk.
#> 
#> 127.0.0.1	FALSE	/	FALSE	0	chocolate	chip
#> 127.0.0.1	FALSE	/	FALSE	0	oatmeal	raisin