Electron Sessions, Networking, and Local Storage
🎯 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
| Content | Suitable location | Notes |
|---|---|---|
| Temporary page state | Vue reactive data | Lost when the window closes |
| General application settings | JSON configuration file | For example, theme and server address |
| Website sessions | Cookies / session | Used by requests and web sessions |
| Sensitive credentials | System credential storage | Do 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:
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:
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
sessionmanages 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.
Menus, Tray Icons, and Multiple Windows
Use application menus, tray icons, and window references to coordinate common desktop window interactions.
Custom Protocols, Resource Loading, and Deep Links
Understand how resource loading differs between development and packaged apps, and when to use links that open specific content in your application.
