【よく使う】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
【対処法】Cursorで発生する「You've saved $102 on API model usage this month with Pro...」エラーの原因と対応
- article
Vue.js で作るモダンなフォームバリデーション
- article
Jest で setTimeout・setInterval をテストするコツ
- article
Playwright MCP でクロスリージョン同時テストを実現する
- article
Tailwind CSS と Alpine.js で動的 UI を作るベストプラクティス
- article
Storybook を Next.js プロジェクトに最短で導入する方法
- review
愛する勇気を持てば人生が変わる!『幸せになる勇気』岸見一郎・古賀史健のアドラー実践編で真の幸福を手に入れる
- review
週末を変えれば年収も変わる!『世界の一流は「休日」に何をしているのか』越川慎司の一流週末メソッド
- review
新しい自分に会いに行こう!『自分の変え方』村岡大樹の認知科学コーチングで人生リセット
- review
科学革命から AI 時代へ!『サピエンス全史 下巻』ユヴァル・ノア・ハラリが予見する人類の未来
- review
人類はなぜ地球を支配できた?『サピエンス全史 上巻』ユヴァル・ノア・ハラリが解き明かす驚愕の真実
- review
え?世界はこんなに良くなってた!『FACTFULNESS』ハンス・ロスリングが暴く 10 の思い込みの正体