net/http/cookiejar

net/http/cookiejar in-memory cookie storage, the insecure nil PublicSuffixList case, and Client.Jar updates with a fake RoundTripper.

The net/http/cookiejar package is an in-memory implementation of http.CookieJar. Import it as "net/http/cookiejar". A Client with a non-nil Jar stores cookies from responses and attaches them to later requests. Official documentation for Client.Jar describes that flow, including redirects. The jar is not a browser: it does not implement a full SameSite, CORS, or user-interface cookie policy, and it does not persist to disk.

cookiejar.New(nil) is equivalent to a zero Options, so PublicSuffixList is nil. Official documentation says a nil list is valid and may be useful for testing but it is not secure: the HTTP server for foo.co.uk can set a cookie for bar.co.uk. Do not treat a nil PublicSuffixList as production-safe. A real list is often supplied by a third-party module such as golang.org/x/net/publicsuffix, which is outside this reference.

Hosts such as foo.example.test and the value fake-cookie-not-real are sample data only. Examples use SetCookies or a fake RoundTripper. They do not read a browser cookie store, process environment, or token file, and they do not send network traffic. Outputs were recorded with Go 1.24.0.

Examples were checked against Go 1.24.0. See the official package documentation for the complete API.

Go reference overview →

API index

APISummary
cookiejar.New, Options, SetCookies, and CookiesWith a nil PublicSuffixList, a cookie for example.test set from foo.example.test is also visible to bar.example.test.
http.Client.Jar with a fake RoundTripperStore a sample Set-Cookie from a fake response and send it on the next in-memory request.

A nil PublicSuffixList is not production-safe

The example creates a jar with a nil *Options, then simulates a Set-Cookie style Domain=example.test from https://foo.example.test/. With no public suffix list, the same cookie is also returned for https://bar.example.test/. That is the insecure sibling-domain behaviour official documentation warns about, shown here with reserved example.test names rather than live sites.

SetCookies does nothing if the URL scheme is not HTTP or HTTPS. Cookies returns the cookies that would be sent to that URL. The Domain field on the structs returned here is not relied on in the printed output; the test is which hosts receive the name and value.

cookiejar.New, Options, SetCookies, and Cookies

func New(o *Options) (*Jar, error)
type Options struct {
    PublicSuffixList PublicSuffixList
}
func (j *Jar) SetCookies(u *url.URL, cookies []*http.Cookie)
func (j *Jar) Cookies(u *url.URL) []*http.Cookie

With a nil PublicSuffixList, a cookie for example.test set from foo.example.test is also visible to bar.example.test.

ParameterDescription
oJar options. nil or a zero Options leaves PublicSuffixList nil. Official documentation calls that useful for testing and not secure.
u, cookiesThe URL of the setting server and the cookie list. Domain, names, and values in this example are fake.

Returns: New returns *Jar and an error. Cookies returns the cookies the jar would send to that URL.

Errors

  • error — New can fail if options are unusable; it is nil in this example.
  • This is not a SameSite or CORS demonstration, and it is not a browser compliance test.
go
package main

import (
	"fmt"
	"net/http"
	"net/http/cookiejar"
	"net/url"
)

func values(cookies []*http.Cookie) []string {
	out := make([]string, 0, len(cookies))
	for _, c := range cookies {
		out = append(out, c.Name+"="+c.Value)
	}
	return out
}

func main() {
	jar, err := cookiejar.New(nil)
	fmt.Println("new", err)

	foo, _ := url.Parse("https://foo.example.test/")
	bar, _ := url.Parse("https://bar.example.test/")
	jar.SetCookies(foo, []*http.Cookie{
		{Name: "session", Value: "fake-cookie-not-real", Domain: "example.test", Path: "/"},
	})
	fmt.Println("foo", values(jar.Cookies(foo)))
	fmt.Println("bar", values(jar.Cookies(bar)))
}

Expected output

new <nil>
foo [session=fake-cookie-not-real]
bar [session=fake-cookie-not-real]

Related: net/url, net/http (client)

Official documentation →

Client.Jar with a fake transport

When Client.Jar is set, the jar records cookies from a response and inserts them into later requests to a matching URL. The example uses a fake RoundTripper that always returns Set-Cookie: session=fake-cookie-not-real; Path=/. The first request sends no Cookie header; the second request to the same host sends the stored sample cookie. Nothing is read from a user store.

http.Client.Jar with a fake RoundTripper

func New(o *Options) (*Jar, error)
func (c *Client) Do(req *Request) (*Response, error)

Store a sample Set-Cookie from a fake response and send it on the next in-memory request.

ParameterDescription
JarThe Client field that holds the cookie jar. If it is nil, only cookies set on the Request are sent.

Returns: Do returns the fake 200 response. The interesting output is the Cookie header the transport sees on each request.

  • The cookie value is the literal fake-cookie-not-real. It is not a credential and is not read from the environment.
go
package main

import (
	"fmt"
	"io"
	"net/http"
	"net/http/cookiejar"
	"strings"
)

type roundTripFunc func(*http.Request) (*http.Response, error)

func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
	return f(req)
}

func main() {
	jar, err := cookiejar.New(nil)
	fmt.Println("new", err)
	client := &http.Client{
		Jar: jar,
		Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
			fmt.Printf("sent=%q\n", req.Header.Get("Cookie"))
			return &http.Response{
				StatusCode: http.StatusOK,
				Status:     "200 OK",
				Body:       io.NopCloser(strings.NewReader("ok")),
				Header:     http.Header{"Set-Cookie": {"session=fake-cookie-not-real; Path=/"}},
				Request:    req,
				Proto:      "HTTP/1.1",
				ProtoMajor: 1,
				ProtoMinor: 1,
			}, nil
		}),
	}

	req, _ := http.NewRequest(http.MethodGet, "https://app.example.test/login", nil)
	resp, err := client.Do(req)
	fmt.Println("first", err, resp.StatusCode)
	resp.Body.Close()

	req, _ = http.NewRequest(http.MethodGet, "https://app.example.test/home", nil)
	resp, err = client.Do(req)
	fmt.Println("second", err, resp.StatusCode)
	resp.Body.Close()
}

Expected output

new <nil>
sent=""
first <nil> 200
sent="session=fake-cookie-not-real"
second <nil> 200

Related: net/http (client), Official Client.Jar

Official documentation →