The License API answers browsers too, with Access-Control-Allow-Origin: *, so a renderer could call it directly. Do not. Anything in a renderer is reachable from page scripts, and a window that shows remote content makes that a real risk. The main process is where the key, the token and the calls belong. The short Electron sample in the platform guides shows the whole flow in one file. This page goes through the parts that are specific to Electron. For the token check used on the offline path, see offline verification in Electron.
The check
net.fetch takes the same arguments as fetch, and Electron documents that it runs on Chromium’s network stack, which follows the operating system’s proxy configuration. Customers behind a corporate proxy are the ones for whom a plain Node fetch fails:
// main/license.js
import { app, net, safeStorage } from 'electron';
/** POST /v1/licenses/<action>. Resolves to null when there is no HTTP answer at all. */
export async function post(base, action, body) {
try {
const res = await net.fetch(`${base}/v1/licenses/${action}`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
signal: AbortSignal.timeout(8000),
});
const retryAfter = Number(res.headers.get('retry-after')) || null;
return { status: res.status, body: await res.json().catch(() => ({})), retryAfter };
} catch {
return null; // offline, DNS failure, timeout
}
}
/** 'valid' | 'not-valid' | 'unknown' | 'no-answer'. Branch on this, never on error text. */
export async function validate(base, saved) {
const r = await post(base, 'validate', { license_key: saved.key, instance_id: saved.instanceId });
if (!r) return { kind: 'no-answer' };
switch (r.status) {
case 200:
if (typeof r.body.valid !== 'boolean') return { kind: 'no-answer' };
return { kind: r.body.valid ? 'valid' : 'not-valid', token: r.body.token, reason: r.body.error };
case 404:
return { kind: 'unknown', reason: r.body.error };
case 429:
case 503:
return { kind: 'no-answer', retryAfter: r.retryAfter };
default:
return { kind: 'no-answer' };
}
}
A known key always answers 200, valid or not, so valid decides. A 404 is an unknown key or instance_id not found. A 429 carries Retry-After: 60 and a 503 carries Retry-After: 5. Neither says anything about the license.
Share one check across windows
Each BrowserWindow that asks for the license state at startup would send its own request. The License API allows 60 requests per minute per key, so a few windows and a reload loop add up. Keep one check in flight:
let inflight = null;
export function check(base, verifier) {
inflight ??= run(base, verifier).finally(() => { inflight = null; });
return inflight;
}
async function run(base, verifier) {
const saved = await load();
if (!saved) return 'unlicensed';
const outcome = await validate(base, saved);
if (outcome.kind === 'valid' || outcome.kind === 'not-valid') {
await save({ ...saved, token: outcome.token ?? saved.token }); // also when not valid: offline, the token then says so
return outcome.kind === 'valid' ? 'licensed' : 'invalid';
}
if (outcome.kind === 'unknown') { await clear(); return 'invalid'; }
// No answer: trust the stored token while it is fresh.
return verifier.check(saved.token) === 'ok' ? 'licensed' : 'needs-network';
}
Three concurrent calls resolved together as ['licensed', 'licensed', 'licensed'] from one request. The verifier is the TokenVerifier from the offline page.
Where to keep the key
safeStorage encrypts with a key held by the operating system. Electron’s documentation marks the synchronous methods as deprecated and says they will be removed in Electron 46, so use the asynchronous ones:
import { readFile, rm, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
const FILE = () => join(app.getPath('userData'), 'license.bin');
export async function load() {
try {
const { result } = await safeStorage.decryptStringAsync(await readFile(FILE()));
return JSON.parse(result);
} catch {
return null;
}
}
export async function save(license) {
await writeFile(FILE(), await safeStorage.encryptStringAsync(JSON.stringify(license)));
}
export const clear = () => rm(FILE(), { force: true });
What protects the file differs by platform, and Electron’s documentation is plain about it:
- macOS. The key sits in the Keychain. Electron advises code signing your app, because without a consistent signature the Keychain can ask for permission again after every update.
- Windows. DPAPI protects the file from other users on the machine, but not from other apps running as the same user.
- Linux. It depends on the desktop. When no secret store exists, the data is encrypted with a hardcoded password. In that case
safeStorage.getSelectedStorageBackend()returnsbasic_text. Check it and decide whether to warn, or to refuse to store the key.
The decrypt call resolves with { result, shouldReEncrypt }. When shouldReEncrypt is true, the key has changed since the data was written, so encrypt the value again with encryptStringAsync and save it.
Real output
Example output:
demo key (live): { kind: 'valid', token: 'sgt1.eyJ2Ijo...' }
unknown key (live): { kind: 'unknown', reason: 'license_key not found.' }
unknown instance (live): unknown
stub 429: { kind: 'no-answer', retryAfter: 60 }
stub 503: { kind: 'no-answer', retryAfter: 5 }
slow server: { kind: 'no-answer' } after 8.0 s
server down, fresh token: licensed
instance removed (404): invalid, saved license cleared
Nothing was run inside Electron itself, so real safeStorage behavior is as documented, not as observed here.
Pitfalls specific to Electron
- Validate the IPC sender. The Electron security guide tells you to validate the sender of every IPC message. Check
event.senderFrame.urlin the handler before it answerslicense:check. - Expose a function, not
ipcRenderer. The preload script should offerlicense.check()and nothing that takes a channel name. userDataoutlives your test runs. A license you activated while developing stays on disk, so deletelicense.binwhen you test the first-run screen.- Do not call
safeStoragebeforeapp.whenReady().
Doing this with Clavem
The License API needs no secret, so nothing sensitive ships in the app. Plan limits never block validation. The statuses and fields are in the API reference. Seats are covered in device activation in Electron.
Questions
Should I validate a license in the Electron main process or the renderer?
In the main process. The key and token then never exist in page scripts, and a renderer that loads remote content cannot read them. Expose a small status function to the renderer through a preload script and contextBridge.
Is safeStorage secure on Linux?
Only when a secret store such as GNOME Keyring or KWallet is available. Without one, Electron encrypts with a hardcoded password, and getSelectedStorageBackend returns basic_text. Check for that and decide whether to warn the user.
Why use net.fetch instead of fetch in the main process?
net.fetch uses Chromium's network stack, which follows the system proxy settings, PAC files and proxy authentication. Node's fetch uses Node's own HTTP stack and does not.