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

How can I use localStorage to persist user settings across browser sessions?

Asked on Oct 03, 2025

Answer

LocalStorage allows you to store data in the browser that persists even after the browser is closed. Here's how you can use it to save and retrieve user settings.
<!-- BEGIN COPY / PASTE -->
        // Save user settings to localStorage
        const userSettings = {
            theme: "dark",
            fontSize: "16px"
        };
        localStorage.setItem("userSettings", JSON.stringify(userSettings));

        // Retrieve user settings from localStorage
        const savedSettings = localStorage.getItem("userSettings");
        if (savedSettings) {
            const settings = JSON.parse(savedSettings);
            console.log(settings.theme); // Outputs: dark
            console.log(settings.fontSize); // Outputs: 16px
        }
        <!-- END COPY / PASTE -->
Additional Comment:
  • LocalStorage stores data as strings, so objects must be converted using JSON.stringify when saving.
  • Use JSON.parse to convert the string back to an object when retrieving data.
  • Check if the data exists in localStorage before attempting to parse it to avoid errors.
✅ Answered with JavaScript best practices.
← Back to All Questions