Electron Secure Context Project Structure
Security-first architecture. Context isolation, sandboxing, and defense-in-depth patterns.
Project Directory
my-electron-app/
package.json
electron-builder.json
vite.config.js
src/
main/
index.js
window.js
Secure window config
security/
Security utilities
csp.js
Content Security Policy
permissions.js
Permission handlers
ipc/
index.js
handlers.js
validators.js
Input validation
services/
store.js
updater.js
Auto-updates
preload/
index.js
Main window preload
api.js
Exposed APIs
types.js
Type definitions
renderer/
index.html
main.jsx
App.jsx
components/
SecureLink.jsx
Safe external links
lib/
ipc.js
Typed IPC calls
resources/
icon.icns
icon.ico
Why This Structure?
Defense-in-depth for Electron. Context isolation prevents renderer from accessing Node.js. Sandbox restricts system access. CSP blocks XSS. Input validation prevents IPC abuse. This structure enforces secure defaults.
Key Directories
- src/main/security/-CSP, permission handling, security utils
- src/main/ipc/validators.js-Validate all IPC inputs
- src/preload/-Minimal, typed API surface
- src/renderer/lib/ipc.js-Typed wrappers for preload APIs
Secure Window Config
// src/main/window.js
const win = new BrowserWindow({
webPreferences: {
contextIsolation: true, // Required
nodeIntegration: false, // Never enable
sandbox: true, // Restrict renderer
preload: path.join(__dirname, '../preload/index.js')
}
});
Best Practices
- Enable
contextIsolation: truealways - Keep
nodeIntegration: falsealways - Enable
sandbox: truefor renderer - Validate all IPC inputs in main process
- Use strict CSP headers
- Never load remote content without validation
When To Use This
- Apps handling sensitive data
- Production apps for distribution
- Apps loading any external content
- Enterprise or compliance requirements
Trade-offs
- More boilerplate-Every API must go through preload
- Stricter development-Can't use quick Node.js shortcuts
- Testing complexity-Need to test security boundaries
Testing Strategy
- Security audit-Check BrowserWindow options programmatically
- IPC validation-Test invalid inputs are rejected
- CSP testing-Verify inline scripts are blocked