Best Practices and Security
Security is Critical
Follow security guidelines to protect your users and their data. Electron applications have access to powerful system APIs, making security considerations especially important.
Keep dependencies up to date and avoid using Node.js integration in renderer unless absolutely necessary.
Essential Security Practices
- Disable Node.js integration in renderer - Prevents untrusted code from accessing Node.js APIs
- Use context isolation - Separates preload scripts from renderer process context
- Validate user input - Always sanitize and validate data from users
- Enable sandbox - Run renderer processes in a sandboxed environment
- Use HTTPS - Load remote content only over secure connections
Recommended webPreferences Configuration
When creating BrowserWindows, use these security settings:
const mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
enableRemoteModule: false,
sandbox: true,
preload: path.join(__dirname, 'preload.js')
}
});
This configuration provides the best security by default.
Content Security Policy (CSP)
Implement a strong Content Security Policy to prevent cross-site scripting (XSS) attacks:
<meta http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'">
This restricts the sources from which content can be loaded.
Handling External Content
When loading external content:
- Never load untrusted remote content with Node.js integration enabled
- Validate and sanitize all URLs before loading
- Use
will-navigateandnew-windowevents to control navigation - Consider using
<webview>tag for isolated content
Dependency Management
Keep your dependencies secure and up-to-date:
- Regularly update Electron to the latest stable version
- Use
npm auditto check for known vulnerabilities - Review and audit third-party packages before installing
- Use lock files (
package-lock.json) for consistent installs
Inter-Process Communication Security
When using IPC between processes:
- Validate all messages received from renderer processes
- Use a preload script to expose only necessary APIs
- Never pass untrusted data directly to Node.js APIs
- Implement proper permission checks
Additional Best Practices
- Code signing - Sign your application for all platforms
- Auto-updates - Implement secure auto-update mechanism
- Error handling - Don't expose sensitive information in error messages
- Logging - Be careful not to log sensitive user data
- Testing - Include security testing in your development workflow
Security Resources
For more detailed security information, refer to:
- Electron Security Checklist (official documentation)
- OWASP guidelines for desktop applications
- Regular security advisories from the Electron team