
JavaScript クッキー&ローカルストレージ チートシート:ステップバイステップで学ぶデータ保存テクニック
Djangoでのセッション処理に悩んでいる新人エンジニアの方向け
▼チートシートだけ欲しい方はこちらからダウンロードしてください
🍪 クイックリファレンス:クッキー操作
クッキーの基本操作
// クッキーを設定
document.cookie = "name=value";
// 有効期限付きクッキーを設定(30日間)
document.cookie = "name=value; expires=" + new Date(Date.now() + 86400000 * 30).toUTCString();
// パスを指定(サイト全体で利用可能に)
document.cookie = "name=value; path=/";
// セキュアフラグ(HTTPS接続のみ)
document.cookie = "name=value; secure";
// SameSite属性
document.cookie = "name=value; samesite=strict"; // または "lax", "none"
// すべてのオプションを組み合わせたセキュアな設定
document.cookie = "name=value; expires=" + new Date(Date.now() + 86400000 * 30).toUTCString() +
"; path=/; secure; samesite=strict";
クッキーヘルパー関数
// クッキー設定関数
function setCookie(name, value, days = 30, secure = true, sameSite = "lax") {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
let cookie = name + "=" + encodeURIComponent(value) +
"; expires=" + date.toUTCString() +
"; path=/";
if (secure) cookie += "; secure";
if (sameSite) cookie += "; samesite=" + sameSite;
document.cookie = cookie;
}
// クッキー取得関数
function getCookie(name) {
const nameEQ = name + "=";
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1);
if (c.indexOf(nameEQ) === 0)
return decodeURIComponent(c.substring(nameEQ.length, c.length));
}
return null;
}
// クッキー削除関数
function deleteCookie(name) {
document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}
🗄️ クイックリファレンス:ローカルストレージ操作
// 保存
localStorage.setItem("key", "value");
// オブジェクトの保存
localStorage.setItem("user", JSON.stringify({ name: "山田", id: 123 }));
// 取得
const value = localStorage.getItem("key");
// オブジェクトの取得
const user = JSON.parse(localStorage.getItem("user"));
// 削除
localStorage.removeItem("key");
// すべて削除
localStorage.clear();
🔄 セッションストレージ(ブラウザを閉じると消去)
// 保存
sessionStorage.setItem("key", "value");
// 取得
const value = sessionStorage.getItem("key");
// 削除
sessionStorage.removeItem("key");
ステップバイステップ:クッキー&ストレージの活用方法
ステップ1:基本的なページ設定
まず、HTMLとJavaScriptのファイルを作成します。
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>クッキー&ストレージデモ</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>データ保存デモ</h1>
<div id="app">
<!-- コンテンツはここに入ります -->
</div>
</div>
<script src="storage.js"></script>
<script src="app.js"></script>
</body>
</html>
storage.js(クッキーとストレージのヘルパー関数)
// クッキー関連のヘルパー関数
const CookieManager = {
// クッキー設定
set: function(name, value, days = 30, secure = true, sameSite = "lax") {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
let cookie = name + "=" + encodeURIComponent(value) +
"; expires=" + date.toUTCString() +
"; path=/";
if (secure && location.protocol === 'https:') cookie += "; secure";
if (sameSite) cookie += "; samesite=" + sameSite;
document.cookie = cookie;
},
// クッキー取得
get: function(name) {
const nameEQ = name + "=";
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1);
if (c.indexOf(nameEQ) === 0)
return decodeURIComponent(c.substring(nameEQ.length, c.length));
}
return null;
},
// クッキー削除
delete: function(name) {
document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}
};
// ローカルストレージ関連のヘルパー関数
const StorageManager = {
// オブジェクトを保存(JSON形式)
setObject: function(key, object) {
localStorage.setItem(key, JSON.stringify(object));
},
// オブジェクトを取得
getObject: function(key) {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : null;
},
// 保存(通常のキーと値)
set: function(key, value) {
localStorage.setItem(key, value);
},
// 取得
get: function(key) {
return localStorage.getItem(key);
},
// 削除
delete: function(key) {
localStorage.removeItem(key);
},
// すべて削除
clear: function() {
localStorage.clear();
}
};
ステップ2:ユーザー設定の保存(テーマ切り替え)
app.jsにテーマ切り替え機能を追加
// アプリケーションのUI構築
function buildUI() {
const app = document.getElementById('app');
// テーマ切り替えのUIを構築
const themeSection = document.createElement('section');
themeSection.className = 'section';
themeSection.innerHTML = `
<h2>テーマ設定</h2>
<div class="options">
<button id="theme-light" class="btn">ライト</button>
<button id="theme-dark" class="btn">ダーク</button>
<button id="theme-auto" class="btn">自動</button>
</div>
`;
app.appendChild(themeSection);
// イベントリスナーを追加
document.getElementById('theme-light').addEventListener('click', () => setTheme('light'));
document.getElementById('theme-dark').addEventListener('click', () => setTheme('dark'));
document.getElementById('theme-auto').addEventListener('click', () => setTheme('auto'));
}
// テーマを設定する関数
function setTheme(theme) {
document.body.className = theme === 'auto'
? (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
: theme;
// テーマ設定をクッキーに保存(30日間)
CookieManager.set('theme', theme, 30);
// アクティブボタンのスタイルを更新
updateActiveButton(theme);
}
// アクティブボタンのスタイルを更新
function updateActiveButton(theme) {
document.querySelectorAll('.options button').forEach(btn => {
btn.classList.remove('active');
});
document.getElementById(`theme-${theme}`).classList.add('active');
}
// 保存されたテーマを適用
function applyTheme() {
const savedTheme = CookieManager.get('theme') || 'light';
setTheme(savedTheme);
}
// 初期化
function init() {
buildUI();
applyTheme();
}
// ページ読み込み時に実行
window.addEventListener('DOMContentLoaded', init);
style.cssにテーマのスタイルを追加
/* 基本スタイル */
* {
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
line-height: 1.6;
margin: 0;
padding: 0;
transition: background-color 0.3s, color 0.3s;
}
/* ライトテーマ(デフォルト) */
body, body.light {
background-color: #f9f9f9;
color: #333;
}
/* ダークテーマ */
body.dark {
background-color: #222;
color: #eee;
}
.container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.section {
background-color: rgba(255, 255, 255, 0.1);
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
.options {
display: flex;
gap: 10px;
}
.btn {
padding: 8px 16px;
border: none;
border-radius: 4px;
cursor: pointer;
background-color: #e0e0e0;
color: #333;
}
body.dark .btn {
background-color: #444;
color: #eee;
}
.btn.active {
background-color: #4a90e2;
color: white;
}
body.dark .btn.active {
background-color: #2d6bc9;
}
ステップ3:ユーザー情報の維持(ログイン状態)
app.jsにログイン機能を追加
// UIにログインセクションを追加
function buildLoginUI() {
const app = document.getElementById('app');
const loginSection = document.createElement('section');
loginSection.className = 'section';
loginSection.innerHTML = `
<h2>ユーザーログイン</h2>
<div id="login-status"></div>
<div id="login-form">
<input type="text" id="username" placeholder="ユーザー名" />
<input type="password" id="password" placeholder="パスワード" />
<button id="btn-login" class="btn">ログイン</button>
</div>
<button id="btn-logout" class="btn" style="display: none;">ログアウト</button>
`;
app.appendChild(loginSection);
// イベントリスナーを追加
document.getElementById('btn-login').addEventListener('click', handleLogin);
document.getElementById('btn-logout').addEventListener('click', handleLogout);
// 既存のログイン状態をチェック
checkLoginStatus();
}
// ログイン処理
function handleLogin() {
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
if (!username || !password) {
alert('ユーザー名とパスワードを入力してください');
return;
}
// 実際のアプリケーションではサーバーと通信して認証を行う
// ここではデモのため単純化
const user = {
username: username,
loginTime: new Date().toISOString(),
isLoggedIn: true
};
// ユーザー情報をローカルストレージに保存
StorageManager.setObject('user', user);
// ログインステータスを更新
updateLoginStatus(user);
}
// ログアウト処理
function handleLogout() {
// ユーザー情報を削除
StorageManager.delete('user');
// ログインステータスを更新
updateLoginStatus(null);
}
// ログインステータスの確認
function checkLoginStatus() {
const user = StorageManager.getObject('user');
updateLoginStatus(user);
}
// ログインステータスの表示を更新
function updateLoginStatus(user) {
const loginStatus = document.getElementById('login-status');
const loginForm = document.getElementById('login-form');
const logoutBtn = document.getElementById('btn-logout');
if (user && user.isLoggedIn) {
// ログイン済み
loginStatus.innerHTML = `
<p>ようこそ、<strong>${user.username}</strong>さん!</p>
<p>ログイン時間: ${new Date(user.loginTime).toLocaleString()}</p>
`;
loginForm.style.display = 'none';
logoutBtn.style.display = 'block';
} else {
// 未ログイン
loginStatus.innerHTML = '<p>ログインしていません</p>';
loginForm.style.display = 'block';
logoutBtn.style.display = 'none';
}
}
// 初期化関数を更新
function init() {
buildUI(); // テーマ設定UI
buildLoginUI(); // ログインUI
applyTheme(); // 保存されたテーマを適用
}
ステップ4:フォーム入力の保存(自動補完)
app.jsにフォーム入力保存機能を追加
// UIにお問い合わせフォームセクションを追加
function buildContactFormUI() {
const app = document.getElementById('app');
const formSection = document.createElement('section');
formSection.className = 'section';
formSection.innerHTML = `
<h2>お問い合わせフォーム</h2>
<form id="contact-form">
<div class="form-group">
<label for="contact-name">お名前</label>
<input type="text" id="contact-name" placeholder="お名前" />
</div>
<div class="form-group">
<label for="contact-email">メールアドレス</label>
<input type="email" id="contact-email" placeholder="メールアドレス" />
</div>
<div class="form-group">
<label for="contact-message">メッセージ</label>
<textarea id="contact-message" placeholder="メッセージ内容"></textarea>
</div>
<div class="form-group checkbox">
<input type="checkbox" id="save-info" />
<label for="save-info">入力情報を保存する</label>
</div>
<div>
<button type="submit" class="btn">送信</button>
<button type="button" id="clear-form" class="btn">クリア</button>
</div>
</form>
`;
app.appendChild(formSection);
// イベントリスナーを追加
document.getElementById('contact-form').addEventListener('submit', handleFormSubmit);
document.getElementById('clear-form').addEventListener('click', clearFormData);
// 保存された入力値があれば復元
loadFormData();
}
// フォーム送信処理
function handleFormSubmit(e) {
e.preventDefault();
const name = document.getElementById('contact-name').value;
const email = document.getElementById('contact-email').value;
const message = document.getElementById('contact-message').value;
const saveInfo = document.getElementById('save-info').checked;
if (saveInfo) {
// フォーム入力をセッションストレージに保存
const formData = { name, email };
sessionStorage.setItem('contactForm', JSON.stringify(formData));
} else {
// 保存しない場合はクリア
sessionStorage.removeItem('contactForm');
}
// ここで実際のフォーム送信処理を行う
alert(`送信しました!\n名前: ${name}\nメール: ${email}\nメッセージ: ${message}`);
// フォームリセット
document.getElementById('contact-form').reset();
}
// 保存されたフォームデータを読み込む
function loadFormData() {
const savedData = sessionStorage.getItem('contactForm');
if (savedData) {
const formData = JSON.parse(savedData);
document.getElementById('contact-name').value = formData.name || '';
document.getElementById('contact-email').value = formData.email || '';
document.getElementById('save-info').checked = true;
}
}
// フォームデータをクリア
function clearFormData() {
document.getElementById('contact-form').reset();
sessionStorage.removeItem('contactForm');
}
// 初期化関数を更新
function init() {
buildUI(); // テーマ設定UI
buildLoginUI(); // ログインUI
buildContactFormUI(); // お問い合わせフォームUI
applyTheme(); // 保存されたテーマを適用
}
ステップ5:閲覧履歴の追跡(最近見た商品)
app.jsに閲覧履歴機能を追加
// 商品データ(実際のアプリではAPIから取得)
const products = [
{ id: 1, name: '高級腕時計', price: 25000, image: 'watch.jpg' },
{ id: 2, name: 'ワイヤレスイヤホン', price: 15000, image: 'earbuds.jpg' },
{ id: 3, name: 'スマートフォン', price: 80000, image: 'smartphone.jpg' },
{ id: 4, name: 'ノートパソコン', price: 120000, image: 'laptop.jpg' },
{ id: 5, name: 'デジタルカメラ', price: 65000, image: 'camera.jpg' }
];
// UIに商品セクションを追加
function buildProductsUI() {
const app = document.getElementById('app');
// 商品リストセクション
const productsSection = document.createElement('section');
productsSection.className = 'section';
productsSection.innerHTML = `
<h2>商品一覧</h2>
<div class="products-grid" id="products-container"></div>
`;
// 最近見た商品セクション
const recentProductsSection = document.createElement('section');
recentProductsSection.className = 'section';
recentProductsSection.innerHTML = `
<h2>最近見た商品</h2>
<div class="products-list" id="recent-products"></div>
`;
app.appendChild(productsSection);
app.appendChild(recentProductsSection);
// 商品一覧を表示
renderProducts();
// 最近見た商品を表示
renderRecentProducts();
}
// 商品一覧を表示
function renderProducts() {
const container = document.getElementById('products-container');
products.forEach(product => {
const productEl = document.createElement('div');
productEl.className = 'product-card';
// 商品画像のパスが実際には存在しないため、プレースホルダーを使用
const imageSrc = product.image || 'https://via.placeholder.com/150';
productEl.innerHTML = `
<div class="product-image">
<img src="${imageSrc}" alt="${product.name}" />
</div>
<h3>${product.name}</h3>
<p class="price">¥${product.price.toLocaleString()}</p>
<button class="btn view-product" data-id="${product.id}">詳細を見る</button>
`;
container.appendChild(productEl);
});
// 詳細ボタンのイベントリスナー
document.querySelectorAll('.view-product').forEach(btn => {
btn.addEventListener('click', (e) => {
const productId = parseInt(e.target.getAttribute('data-id'));
viewProductDetails(productId);
});
});
}
// 商品詳細を表示し、閲覧履歴に追加
function viewProductDetails(productId) {
const product = products.find(p => p.id === productId);
if (!product) return;
// 実際のアプリでは商品詳細ページに遷移
alert(`商品詳細: ${product.name}\n価格: ¥${product.price.toLocaleString()}`);
// 閲覧履歴に追加
addToRecentlyViewed(product);
// 最近見た商品を更新
renderRecentProducts();
}
// 最近見た商品リストに追加
function addToRecentlyViewed(product) {
// 既存の履歴を取得
let recentProducts = StorageManager.getObject('recentProducts') || [];
// 同じ商品が既に履歴にあれば削除
recentProducts = recentProducts.filter(p => p.id !== product.id);
// 先頭に新しい商品を追加
recentProducts.unshift(product);
// 最大5件まで保持
if (recentProducts.length > 5) {
recentProducts = recentProducts.slice(0, 5);
}
// 履歴を保存
StorageManager.setObject('recentProducts', recentProducts);
}
// 最近見た商品を表示
function renderRecentProducts() {
const container = document.getElementById('recent-products');
const recentProducts = StorageManager.getObject('recentProducts') || [];
// コンテナをクリア
container.innerHTML = '';
if (recentProducts.length === 0) {
container.innerHTML = '<p>最近見た商品はありません。</p>';
return;
}
// 商品を表示
recentProducts.forEach(product => {
const productEl = document.createElement('div');
productEl.className = 'recent-product';
const imageSrc = product.image || 'https://via.placeholder.com/80';
productEl.innerHTML = `
<img src="${imageSrc}" alt="${product.name}" class="small-image" />
<div>
<h4>${product.name}</h4>
<p>¥${product.price.toLocaleString()}</p>
</div>
`;
container.appendChild(productEl);
});
}
// 初期化関数を更新
function init() {
buildUI(); // テーマ設定UI
buildLoginUI(); // ログインUI
buildContactFormUI(); // お問い合わせフォームUI
buildProductsUI(); // 商品UI
applyTheme(); // 保存されたテーマを適用
}
スタイルを追加
/* style.cssに追加 */
.products-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 20px;
}
.product-card {
background-color: rgba(255, 255, 255, 0.05);
border-radius: 8px;
padding: 15px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
text-align: center;
}
.product-card img {
max-width: 100%;
height: auto;
border-radius: 4px;
}
.price {
font-weight: bold;
color: #e63946;
}
body.dark .price {
color: #ff6b6b;
}
.recent-product {
display: flex;
align-items: center;
margin-bottom: 10px;
padding: 10px;
background-color: rgba(255, 255, 255, 0.05);
border-radius: 4px;
}
.recent-product img.small-image {
width: 50px;
height: 50px;
object-fit: cover;
margin-right: 15px;
border-radius: 4px;
}
.form-group {
margin-bottom: 15px;
}
.form-group label {
display: block;
margin-bottom: 5px;
}
.form-group input,
.form-group textarea {
width: 100%;
padding: 8px;
border-radius: 4px;
border: 1px solid #ddd;
background-color: #fff;
color: #333;
}
body.dark .form-group input,
body.dark .form-group textarea {
background-color: #333;
color: #eee;
border-color: #555;
}
.form-group.checkbox {
display: flex;
align-items: center;
}
.form-group.checkbox input {
width: auto;
margin-right: 10px;
}
textarea {
min-height: 100px;
resize: vertical;
}
ステップ6:バージョン管理と互換性対応
storage.jsに互換性チェック機能を追加
// バージョン管理と互換性チェック
const StorageVersion = {
CURRENT_VERSION: "1.0",
// 初期化と互換性チェック
init: function() {
// 現在のバージョンを取得
const savedVersion = localStorage.getItem('storageVersion');
// 初回または新バージョンの場合
if (!savedVersion || savedVersion !== this.CURRENT_VERSION) {
this.handleVersionChange(savedVersion);
localStorage.setItem('storageVersion', this.CURRENT_VERSION);
}
},
// バージョン変更時の処理
handleVersionChange: function(oldVersion) {
console.log(`Storage version changed from ${oldVersion} to ${this.CURRENT_VERSION}`);
// バージョンごとの移行処理をここに実装
// 例: 0.9 → 1.0 の移行
if (oldVersion === "0.9") {
this.migrateFromV09ToV10();
}
// 初回起動の場合はデフォルト設定
if (!oldVersion) {
this.setDefaultSettings();
}
},
// 0.9から1.0への移行(例)
migrateFromV09ToV10: function() {
// 例: データ構造が変わった場合の移行処理
try {
const oldUserData = localStorage.getItem('user');
if (oldUserData) {
const oldUser = JSON.parse(oldUserData);
// 新データ形式に変換
const newUser = {
username: oldUser.name || oldUser.username,
loginTime: oldUser.lastLogin || new Date().toISOString(),
isLoggedIn: true
};
localStorage.setItem('user', JSON.stringify(newUser));
}
} catch (e) {
console.error('Migration error:', e);
// 移行に失敗した場合はデータをクリア
localStorage.removeItem('user');
}
},
// デフォルト設定
setDefaultSettings: function() {
// テーマのデフォルト設定
if (!CookieManager.get('theme')) {
CookieManager.set('theme', 'light', 30);
}
}
};
// 初期化時にバージョンチェック
StorageVersion.init();
ステップ7:アプリの初期化コードを更新
app.jsのinit関数を更新
// 初期化関数を更新
function init() {
// バージョンチェックは既にstorage.jsで実行済み
// UIコンポーネントの構築
buildUI(); // テーマ設定UI
buildLoginUI(); // ログインUI
buildContactFormUI(); // お問い合わせフォームUI
buildProductsUI(); // 商品UI
// 保存されたデータを適用
applyTheme(); // 保存されたテーマを適用
console.log('アプリケーションが初期化されました');
}
// ブラウザのストレージをサポートしているか確認
function checkBrowserSupport() {
let supported = true;
let message = '';
if (!window.localStorage) {
supported = false;
message += 'このブラウザはローカルストレージをサポートしていません。';
}
if (!navigator.cookieEnabled) {
supported = false;
message += 'このブラウザはクッキーが無効化されています。';
}
if (!supported) {
alert('警告: ' + message + ' 一部の機能が正常に動作しない可能性があります。');
}
return supported;
}
// ページ読み込み時に実行
window.addEventListener('DOMContentLoaded', function() {
checkBrowserSupport();
init();
});
まとめ:クッキーとストレージの使い分け
特性 クッキー ローカルストレージ セッションストレージ 容量 約4KB 約5MB 約5MB 有効期限 設定可能 永続的(手動削除まで) ブラウザ/タブを閉じるまで サーバー送信 自動的に送信 送信されない 送信されない 用途 ・ログイン状態<br>・サーバーと共有する設定<br>・トラッキング ・ユーザー設定<br>・大きなデータ<br>・アプリケーション状態 ・一時的なフォームデータ<br>・ウィザードの状態<br>・セッション固有の設定 セキュリティ設定 Secure, HttpOnly, SameSiteなど なし なし
ベストプラクティス
適切なストレージの選択
サーバーと共有する認証情報 → クッキー(HttpOnly設定あり)
UIの設定やテーマ → ローカルストレージ
一時的なフォームデータ → セッションストレージ
セキュリティ対策
クッキーには常にSecureとSameSite属性を設定
機密情報はクッキーの場合はHttpOnlyフラグを有効に
JWTトークンなどの認証情報はXSS攻撃を避けるためローカルストレージではなくクッキーに保存
エラー処理
ストレージ操作は常にtry-catchでラップ
プライベートブラウジングモードでのストレージ容量制限に注意
互換性
古いブラウザでの対応が必要な場合はポリフィルを使用
常にストレージが利用可能かチェック
これらの方法を活用することで、ユーザーフレンドリーなウェブアプリケーションを構築し、ユーザー設定や状態を効果的に管理することができます。