Many developers need to build Angular applications that need to temporarily store user data. They may need this simply to deter progress, or to keep track of a cart, or just to keep note of the state between routes. This handling of Session Storage involves some problems.
Since the browser tells you that it only accepts data strings, you cannot help but figure out a way to store and retrieve JSON formatter data without breaking things.
In this post we will take you through what we have learned in the process. Besides giving you useful l “copy-paste” code snippets, we will also discuss the why, the pitfalls, and those small discoveries and findings that you don’t see in generic docs.
What Is Session Storage, Really?
Before we even touch Angular, let’s clear up what session storage is.
Think of it like a notepad the browser gives you while someone is visiting your site. You can jot things down, but the moment that tab is closed, everything’s gone. It is different from local storage, which is like a more permanent notebook, stickier data that hangs around even if you close your browser.
In Angular apps, session storage is perfect for things like:
- Keeping user settings while they’re still on the site.
- Storing multi-step form data so the user can jump between steps without losing info.
- Temporary flags, like whether a user has already seen a pop-up.
Why Can’t You Just Store an Object?
It is the exact question when you first type:
sessionStorage.setItem(‘user’, { name: ‘John’, age: 30 });
And then the browser quietly stored [object Object]. Not helpful.
That’s because sessionStorage (like its siblings localStorage and cookies) only works with strings. No arrays, no objects, just plain old text. So, when you pass an object, it converts it to a string, just not the string you need.
Convert your object to JSON before storing, then parse it back when retrieving. Simple, but easy to forget.
The Right Way: Storing JSON in Angular
Here’s the basic pattern I now use:
// 1. Store JSON
const user = { name: ‘John’, age: 30 };
sessionStorage.setItem(‘user’, JSON.stringify(user));
// 2. Retrieve JSON
const storedUser = sessionStorage.getItem(‘user’);
if (storedUser) {
const parsedUser = JSON.parse(storedUser);
console.log(parsedUser.name); // “John”
}
That’s the core idea: JSON.stringify() to set, JSON.parse() to get.
But let’s not stop there. In a real Angular app, you’ll want to handle it in a slightly cleaner way.
Wrapping It in an Angular Service
If you start sprinkling sessionStorage.setItem() calls across random components, it isgoing to get messy fast. Instead, create a storage service that acts as your single “gatekeeper” for setting and getting session data.
Example: storage.service.ts
import { Injectable } from ‘@angular/core’;
@Injectable({
providedIn: ‘root’
})
export class StorageService {
setSessionData(key: string, value: any): void {
try {
const jsonData = JSON.stringify(value);
sessionStorage.setItem(key, jsonData);
} catch (error) {
console.error(‘Error saving to session storage’, error);
}
}
getSessionData<T>(key: string): T | null {
try {
const data = sessionStorage.getItem(key);
return data ? JSON.parse(data) as T : null;
} catch (error) {
console.error(‘Error reading from session storage’, error);
return null;
}
}
removeSessionData(key: string): void {
sessionStorage.removeItem(key);
}
clearSession(): void {
sessionStorage.clear();
}
}
Why bother with a service?
Because once your app grows, you’ll thank yourself for having all your session storage logic in one place especially if you decide later to switch to localStorage or an entirely different state management approach.
Real-Life Example: Multi-Step Form
Let’s make this practical. Imagine you are building a three-step sign-up form. Users enter their info on step one, then navigate to step two. Without session storage, if they hit “back,” all their data disappears. Frustrating.
With session storage:
- On every form step, save the data.
- On load, check if there’s existing data and pre-fill the form.
// Inside your form component
import { StorageService } from ‘./storage.service’;
constructor(private storage: StorageService) {}
ngOnInit() {
const savedData = this.storage.getSessionData<any>(‘signupForm’);
if (savedData) {
this.form.patchValue(savedData);
}
}
onNextStep() {
this.storage.setSessionData(‘signupForm’, this.form.value);
}
Now, even if the user navigates away, their progress is still there—until they close the tab.
Common Mistakes (Learned the Hard Way)
a) Forgetting to stringify
I’ve done this more times than I’d like to admit. If you try to store an object directly, you’ll end up with [object Object] instead of real data.
b) Parsing without checking for null
When you call JSON.parse() on null, your app crashes. Always check before parsing.
c) Storing too much data
Session storage isn’t infinite; it is usually limited to around 5MB per domain. Don’t try to store giant datasets or images.
d) Assuming it is secure
Session storage is just like local storage; anyone can open DevTools and see it. Don’t put sensitive data (like passwords or tokens) there.
Debugging: How to Check Your Stored Data
Open Chrome (or any browser), right-click → Inspect → Application tab → Session Storage.
You’ll see a neat key-value table. That’s where your JSON data lives. If it looks like {“name”:”John”,”age”:30}, you are good. If you see [object Object], you forgot JSON.stringify().
When Should You Use Session Storage vs. Other Options?
I’ve made the mistake of treating session storage as a one-size-fits-all solution. Here’s what I’ve learned:
- Session Storage: Temporary tab-specific data. Perfect for form states, filters, or UI flags.
- Local Storage: Persistent across sessions. Good for settings like dark mode.
- NgRx or other state management: If your app is complex, session storage becomes clunky. A proper state library gives you more control.
- Cookies: Use for server-side needs (but remember they get sent with every request).
Edge Cases: Tab Duplication and Session Cloning
One thing I didn’t know until I tested: if a user duplicates a tab, the session storage is cloned. That might be fine, or a nightmare, depending on your app.
For example, if you are building a checkout page, two tabs with the same cart data might cause weird issues. Test these scenarios early.
Key Learnings
Honestly, session storage isn’t some advanced Angular feature, it isjust the browser’s built-in API. The tricky part isn’t “how” to use it, but “when” and “how much” to rely on it.
Here are the key learnings you should keep in mind:
- Wrap your code in a service to keep things organized.
- Always stringify/parse safely.
- Don’t dump sensitive or massive data there.
- Test edge cases, tab closing, refreshing, and opening multiple windows.
Quick Reference Cheat Sheet:
// Store JSON
sessionStorage.setItem(‘key’, JSON.stringify(data));
// Get JSON
const data = sessionStorage.getItem(‘key’);
const parsed = data ? JSON.parse(data) : null;
// Remove
sessionStorage.removeItem(‘key’);
// Clear all
sessionStorage.clear();
Wrapping Up
Working with session storage in Angular isn’t rocket science, but it isone of those “small” things that can either save your users a ton of frustration or turn into silent bugs that you don’t catch until production.
Take a little time to set it up right, use a service, handle errors, and know its limits. You’ll avoid a lot of headaches later.

