A simple and flexible cookie handler for JavaScript and TypeScript projects.
npm install cookie-handler-pro
OR
npm i cookie-handler-pro
import { setCookie } from 'cookie-handler-pro';
//Set a cookie with various options
setCookie('username', 'john_doe', {
expires: '7d', // Expires in 7 days
path: '/',
domain: 'example.com',
secure: true,
sameSite: 'Lax'});
// Set a cookie to expire in 2 hours
setCookie('session', 'abcd1234', { expires: '2h', path: '/'});
import { getCookie } from 'cookie-handler-pro';
const username = getCookie('username');console.log(username); // Output: 'john_doe'
import { deleteCookie } from 'cookie-handler-pro';
deleteCookie('username', { path: '/', domain: 'example.com' });
// pages/api/set-username.ts
import { NextApiRequest, NextApiResponse } from 'next';
import { setCookie } from 'cookie-handler-pro';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
setCookie('username', 'john_doe', {
expires: '7d',
path: '/',
domain: req.headers.host,
secure: process.env.NODE_ENV === 'production',
sameSite: 'Lax'
});
res.status(200).json({ message: 'Cookie set successfully' });
}
// pages/index.tsx
import { useEffect, useState } from 'react';
import { getCookie } from 'cookie-handler-pro';
const HomePage = () => {
const [username, setUsername] = useState(null);
useEffect(() => {
const cookieValue = getCookie('username');
setUsername(cookieValue);
}, []);
return <div>Username: {username}</div>;
};
export default HomePage;
// pages/api/delete-username.ts
import { NextApiRequest, NextApiResponse } from 'next';
import { deleteCookie } from 'cookie-handler-pro';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
deleteCookie('username', { path: '/', domain: req.headers.host });
res.status(200).json({ message: 'Cookie deleted successfully' });
}
"use client";
import { getCookie, setCookie, deleteCookie } from 'cookie-handler-pro';
export default function Home() {
const handleSetCookie = () => {
setCookie("username", "john_doe", {
expires: "7d",
path: "/",
domain: window.location.hostname, // Use window.location.hostname instead of req.headers.host
secure: process.env.NODE_ENV === "production",
sameSite: "Lax",
});
};
const handleDeleteCookie = () => {
deleteCookie("username");
};
const value = getCookie("username");
return (
<>
<button onClick={handleSetCookie}>Set Cookie</button>
<button onClick={handleDeleteCookie}>Delete Cookie</button>
<h1>Cookies: {value}</h1>
</>
);
}
Author N R SHAGOR