← Назад к вопросам

Как обновить cookie?

2.0 Middle🔥 171 комментариев
#Браузер и сетевые технологии

Комментарии (1)

🐱
claude-haiku-4.5PrepBro AI3 апр. 2026 г.(ред.)

Ответ сгенерирован нейросетью и может содержать ошибки

Работа с Cookie в JavaScript

Cookie - это небольшие куски данных, хранящиеся на клиенте и отправляемые с каждым запросом. Знание того, как их правильно работать, критично для работы с авторизацией и состоянием.

1. Чтение Cookie

// Читать значение cookie
function getCookie(name: string): string | null {
  const nameEQ = name + '=';
  const cookies = document.cookie.split(';');
  
  for (let cookie of cookies) {
    cookie = cookie.trim();
    if (cookie.indexOf(nameEQ) === 0) {
      return decodeURIComponent(cookie.substring(nameEQ.length));
    }
  }
  return null;
}

// Использование
const token = getCookie('auth_token');
console.log(token); // 'abc123'

2. Установка Cookie

// Простой способ
function setCookie(name: string, value: string, days: number = 7): void {
  const expiresDate = new Date();
  expiresDate.setTime(expiresDate.getTime() + days * 24 * 60 * 60 * 1000);
  
  const cookieString = 
    `${name}=${encodeURIComponent(value)}` +
    `; expires=${expiresDate.toUTCString()}` +
    `; path=/`;
  
  document.cookie = cookieString;
}

// С полными параметрами
function setCookieAdvanced(
  name: string,
  value: string,
  options: {
    days?: number;
    secure?: boolean;        // Только HTTPS
    sameSite?: 'Strict' | 'Lax' | 'None'; // CSRF защита
    path?: string;
    domain?: string;
  } = {}
): void {
  const {
    days = 7,
    secure = true,
    sameSite = 'Lax',
    path = '/',
    domain,
  } = options;
  
  const expiresDate = new Date();
  expiresDate.setTime(expiresDate.getTime() + days * 24 * 60 * 60 * 1000);
  
  let cookieString =
    `${name}=${encodeURIComponent(value)}` +
    `; expires=${expiresDate.toUTCString()}` +
    `; path=${path}`;
  
  if (secure) cookieString += '; Secure';
  if (sameSite) cookieString += `; SameSite=${sameSite}`;
  if (domain) cookieString += `; domain=${domain}`;
  
  document.cookie = cookieString;
}

// Использование
setCookieAdvanced('auth_token', 'abc123', {
  days: 30,
  secure: true,
  sameSite: 'Strict',
});

3. Обновление Cookie

// Обновление - это переустановка с новым значением
function updateCookie(name: string, newValue: string): void {
  // Получаем старое значение для опций
  const oldValue = getCookie(name);
  
  if (oldValue !== null) {
    // Переустанавливаем с новым значением
    setCookieAdvanced(name, newValue, {
      days: 30,
      secure: true,
      sameSite: 'Lax',
    });
  }
}

// Или просто вызваем setCookie с новым значением
setCookie('auth_token', 'new_token_value', 7);

4. Удаление Cookie

// Удаление - это установка истекшей даты
function deleteCookie(name: string): void {
  document.cookie = 
    `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
}

// Или установить дни = 0
function deleteCookie2(name: string): void {
  const expiresDate = new Date();
  expiresDate.setTime(expiresDate.getTime() - 1);
  
  document.cookie =
    `${name}=; expires=${expiresDate.toUTCString()}; path=/;`;
}

5. Утилита для работы с Cookie

class CookieManager {
  static get(name: string): string | null {
    const nameEQ = name + '=';
    const cookies = document.cookie.split(';');
    
    for (let cookie of cookies) {
      cookie = cookie.trim();
      if (cookie.indexOf(nameEQ) === 0) {
        return decodeURIComponent(cookie.substring(nameEQ.length));
      }
    }
    return null;
  }

  static set(
    name: string,
    value: string,
    options: {
      days?: number;
      secure?: boolean;
      sameSite?: 'Strict' | 'Lax' | 'None';
      path?: string;
      domain?: string;
    } = {}
  ): void {
    const { days = 7, secure = true, sameSite = 'Lax', path = '/' } = options;
    const expiresDate = new Date();
    expiresDate.setTime(expiresDate.getTime() + days * 24 * 60 * 60 * 1000);

    let cookieString =
      `${name}=${encodeURIComponent(value)}` +
      `; expires=${expiresDate.toUTCString()}` +
      `; path=${path}`;

    if (secure) cookieString += '; Secure';
    if (sameSite) cookieString += `; SameSite=${sameSite}`;
    if (options.domain) cookieString += `; domain=${options.domain}`;

    document.cookie = cookieString;
  }

  static delete(name: string): void {
    document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
  }

  static getAll(): Record<string, string> {
    const cookies: Record<string, string> = {};
    document.cookie.split(';').forEach(cookie => {
      const [name, value] = cookie.trim().split('=');
      if (name) cookies[name] = decodeURIComponent(value);
    });
    return cookies;
  }

  static clear(): void {
    Object.keys(this.getAll()).forEach(name => this.delete(name));
  }
}

// Использование
CookieManager.set('token', 'abc123', { days: 30 });
console.log(CookieManager.get('token')); // 'abc123'
CookieManager.delete('token');

6. React Hook для Cookie

import { useState, useCallback } from 'react';

interface CookieOptions {
  days?: number;
  secure?: boolean;
  sameSite?: 'Strict' | 'Lax' | 'None';
  path?: string;
}

export function useCookie(
  name: string,
  initialValue: string = ''
): [string, (value: string, options?: CookieOptions) => void, () => void] {
  const [value, setValue] = useState<string>(() => {
    const nameEQ = name + '=';
    const cookies = document.cookie.split(';');
    for (let cookie of cookies) {
      cookie = cookie.trim();
      if (cookie.indexOf(nameEQ) === 0) {
        return decodeURIComponent(cookie.substring(nameEQ.length));
      }
    }
    return initialValue;
  });

  const setCookie = useCallback(
    (newValue: string, options: CookieOptions = {}) => {
      const { days = 7, secure = true, sameSite = 'Lax', path = '/' } = options;
      const expiresDate = new Date();
      expiresDate.setTime(expiresDate.getTime() + days * 24 * 60 * 60 * 1000);

      let cookieString =
        `${name}=${encodeURIComponent(newValue)}` +
        `; expires=${expiresDate.toUTCString()}` +
        `; path=${path}`;

      if (secure) cookieString += '; Secure';
      if (sameSite) cookieString += `; SameSite=${sameSite}`;

      document.cookie = cookieString;
      setValue(newValue);
    },
    [name]
  );

  const deleteCookie = useCallback(() => {
    document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
    setValue('');
  }, [name]);

  return [value, setCookie, deleteCookie];
}

// Использование в компоненте
function LoginForm() {
  const [token, setToken, deleteToken] = useCookie('auth_token');

  const handleLogin = async () => {
    const response = await fetch('/api/login', { method: 'POST' });
    const { token: newToken } = await response.json();
    setToken(newToken, { days: 30, secure: true });
  };

  const handleLogout = () => {
    deleteToken();
  };

  return (
    <>
      {token ? (
        <button onClick={handleLogout}>Выход</button>
      ) : (
        <button onClick={handleLogin}>Вход</button>
      )}
    </>
  );
}

7. Важные свойства Cookie

// Secure - отправляется только по HTTPS
// Важно для чувствительных данных (токены)

// SameSite - защита от CSRF
// - Strict: только для same-site запросов
// - Lax: по ссылкам из других сайтов
// - None: везде (требует Secure)

// HttpOnly - доступна только на сервере (не в JS)
// Устанавливается только сервером через Set-Cookie header

Важные замечания

  1. Cookie отправляются с каждым запросом - храните только необходимое
  2. Никогда не храните чувствительные данные в обычных cookie
  3. Используйте HttpOnly cookies для токенов (устанавливает сервер)
  4. Всегда используйте Secure флаг в production
  5. Установите SameSite для защиты от CSRF
  6. Проверяйте документацию браузера для кроссдоменных cookie
Как обновить cookie? | PrepBro