Electron Sessions, Networking, and Local Storage

Use session, cookies, and local configuration to preserve login state and application settings.

🎯 Introduction

Desktop apps often need to remember server addresses, login state, and user preferences. This article introduces common storage locations and their boundaries without implementing a complete login system.


🧱 Choose the right storage mechanism

ContentSuitable locationNotes
Temporary page stateVue reactive dataLost when the window closes
General application settingsJSON configuration fileFor example, theme and server address
Website sessionsCookies / sessionUsed by requests and web sessions
Sensitive credentialsSystem credential storageDo not write plaintext credentials to ordinary configuration files

Do not store passwords or long-lived tokens directly in localStorage or ordinary JSON files. Production projects should use secure system credential storage and define a cleanup workflow for logout.


🛠 Save general settings

The main process can use Node.js path and file APIs to save ordinary settings:

electron/main.js
const { app } = require('electron/main');
const path = require('node:path');
const { readFile, writeFile } = require('node:fs/promises');

const settingsPath = path.join(app.getPath('userData'), 'settings.json');

async function saveSettings(settings) {
    await writeFile(settingsPath, JSON.stringify(settings, null, 4), 'utf8');
}

async function loadSettings() {
    try {
        return JSON.parse(await readFile(settingsPath, 'utf8'));
    } catch {
        return { theme: 'system' };
    }
}

app.getPath('userData') returns the current user's application data directory. For example:

  • macOS: ~/Library/Application Support/AppName
  • Windows: C:\Users\Username\AppData\Roaming\AppName
  • Linux: ~/.config/AppName

The “project directory” is the folder containing package.json and source files during development. The “installation directory” contains application files after installation. Neither is appropriate for user settings: the project directory exists only in development, while the installation directory may not be writable and may be replaced during updates.

userData belongs to the current user and suits ordinary settings such as themes and server addresses. The settingsPath above places settings.json in this directory.


🌐 Read session information

When an Electron window opens a website that requires login, the website usually saves login credentials as cookies after authentication. Electron automatically includes those cookies in subsequent requests to the same website, so users do not have to log in each time.

The window's session manages these cookies. You usually do not need to read them yourself. Read them when you need to display login state or troubleshoot authentication:

electron/main.js
const cookies = await win.webContents.session.cookies.get({
    url: 'https://example.com',
});

console.log('Cookies in the current session:', cookies.length);

This code only checks how many cookies the current window stores for the website. It does not log in automatically or create an authenticated session.

When the user clicks “Log out”, you can clear the website's cookies:

await win.webContents.session.clearStorageData({
    origins: ['https://example.com'],
    storages: ['cookies'],
});

win.reload();

After reloading, the website finds that the login cookie is missing and typically returns to its login page. origins limits cleanup to the intended site, avoiding accidental removal of other websites' sessions.

session manages website login state, while app.getPath('userData') provides a location for application configuration files. They serve different purposes.

🧾 Summary

  • Store temporary state, general settings, cookies, and sensitive credentials separately.
  • General settings can be saved to app.getPath('userData').
  • The window's session manages cookies.
  • Clear session data when logging out.
  • Never write sensitive credentials to configuration files in plaintext.

❓ Questions and answers

Q1: Why not store settings in the project directory?

The installation directory may not be writable and may be overwritten during app updates.

Q2: How do cookies differ from general configuration files?

Cookies primarily support web requests and are sent according to session rules. Configuration files suit application settings such as themes and addresses.

🧪 Practice

Save the following settings object to the userData directory:

const settings = {
    // Write your code here
};

🎉 You can now plan basic session and configuration storage for a desktop app.