The CookieJar class provides HTTP cookie storage and management, extending tough-cookie's CookieJar with jsdom-specific defaults.
Creates a cookie jar for storing HTTP cookies. jsdom's CookieJar enables loose mode by default to match browser behavior.
/**
* Creates a cookie jar
* @param store - Optional cookie store (from tough-cookie)
* @param options - Configuration options
*/
constructor(store?: toughCookie.Store, options?: CookieJarOptions);
interface CookieJarOptions {
/**
* Enables loose mode parsing (matches browser behavior)
* @default true (jsdom default)
*/
looseMode?: boolean;
/**
* Rejects cookies from public suffix domains
* @default true (tough-cookie default)
*/
rejectPublicSuffixes?: boolean;
/**
* Allows cookies on special use domains
* @default true (tough-cookie default)
*/
allowSpecialUseDomain?: boolean;
}Usage Examples:
const { JSDOM, CookieJar } = require("jsdom");
// Basic usage - looseMode is true by default
const cookieJar = new CookieJar();
const dom = new JSDOM(``, { cookieJar });
// Share cookie jar between multiple jsdoms
const sharedJar = new CookieJar();
const dom1 = new JSDOM(``, { cookieJar: sharedJar, url: "https://example.org/" });
const dom2 = new JSDOM(``, { cookieJar: sharedJar, url: "https://example.org/" });
// Both jsdoms share the same cookies
// With custom options
const strictJar = new CookieJar(null, {
looseMode: false,
rejectPublicSuffixes: true
});Cookies that match the document's domain and are not marked HTTP-only are accessible via document.cookie.
Usage Example:
const { JSDOM, CookieJar } = require("jsdom");
const cookieJar = new CookieJar();
// Set cookies programmatically
cookieJar.setCookieSync("sessionid=abc123", "https://example.org/");
cookieJar.setCookieSync("user=john", "https://example.org/");
const dom = new JSDOM(``, {
url: "https://example.org/",
cookieJar
});
// Access cookies from the page
console.log(dom.window.document.cookie);
// "sessionid=abc123; user=john"
// Set cookies from the page
dom.window.document.cookie = "theme=dark";
// Cookie is now in the jar
const cookies = cookieJar.getCookiesSync("https://example.org/");
console.log(cookies.map(c => c.toString()));
// ["sessionid=abc123", "user=john", "theme=dark"]HTTP-only cookies are stored in the cookie jar but not accessible via document.cookie.
Usage Example:
const { JSDOM, CookieJar } = require("jsdom");
const cookieJar = new CookieJar();
// Set an HTTP-only cookie
cookieJar.setCookieSync("session=secret; HttpOnly", "https://example.org/");
// Set a regular cookie
cookieJar.setCookieSync("user=john", "https://example.org/");
const dom = new JSDOM(``, {
url: "https://example.org/",
cookieJar
});
// HTTP-only cookie is not visible via document.cookie
console.log(dom.window.document.cookie);
// "user=john" (session=secret is hidden)
// But it's still in the jar and will be sent with requests
const allCookies = cookieJar.getCookiesSync("https://example.org/");
console.log(allCookies.map(c => c.key));
// ["session", "user"]Cookies in the jar affect subresource requests when resources: "usable" is enabled.
Usage Example:
const { JSDOM, CookieJar } = require("jsdom");
const cookieJar = new CookieJar();
cookieJar.setCookieSync("auth=token123", "https://example.org/");
const dom = new JSDOM(`
<html>
<head>
<script src="https://example.org/script.js"></script>
</head>
</html>
`, {
url: "https://example.org/",
resources: "usable",
runScripts: "dangerously",
cookieJar
});
// When script.js is fetched, the Cookie header will include "auth=token123"Cookies from HTTP Set-Cookie response headers are automatically stored in the cookie jar when using fromURL().
Usage Example:
const { JSDOM, CookieJar } = require("jsdom");
const cookieJar = new CookieJar();
// Add cookies before the request
cookieJar.setCookieSync("tracking=xyz", "https://example.com/");
JSDOM.fromURL("https://example.com/", { cookieJar }).then(dom => {
// Cookies from the request are sent as Cookie header
// Cookies from Set-Cookie response headers are added to the jar
// Check all cookies in the jar
const cookies = cookieJar.getCookiesSync("https://example.com/");
console.log(cookies);
// Includes both the tracking cookie we set and any from Set-Cookie headers
// Access non-HTTP-only cookies from the page
console.log(dom.window.document.cookie);
});jsdom's CookieJar extends tough-cookie's CookieJar, providing access to all tough-cookie methods.
// CookieJar extends tough-cookie's CookieJar
// Provides all tough-cookie methods including:
/**
* Set a cookie (synchronous)
*/
setCookieSync(cookieOrString: string | Cookie, currentUrl: string, options?: object): Cookie;
/**
* Set a cookie (asynchronous)
*/
setCookie(cookieOrString: string | Cookie, currentUrl: string, options?: object, callback?: (error: Error | null, cookie: Cookie) => void): void;
/**
* Get cookies for a URL (synchronous)
*/
getCookiesSync(currentUrl: string, options?: object): Cookie[];
/**
* Get cookies for a URL (asynchronous)
*/
getCookies(currentUrl: string, options?: object, callback?: (error: Error | null, cookies: Cookie[]) => void): void;
/**
* Get cookie string for a URL (synchronous)
*/
getCookieStringSync(currentUrl: string, options?: object): string;
/**
* Get cookie string for a URL (asynchronous)
*/
getCookieString(currentUrl: string, options?: object, callback?: (error: Error | null, cookieString: string) => void): void;
/**
* Remove all cookies (synchronous)
*/
removeAllCookiesSync(): void;
/**
* Remove all cookies (asynchronous)
*/
removeAllCookies(callback?: (error: Error | null) => void): void;
// And many more tough-cookie methods...Usage Example:
const { JSDOM, CookieJar } = require("jsdom");
const cookieJar = new CookieJar();
// Use tough-cookie's synchronous methods
cookieJar.setCookieSync(
"session=abc; Path=/; Secure; SameSite=Strict",
"https://example.org/"
);
// Get cookies with options
const cookies = cookieJar.getCookiesSync("https://example.org/secure/", {
secure: true,
sameSiteContext: "strict"
});
// Get cookie string (formatted for Cookie header)
const cookieString = cookieJar.getCookieStringSync("https://example.org/");
console.log(cookieString); // "session=abc"
// Use tough-cookie's asynchronous methods
cookieJar.getCookies("https://example.org/", (err, cookies) => {
if (err) {
console.error(err);
} else {
console.log(cookies);
}
});The toughCookie export provides access to the tough-cookie module used by jsdom.
// Access to tough-cookie module
import { toughCookie } from "jsdom";
// Provides access to:
// - toughCookie.Cookie class
// - toughCookie.CookieJar class
// - toughCookie.Store base class
// - toughCookie.MemoryCookieStore
// - Various utilities and constantsUsage Example:
const { JSDOM, CookieJar, toughCookie } = require("jsdom");
// Use tough-cookie's Cookie class
const cookie = new toughCookie.Cookie({
key: "session",
value: "abc123",
domain: "example.org",
path: "/",
secure: true,
httpOnly: true,
maxAge: 3600
});
// Set the cookie using the Cookie object
const cookieJar = new CookieJar();
cookieJar.setCookieSync(cookie, "https://example.org/");
// Use tough-cookie utilities
const canonicalDomain = toughCookie.canonicalDomain("EXAMPLE.ORG");
console.log(canonicalDomain); // "example.org"
// Create custom cookie store
class CustomStore extends toughCookie.Store {
constructor() {
super();
this.idx = {};
}
findCookie(domain, path, key, cb) {
// Custom implementation
}
// ... implement other Store methods
}
const customJar = new CookieJar(new CustomStore());Cookies are automatically filtered based on the document's URL.
Usage Example:
const { JSDOM, CookieJar } = require("jsdom");
const cookieJar = new CookieJar();
// Set cookies for different domains and paths
cookieJar.setCookieSync("global=1; Domain=example.org", "https://example.org/");
cookieJar.setCookieSync("api=2; Path=/api", "https://example.org/api/");
cookieJar.setCookieSync("admin=3; Path=/admin", "https://example.org/admin/");
// Document at root path sees global and no path-specific cookies
const dom1 = new JSDOM(``, {
url: "https://example.org/",
cookieJar
});
console.log(dom1.window.document.cookie); // "global=1"
// Document at /api path sees global and api cookies
const dom2 = new JSDOM(``, {
url: "https://example.org/api/endpoint",
cookieJar
});
console.log(dom2.window.document.cookie); // "global=1; api=2"
// Document at /admin path sees global and admin cookies
const dom3 = new JSDOM(``, {
url: "https://example.org/admin/panel",
cookieJar
});
console.log(dom3.window.document.cookie); // "global=1; admin=3"You can pre-populate a cookie jar before creating jsdom instances.
Usage Example:
const { JSDOM, CookieJar } = require("jsdom");
// Prime the jar with initial cookies
const cookieJar = new CookieJar();
cookieJar.setCookieSync("user_id=12345", "https://app.example.com/");
cookieJar.setCookieSync("session_token=abc123", "https://app.example.com/");
cookieJar.setCookieSync("preferences=dark_mode", "https://app.example.com/");
// Use the primed jar with jsdom
const dom = new JSDOM(`
<script>
console.log("Cookies:", document.cookie);
// Will log all the pre-set cookies
</script>
`, {
url: "https://app.example.com/",
runScripts: "dangerously",
cookieJar
});
// Useful for testing authenticated scenarios
async function testAuthenticatedPage() {
const jar = new CookieJar();
jar.setCookieSync("auth=valid_token", "https://example.com/");
const dom = await JSDOM.fromURL("https://example.com/dashboard", {
cookieJar: jar
});
// The request will include the auth cookie
return dom.window.document.title;
}