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

How can I securely store and access user preferences in the browser using localStorage or sessionStorage?

Asked on Oct 13, 2025

Answer

To securely store and access user preferences in the browser, you can use the Web Storage API, which includes "localStorage" and "sessionStorage". Here's a basic example of how to store and retrieve data securely using "localStorage".
<!-- BEGIN COPY / PASTE -->
        // Function to save user preferences
        function savePreferences(key, value) {
            const jsonData = JSON.stringify(value);
            localStorage.setItem(key, jsonData);
        }

        // Function to load user preferences
        function loadPreferences(key) {
            const jsonData = localStorage.getItem(key);
            return jsonData ? JSON.parse(jsonData) : null;
        }

        // Example usage
        const userPreferences = {
            theme: 'dark',
            fontSize: '16px'
        };

        // Save preferences
        savePreferences('userPreferences', userPreferences);

        // Load preferences
        const loadedPreferences = loadPreferences('userPreferences');
        console.log(loadedPreferences);
        <!-- END COPY / PASTE -->
Additional Comment:
  • This example uses "localStorage" to persist data across browser sessions. Use "sessionStorage" if you want data to be cleared when the session ends.
  • Always use "JSON.stringify" to convert objects to strings before storing them.
  • Use "JSON.parse" to convert strings back to objects when retrieving data.
  • Consider encrypting sensitive data before storing it, as "localStorage" and "sessionStorage" are accessible via JavaScript and can be viewed by users.
✅ Answered with JavaScript best practices.
← Back to All Questions