JavaScript
localStorageからnullが返る
キー名が一致していない
こんな症状
localStorage.getItem()で保存したはずのデータがnullになる。localStorageのキー管理で起きやすいよ。
まず試す
setItem('key',...) と getItem('key') のキー名が完全一致(大文字小文字も)しているか確認する。
js
localStorage.setItem('userName', '太郎');
// ✅ 完全に同じキー名で取得
const name = localStorage.getItem('userName');
console.log(name); // 太郎これで直らなければ、下の「自分のケース」を確認。
🔍 自分のケースはどれ?
- ✓キー名が微妙に違う(username と userName)
→ setItem と getItem のキーを完全一致させる。 - ✓別のURL(オリジン)で保存した
→ localStorage はオリジンごとに分離。localhost:3000 と :5173 は別物。同じURLで確認する。 - ✓オブジェクトを保存したい
→ JSON.stringify で保存し、JSON.parse で復元する。
なぜ起きる?
setItemとgetItemのキー名が一致していない、別のドメイン(オリジン)で保存したデータにアクセスしようとしている、またはブラウザの設定でストレージが無効になっているよ。localStorageはオリジンごとに分離されるから、localhost:3000とlocalhost:5173は別のストレージだよ。
✕ エラーが起きるコード
localStorage.setItem('userName', '太郎');
// キー名が微妙に違う(username ≠ userName)
const name = localStorage.getItem('username');
console.log(name); // null✓ 直したコード
localStorage.setItem('userName', '太郎');
// ✅ setItemと完全に同じキー名で取得(大文字小文字も区別)
const name = localStorage.getItem('userName');
console.log(name); // 太郎
// オブジェクトはJSONにして保存・復元する
localStorage.setItem('user', JSON.stringify({ name: '太郎' }));
const user = JSON.parse(localStorage.getItem('user'));✅ 直ったか確認
DevTools の Application→Local Storage に該当キーがあり、getItem が値を返せばOK。
この解決法は役立ちましたか?
🔗 関連するエラー
- Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') — 取得しようとしたHTML要素が見つかっていない
- Uncaught TypeError: Cannot set properties of null (setting 'textContent') — nullに対してプロパティを設定しようとしている
- Uncaught ReferenceError: xxx is not defined — 変数・関数名のタイポ
- 404 Not Found(スクリプトが読み込まれない) — script の src パスが間違っている
- 計算結果が NaN になる — 文字列を数値に変換していない
📖 この問題を学べるレッスン
✏️ 手を動かして練習
📝 関連ブログ記事
- プログラミングのエラーメッセージの読み方 — エラーの読み方を基礎から解説
- JavaScriptとは?初心者向けにわかりやすく解説 — 変数・関数・イベントの基本
- JavaScriptでボタンクリックを動かす方法 — ボタンクリック時の動作を解説