yuniq-cookie is a sophisticated cookie management library for Node.js, designed to handle cookies in various use cases such as web scraping, browser automation, API consumption, and more. This library offers advanced features such as cookie expiration management, domain filtering, serialization for HTTP requests, and the ability to import/export cookies in Netscape format.
Inspired by the tough-cookie library, yuniq-cookie brings additional functionality and detailed cookie representation for use in modern applications.
Features
• Comprehensive Cookie Management: Add, remove, retrieve, and iterate over cookies easily.
• Expiration Management: Automatically handles expired cookies.
• Domain-Specific Handling: Work with cookies filtered by specific domains or URLs.
• Netscape Format Support: Import and export cookies using the classic Netscape cookie format.
• Detailed Cookie Representation: Inspect cookies in detailed format, useful for debugging or data export.
• Asynchronous Operations: Seamless integration of async workflows using callback-based APIs.
• HTTP Header Serialization: Convert cookies into formats suitable for HTTP requests and responses.
Installation
Install the package via npm:
npm install yuniq-cookie
Usage
Basic Example
const { CookieJar } = require('yuniq-cookie');
// Create a new CookieJar instance
const jar = new CookieJar();
// Add a cookie to the jar
jar.setCookieSync('name=value; Domain=example.com', 'http://example.com');
// Retrieve all cookies for a domain
const cookies = jar.getAllCookies('http://example.com');
console.log(cookies);
// Convert cookies to a header string for HTTP requests
const cookieHeader = jar.toHeader('http://example.com');
console.log(cookieHeader); // Outputs "name=value" for the Cookie header
// Check the number of cookies stored in the jar
console.log(jar.size); // Outputs the number of cookies stored
API Reference
Core Methods
fromArray(cookies: DetailedCookie[]): void
Imports an array of cookies into the CookieJar. This method is particularly useful when you have an external source of cookies (such as a session export) that you want to restore in the current context.
• Parameters:
• cookies: An array of DetailedCookie objects to be added to the jar. Each cookie should follow the detailed structure, including properties like name, value, domain, path, and expires.
• Usage:
const detailedCookies = [
{ name: 'session', value: 'xyz', domain: 'example.com', path: '/', expires: new Date() },
{ name: 'token', value: 'abc', domain: 'example.com', path: '/', expires: new Date() }
];
jar.fromArray(detailedCookies);
console.log(jar.size); // The number of cookies now includes the imported cookies
setResponseCookies(cookies: string[], url: string): void
Parses and stores cookies received from an HTTP response. This method is designed to handle the Set-Cookie header from HTTP responses, allowing you to store cookies associated with a specific URL.
• Parameters:
• cookies: An array of strings representing the cookies from the Set-Cookie header.
• url: The URL from which the cookies were received. This ensures that the cookies are stored with the correct domain and path information.
• Usage:
const responseCookies = [
'sessionid=abc123; Domain=example.com; Path=/; HttpOnly',
'user_token=xyz789; Domain=example.com; Path=/; Secure'
];
jar.setResponseCookies(responseCookies, 'http://example.com');
console.log(jar.getAllCookies('http://example.com')); // Outputs the parsed cookies
toNetscapeFormat(): string
Serializes all cookies in the CookieJar to the Netscape cookie file format. This format is often used for saving and loading cookies in older tools and browser extensions. It’s a simple plain-text format that is still widely supported for certain applications.
• Returns: A string containing all cookies in the Netscape format, which can be saved to a file or sent to an external application.
• Usage:
const netscapeFormat = jar.toNetscapeFormat();
console.log(netscapeFormat); // Outputs the Netscape-style cookie string
parseNetscapeCookies(netscapeCookieString: string): void
Parses a string containing cookies in the Netscape format and adds them to the CookieJar. This method is useful when you need to import cookies from tools that export in the Netscape format (e.g., browser extensions).
• Parameters:
• netscapeCookieString: A string containing cookies in the Netscape format.
• Usage:
const netscapeCookieString = `
Netscape HTTP Cookie File
.example.com TRUE / FALSE 0 sessionid abc123
.example.com TRUE / FALSE 0 user_token xyz789
`;
jar.parseNetscapeCookies(netscapeCookieString);
console.log(jar.getAllCookies('http://example.com')); // The cookies are now added to the jar
toCookieString(url: string): string
Converts the cookies associated with a specific domain or URL into a string formatted for use in an HTTP Cookie header. This is useful when sending requests to servers that expect cookies in the Cookie header.
• Parameters:
• url: The URL or domain for which to serialize the cookies.
• Returns: A string that can be used in the Cookie header of an HTTP request, formatted as name=value; another=cookie.
• Usage:
const cookieString = jar.toCookieString('http://example.com');
console.log(cookieString); // Outputs "sessionid=abc123; user_token=xyz789"
General Methods
setCookieSync(cookieString: string, url: string): void
Synchronously sets a cookie in the CookieJar. The cookieString should follow the standard cookie format (e.g., name=value; Domain=example.com; Path=/; Expires=...).
• Parameters:
• cookieString: The string representation of the cookie to be added.
• url: The URL that the cookie is associated with.
getAllCookies(url: string): Cookie[]
Retrieves all cookies stored in the jar that are associated with a specific domain or URL.
• Parameters:
• url: The domain or URL for which to retrieve cookies.
• Returns: An array of Cookie objects.
toArray(): DetailedCookie[]
Converts all non-expired cookies in the jar into an array of DetailedCookie objects. Each DetailedCookie includes properties such as name, value, domain, path, expires, and more.
• Returns: An array of DetailedCookie objects.
isEmpty(): boolean
Checks whether the cookie jar is empty.
• Returns: true if the jar is empty, otherwise false.
size(): number
Returns the total number of cookies currently stored in the jar.
Symbol.iterator: Iterator
Enables iteration over the cookies in the jar using a for...of loop. Each iteration yields a Cookie object.
• Usage:
for (const cookie of jar) {
console.log(cookie);
}
Advanced Example
Handling Cookies in HTTP Responses
const responseCookies = [
'auth_token=abcdef; Domain=example.com; Path=/; HttpOnly',
'session_id=xyz123; Domain=example.com; Path=/; Secure'
];
// Set cookies from HTTP response
jar.setResponseCookies(responseCookies, 'http://example.com');
// Retrieve and inspect cookies
const cookies = jar.getAllCookies('http://example.com');
console.log(cookies);
// Serialize cookies for sending in an HTTP request
const cookieHeader = jar.toCookieString('http://example.com');
console.log(cookieHeader); // "auth_token=abcdef; session_id=xyz123"
Importing and Exporting Netscape Cookies
// Export cookies to Netscape format
const netscapeCookies = jar.toNetscapeFormat();
console.log(netscapeCookies);
// Parse and import cookies from Netscape format
const netscapeCookieString = `
Netscape HTTP Cookie File
.example.com TRUE / FALSE 0 auth_token abc123
.example.com TRUE / FALSE 0 session_id xyz789
`;
jar.parseNetscapeCookies(netscapeCookieString);
console.log('Netscape cookies parsed and added to the jar.');
Conclusion
yuniq-cookie offers a complete solution for managing HTTP cookies in Node.js environments. Whether you’re dealing with cookie expiration, domain-specific filtering, or exporting cookies in Netscape format, this library provides the flexibility and power needed for handling cookies in modern applications.
By supporting both synchronous and asynchronous workflows, as well as detailed cookie management features, yuniq-cookie is the ideal choice for any developer looking for a robust cookie management solution.
Explore the API to take full advantage of its capabilities, and feel free to contribute or report issues on the GitHub repository!
License
This project is licensed under the MIT License.