JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network
Q&A Logo

How can I securely store and retrieve user preferences using the Web Storage API in JavaScript? Pending Review

Asked on Oct 14, 2025

Answer

To securely store and retrieve user preferences using the Web Storage API, you can use the "localStorage" or "sessionStorage" objects. Here's a simple example of how to do this:
<!-- BEGIN COPY / PASTE -->
        // Storing user preferences
        const userPreferences = {
            theme: "dark",
            fontSize: "16px"
        };
        localStorage.setItem("userPreferences", JSON.stringify(userPreferences));

        // Retrieving user preferences
        const storedPreferences = localStorage.getItem("userPreferences");
        if (storedPreferences) {
            const preferences = JSON.parse(storedPreferences);
            console.log(preferences.theme); // Output: "dark"
            console.log(preferences.fontSize); // Output: "16px"
        }
        <!-- END COPY / PASTE -->
Additional Comment:
  • Use "localStorage" for data you want to persist across sessions, or "sessionStorage" for data that should only last for the duration of the page session.
  • Always convert objects to strings using "JSON.stringify" before storing them.
  • Retrieve and parse the stored string back to an object using "JSON.parse".
  • Be cautious with sensitive data; Web Storage is not encrypted and can be accessed by JavaScript running on the same domain.
✅ Answered with JavaScript best practices.
← Back to All Questions