Skip to main content

Disabling the Cookie Jar

Sometimes you don't want the session managing cookies for you. Maybe you've got a database acting as your single source of truth. Maybe you want every request fully isolated. Or maybe you're debugging and the auto-replay is getting in the way.

WithoutCookieJar() (added in 1.6.6) flips the jar off. With it set:

  • Set-Cookie headers from responses are not stored
  • The jar is not consulted when building the next request's Cookie header
  • GetCookies() returns an empty list

Caller-provided Cookie headers still pass through untouched. Only the auto-injection from the internal jar is suppressed.

When to actually do this

A few real reasons to turn it off:

  • You manage cookies yourself. App-level cookie store in Redis, Postgres, whatever. You read from there, build the Cookie header per request, and don't want the lib doing anything else.
  • You want each request fully independent. Useful for fan-out crawling where two requests on the same session shouldn't share state.
  • You're debugging. When you're trying to figure out why a response sets a weird cookie, having the jar silently swallow and replay it makes things harder. Turn it off, watch the raw headers.

If none of those apply, leave the jar on. It's there for a reason.

Code

package main

import (
"context"
"fmt"
"io"

"github.com/sardanioss/httpcloak"
)

func main() {
s := httpcloak.NewSession("chrome-146", httpcloak.WithoutCookieJar())
defer s.Close()

ctx := context.Background()

r1, _ := s.Get(ctx, "https://httpbin.org/cookies/set?demo=hello")
r1.Close()

r2, _ := s.Get(ctx, "https://httpbin.org/cookies")
body, _ := io.ReadAll(r2.Body)
r2.Close()
fmt.Println(string(body))
// {"cookies": {}} (jar didn't store anything)

fmt.Println(s.GetCookies()) // []
}

Managing cookies yourself

With the jar off, you're driving. Two main patterns:

  1. Send a Cookie header per request. Build the string yourself, attach it to the request headers. See Per-Request Cookies for examples.
  2. Pull Set-Cookie out of the response. Each Response exposes its raw headers; parse Set-Cookie yourself and stash the result wherever you want.
Headers still pass through

Even with the jar off, the Cookie header you set on a request still goes out as you wrote it. The flag only suppresses the lib's auto-injection, not your manual headers.

Mixing modes

You can't toggle WithoutCookieJar mid-session. It's a session option, set once at construction. If you need both modes (jar-on for one workflow, jar-off for another), spin up two sessions.

If you need shared TLS state across the two, use Fork() to create a sibling that carries the same TLS resumption cache but starts fresh on cookies. Heads up: forks share the same cookie jar pointer, so if you fork from a jar-enabled parent, both share the jar. To genuinely separate the cookie state, build a fresh session.