Nextjs function set và get cookie
// Lấy cookie từ document.cookie
export const getCookie = (name: string): string | null => {
if (typeof document === 'undefined') return null; // Ngăn lỗi SSR
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) {
const part = parts.pop();
if (part) {
return part.split(';').shift() || null;
}
}
return null;
};
export async function setCookie(name: string, value: string, days: number = 10) {
if (typeof document === 'undefined') return; // Chạy client-side thôi
if (!name || !value) return; // Tránh lỗi set cookie rỗng
const now = new Date();
now.setTime(now.getTime() + days * 24 * 60 * 60 * 1000);
const cookieString = `${encodeURIComponent(name)}=${encodeURIComponent(value)}; path=/; expires=${now.toUTCString()}; secure; samesite=strict`;
document.cookie = cookieString;
}
// Hàm xóa cookie
export function deleteCookie(name: string) {
document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
}
// Đặt cookie cho token và refreshToken
export async function setAuthCookies(token: string, refreshToken: string) {
// Token: hết hạn sau 2 giờ
await setCookie('token', token, 2 / 24); // 2 giờ = 2 / 24 ngày
// Refresh token: hết hạn sau 60 ngày
await setCookie('refreshToken', refreshToken, 60);
}
// ❌ Hàm xóa token và refreshToken
export function clearAuthCookies() {
deleteCookie('token');
deleteCookie('refreshToken');
}