Introduction to Tough-Cookie
Tough-cookie is a library designed for managing HTTP cookies in Node.js and the browser. It is a robust solution for handling cookie stores, parsing and serializing cookies, and managing cookie expiration.
Installing Tough-Cookie
npm install tough-cookie
Core API Examples
Create a Cookie Store
const tough = require('tough-cookie'); const cookieJar = new tough.CookieJar();
Set a Cookie
cookieJar.setCookie('key=value; Domain=example.com; Path=/', 'http://example.com', (err, cookie) => { if (err) throw err; console.log(cookie); });
Get Cookies for a Domain
cookieJar.getCookies('http://example.com', (err, cookies) => { if (err) throw err; console.log(cookies); });
Get a Specific Cookie
cookieJar.getCookieString('http://example.com', (err, cookieString) => { if (err) throw err; console.log(cookieString); });
Serialize a CookieJar
cookieJar.serialize((err, serializedJar) => { if (err) throw err; console.log(serializedJar); });
Deserialize a CookieJar
const serialized = {/* serialized cookie jar object */}; tough.CookieJar.deserialize(serialized, (err, cookieJar) => { if (err) throw err; console.log(cookieJar); });
Sample Application Using Tough-Cookie
Here is a simple example demonstrating how you can use tough-cookie to manage cookies in a Node.js application:
const http = require('http'); const tough = require('tough-cookie'); const cookieJar = new tough.CookieJar(); http.createServer((req, res) => { // Set cookies const setCookie = tough.Cookie.parse('session=abc123; Domain=localhost; Path=/'); cookieJar.setCookieSync(setCookie, 'http://localhost'); // Get cookies cookieJar.getCookies('http://localhost', (err, cookies) => { if (err) throw err; res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(`Cookies: ${cookies.join('; ')}`); }); }).listen(3000, () => { console.log('Server running at http://localhost:3000/'); });
Conclusion
Tough-cookie is an essential tool for developers requiring efficient and robust cookie management. Its comprehensive API ensures that cookies are handled safely and in accordance with HTTP standards.
Start incorporating tough-cookie into your Node.js applications to simplify your cookie management tasks today!
Hash: e95bbdc51fa9675aba6ac640de29af4887ef93d0a5f9d513e59d4256e45262ad