# Cookies and sessions

> How to send cookies, read the cookies a site sets, and let a session remember them across requests like a browser tab.

Source: https://docs.virginproxy.com/cookies/

Cookies are how websites remember a visitor: consent, language, cart, login. You can send them with a request, read the ones a site sets, and let a session keep them for you.

## Send cookies

The simplest form is an object of names and values:

**cURL**

```bash
curl https://api.virginproxy.com/v1/requests \
  -H "Authorization: Bearer $VP_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://httpbin.org/cookies",
    "cookies": {
      "theme": "dark",
      "consent": "yes"
    }
  }'
```

**Python**

```python
import os, requests

r = requests.post(
    "https://api.virginproxy.com/v1/requests",
    headers={"Authorization": "Bearer " + os.environ["VP_KEY"]},
    json={
        "url": "https://httpbin.org/cookies",
        "cookies": {"theme": "dark", "consent": "yes"},
    },
    timeout=180,
)
data = r.json()
if not r.ok:
    raise SystemExit(data["error"]["code"] + ": " + data["error"]["message"])
print(data["body"])
```

**Node.js**

```javascript
const res = await fetch("https://api.virginproxy.com/v1/requests", {
  method: "POST",
  headers: { Authorization: "Bearer " + process.env.VP_KEY, "Content-Type": "application/json" },
  body: JSON.stringify({
    url: "https://httpbin.org/cookies",
    cookies: { theme: "dark", consent: "yes" },
  }),
  signal: AbortSignal.timeout(180_000),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error.code + ": " + data.error.message);
console.log(data.body);
```

**Python SDK**

```pysdk
from virginproxy import VirginProxy  # docs.virginproxy.com/sdk/virginproxy.py

vp = VirginProxy()  # reads VP_KEY
data = vp.request({
    "url": "https://httpbin.org/cookies",
    "cookies": {"theme": "dark", "consent": "yes"},
})
print(data)
```

**Node SDK**

```nodesdk
import { VirginProxy } from "./virginproxy.mjs"; // docs.virginproxy.com/sdk/virginproxy.mjs

const vp = new VirginProxy(); // reads VP_KEY
const data = await vp.request({
  url: "https://httpbin.org/cookies",
  cookies: { theme: "dark", consent: "yes" },
});
console.log(data);
```

**PHP**

```php
<?php
$ch = curl_init("https://api.virginproxy.com/v1/requests");
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 180,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . getenv("VP_KEY"),
        "Content-Type: application/json",
    ],
    CURLOPT_POSTFIELDS => json_encode([
        "url" => "https://httpbin.org/cookies",
        "cookies" => ["theme" => "dark", "consent" => "yes"],
    ], JSON_UNESCAPED_SLASHES),
]);
$data = json_decode(curl_exec($ch), true);
if (isset($data["error"])) {
    exit($data["error"]["code"] . ": " . $data["error"]["message"] . PHP_EOL);
}
echo $data["body"], PHP_EOL;
```

**Go**

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"
)

func main() {
	payload := []byte(`{
  "url": "https://httpbin.org/cookies",
  "cookies": {
    "theme": "dark",
    "consent": "yes"
  }
}`)
	req, err := http.NewRequest("POST", "https://api.virginproxy.com/v1/requests", bytes.NewReader(payload))
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("VP_KEY"))
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{Timeout: 180 * time.Second}
	res, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()

	var data map[string]any
	if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
		log.Fatal(err)
	}
	if res.StatusCode >= 300 {
		e := data["error"].(map[string]any)
		log.Fatalf("%v: %v", e["code"], e["message"])
	}
	fmt.Println(data["body"])
}
```

POST`/v1/requests`[≈ 1 credit](https://docs.virginproxy.com/billing/#cost)[Open in Playground](https://dash.virginproxy.com/playground#request=eyJ1cmwiOiJodHRwczovL2h0dHBiaW4ub3JnL2Nvb2tpZXMiLCJjb29raWVzIjp7InRoZW1lIjoiZGFyayIsImNvbnNlbnQiOiJ5ZXMifX0)

When a cookie should only go to certain hosts or paths, use a list:

```json
{
  "url": "https://www.example.com/shop/",
  "cookies": [
    { "name": "consent", "value": "yes", "domain": ".example.com" },
    { "name": "cart", "value": "42", "path": "/shop" }
  ]
}
```

| Field | Meaning |
| --- | --- |
| `name` | Required. Up to 256 characters, the characters a cookie name may contain. |
| `value` | Required. A string of up to 8,000 characters without `;` or line breaks. |
| `domain` | Optional. Without it the cookie goes to the target host only. With `example.com` or `.example.com` it also goes to its subdomains, for example after a redirect to `www.example.com`. |
| `path` | Optional. Starts with `/`; the cookie goes only to paths below it. |

At most 200 cookies per request. A `Cookie` header in `headers` works too, which is handy when you copy one from your browser (see [Copy a request from your browser](https://docs.virginproxy.com/copy-from-browser/)). Both can be combined: your `Cookie` header comes first, the other cookies follow.

## Read the cookies a site sets

Every response lists the cookies the target set, parsed, including those set on the way through redirects:

```json
"cookies": [
  { "name": "session-id", "value": "262-4410173", "domain": ".shop.example", "path": "/",
    "expires": "2027-11-17T10:12:08Z", "secure": true, "http_only": true, "same_site": "Lax" }
]
```

`expires`, `max_age` and `same_site` appear only when the site set them. The raw headers are in `headers["set-cookie"]`, a list with one entry per cookie of the final response.

**Python**

```python
API = "https://api.virginproxy.com/v1/requests"
AUTH = {"Authorization": "Bearer " + os.environ["VP_KEY"]}

jar = {c["name"]: c["value"] for c in data["cookies"]}
# send them along next time
requests.post(API, headers=AUTH, json={"url": "https://shop.example/cart", "cookies": jar}, timeout=180)
```

**Node.js**

```javascript
const jar = Object.fromEntries(data.cookies.map((c) => [c.name, c.value]));
// send them along next time
await fetch("https://api.virginproxy.com/v1/requests", {
  method: "POST",
  headers: { Authorization: "Bearer " + process.env.VP_KEY, "Content-Type": "application/json" },
  body: JSON.stringify({ url: "https://shop.example/cart", cookies: jar }),
});
```

## Let a session remember cookies

With a `session`, you do not have to carry cookies yourself. Cookies the site sets are remembered and sent automatically with the next requests of the same session to that site, just like in a browser tab. Cookies you send in `cookies` are remembered too.

**cURL**

```bash
curl https://api.virginproxy.com/v1/requests \
  -H "Authorization: Bearer $VP_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://httpbin.org/cookies/set?step=1",
    "session": "visitor-7"
  }'
```

**Python**

```python
import os, requests

r = requests.post(
    "https://api.virginproxy.com/v1/requests",
    headers={"Authorization": "Bearer " + os.environ["VP_KEY"]},
    json={
        "url": "https://httpbin.org/cookies/set?step=1",
        "session": "visitor-7",
    },
    timeout=180,
)
data = r.json()
if not r.ok:
    raise SystemExit(data["error"]["code"] + ": " + data["error"]["message"])
# the second request carries the cookie of the first one
r = requests.post(r.url, headers={"Authorization": "Bearer " + os.environ["VP_KEY"]}, timeout=180,
                  json={"url": "https://httpbin.org/cookies", "session": "visitor-7"})
print(r.json()["body"])  # {"cookies": {"step": "1"}}
```

**Node.js**

```javascript
const res = await fetch("https://api.virginproxy.com/v1/requests", {
  method: "POST",
  headers: { Authorization: "Bearer " + process.env.VP_KEY, "Content-Type": "application/json" },
  body: JSON.stringify({
    url: "https://httpbin.org/cookies/set?step=1",
    session: "visitor-7",
  }),
  signal: AbortSignal.timeout(180_000),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error.code + ": " + data.error.message);
// the second request carries the cookie of the first one
const again = await fetch(res.url, {
  method: "POST",
  headers: { Authorization: "Bearer " + process.env.VP_KEY, "Content-Type": "application/json" },
  body: JSON.stringify({ url: "https://httpbin.org/cookies", session: "visitor-7" }),
});
console.log((await again.json()).body); // {"cookies": {"step": "1"}}
```

**Python SDK**

```pysdk
from virginproxy import VirginProxy  # docs.virginproxy.com/sdk/virginproxy.py

vp = VirginProxy()  # reads VP_KEY
data = vp.request({
    "url": "https://httpbin.org/cookies/set?step=1",
    "session": "visitor-7",
})
print(data)
```

**Node SDK**

```nodesdk
import { VirginProxy } from "./virginproxy.mjs"; // docs.virginproxy.com/sdk/virginproxy.mjs

const vp = new VirginProxy(); // reads VP_KEY
const data = await vp.request({
  url: "https://httpbin.org/cookies/set?step=1",
  session: "visitor-7",
});
console.log(data);
```

**PHP**

```php
<?php
$ch = curl_init("https://api.virginproxy.com/v1/requests");
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 180,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . getenv("VP_KEY"),
        "Content-Type: application/json",
    ],
    CURLOPT_POSTFIELDS => json_encode([
        "url" => "https://httpbin.org/cookies/set?step=1",
        "session" => "visitor-7",
    ], JSON_UNESCAPED_SLASHES),
]);
$data = json_decode(curl_exec($ch), true);
if (isset($data["error"])) {
    exit($data["error"]["code"] . ": " . $data["error"]["message"] . PHP_EOL);
}
echo $data["status"], " ", $data["body"], PHP_EOL;
```

**Go**

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"
)

func main() {
	payload := []byte(`{
  "url": "https://httpbin.org/cookies/set?step=1",
  "session": "visitor-7"
}`)
	req, err := http.NewRequest("POST", "https://api.virginproxy.com/v1/requests", bytes.NewReader(payload))
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("VP_KEY"))
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{Timeout: 180 * time.Second}
	res, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()

	var data map[string]any
	if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
		log.Fatal(err)
	}
	if res.StatusCode >= 300 {
		e := data["error"].(map[string]any)
		log.Fatalf("%v: %v", e["code"], e["message"])
	}
	fmt.Println(data["status"], data["body"])
}
```

POST`/v1/requests`[≈ 1 credit](https://docs.virginproxy.com/billing/#cost)[Open in Playground](https://dash.virginproxy.com/playground#request=eyJ1cmwiOiJodHRwczovL2h0dHBiaW4ub3JnL2Nvb2tpZXMvc2V0P3N0ZXA9MSIsInNlc3Npb24iOiJ2aXNpdG9yLTcifQ)

|  | How long |
| --- | --- |
| Same IP | Up to 10 minutes from the first request of the session. See [IPs and sessions](https://docs.virginproxy.com/sessions/). |
| Remembered cookies | Until 30 minutes after the last request of the session. Each request starts the 30 minutes again. |

After 10 minutes the session continues on a new IP with the same cookies, like a person whose connection changed. Use a new session name when you want to start over as a new visitor.

To keep the IP of a session but manage cookies yourself, send `"cookie_jar": false`. Without a session every request starts with no cookies except the ones you send; cookies set during its own redirects are still passed on to the next step.

Pages loaded with `render` share the cookies of their session in both directions. You can load one page in the browser and continue with plain requests in the same session.

> **Note:** Remembered cookies are kept in memory only, for your session alone, and are deleted 30 minutes after the session was last used. They never appear in our logs.
