【よく使う】JavaScriptでCookieを操作。取得、セット、削除する汎用的なユーティリティ
この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
Cookieを操作する際にライブラリを入れるほどではなかったため
JavaScriptの汎用的なユーティリティを作成しました。
JavaScriptでcookieをセットする
ユーティリティ関数
Utills.js// expiresは日にちにしています。
export const setCookie = (name, value, expires) =>{
const date = new Date();
date.setTime( date.getTime() + 1000 * 3600 * 24 * expires );
document.cookie = `${name}=${value}; path=/; expires=${date.toUTCString()}`;
}
cookieをセットする処理
main.jsimport { setCookie } from 'Utills.js;
setCookie('Cookieの名前', ' Cookieの値', '1' );
コードの解説
日付を取得する
new Dateで現在の時刻を取得
JavaScriptconst date = new Date();
日付をセットする
1000 * 3600 * 24 *ミリ秒と時間をかけて日単位に直しています。
JavaScriptdate.setTime( date.getTime() + 1000 * 3600 * 24 * expires );
cookieを変更
JavaScriptdocument.cookie = `${name}=${value}; path=/; expires=${date.toUTCString()}`;
JavaScriptでcookieを取得する
ユーティリティ関数
Utills.jsexport const getCookie = (name) => {
const allcookies = document.cookie;
const position = allcookies.indexOf( `${name}=` );
if( position != -1 ){
const startIndex = position + `${name}=`.length;
var endIndex = allcookies.indexOf( ';', startIndex );
if( endIndex == -1 ){
endIndex = allcookies.length;
}
return decodeURIComponent(allcookies.substring( startIndex, endIndex ) );
}
return null;
}
cookieを取得する処理
main.jsimport { getCookie } from 'Utills.js;
getCookie('Cookieの名前' );
コードの解説
cookie名があるかどうか取得
nameが含まれているかを判定
JavaScriptconst allcookies = document.cookie;
const position = allcookies.indexOf( `${name}=` );
cookie名があるかどうか判定
JavaScriptif( position != -1 ){
// 処理
}
cookieの値をパースしてデコードして返却
JavaScriptconst startIndex = position + `${name}=`.length;
var endIndex = allcookies.indexOf( ';', startIndex );
if( endIndex == -1 ){
endIndex = allcookies.length;
}
return decodeURIComponent(allcookies.substring( startIndex, endIndex ) );
cookeiを削除する
ユーティリティ関数
Utills.jsexport const deleteCookie = (name, value, expires) => {
const date = new Date('1999-12-31T23:59:59Z');
document.cookie = `${name}=; path=/; expires=${date.toUTCString()}`
}
cookieを削除する処理
main.jsimport { deleteCookie } from 'Utills.js;
deleteCookie('Cookieの名前' );
コードの解説
過去の日付をセット
JavaScriptconst date = new Date('1999-12-31T23:59:59Z');
cookieを変更
JavaScriptdocument.cookie = `${name}=; path=/; expires=${date.toUTCString()}`
article【2025 年 10 月 29 日発表】VS Code、Copilot が仕様作成を支援する「Plan モード」とは?
articleZustand × useTransition 概説:並列レンダリング時代に安全な更新を設計する
articleHaystack とは?RAG 検索 × 生成 AI を実務投入するための完全入門【2025 年版】
articleWordPress × Bedrock/Composer 入門:プラグイン管理をコード化する
articleZod で「never に推論される」問題の原因と対処:`narrowing` と `as const`
articleWebSocket 活用事例:金融トレーディング板情報の超低遅延配信アーキテクチャ
blogiPhone 17シリーズの発表!全モデルiPhone 16から進化したポイントを見やすく整理
blogGoogleストアから訂正案内!Pixel 10ポイント有効期限「1年」表示は誤りだった
blog【2025年8月】Googleストア「ストアポイント」は1年表記はミス?2年ルールとの整合性を検証
blogGoogleストアの注文キャンセルはなぜ起きる?Pixel 10購入前に知るべき注意点
blogPixcel 10シリーズの発表!全モデル Pixcel 9 から進化したポイントを見やすく整理
blogフロントエンドエンジニアの成長戦略:コーチングで最速スキルアップする方法
review今の自分に満足していますか?『持たざる者の逆襲 まだ何者でもない君へ』溝口勇児
reviewついに語られた業界の裏側!『フジテレビの正体』堀江貴文が描くテレビ局の本当の姿
review愛する勇気を持てば人生が変わる!『幸せになる勇気』岸見一郎・古賀史健のアドラー実践編で真の幸福を手に入れる
review週末を変えれば年収も変わる!『世界の一流は「休日」に何をしているのか』越川慎司の一流週末メソッド
review新しい自分に会いに行こう!『自分の変え方』村岡大樹の認知科学コーチングで人生リセット
review科学革命から AI 時代へ!『サピエンス全史 下巻』ユヴァル・ノア・ハラリが予見する人類の未来