Building Desktop Apps With Electron
Cover photo by Ilya Pavlov on Unsplash
I get why people dislike Electron. Shipping a massive Chromium instance just to show a button is inefficient. But, if you need cross-platform support and you know React, it is hard to beat for speed to market.
The naive approach
Most beginners start by putting their entire app logic in the renderer process. It looks like this:
const handleSave = () => { fs.writeFileSync('data.txt', content);};This breaks security immediately. If you enable Node integration in the renderer, any malicious script running in your app gains full access to the file system. Don’t do this (seriously, I have seen this lead to some messy security audits).
The better way
Instead, use the preload script as a bridge. This is the IPC (Inter-Process Communication) pattern.
First, expose a safe function in your preload file:
const { contextBridge, ipcRenderer } = require('electron');contextBridge.exposeInMainWorld('api', { saveFile: (data) => ipcRenderer.invoke('save-file', data)});Then, handle the action in the main process:
ipcMain.handle('save-file', async (event, data) => { return fs.promises.writeFile('data.txt', data);});Finally, call it from React:
const onSave = async () => { await window.api.saveFile(content);};This keeps your main process isolated and secure. “But isn’t this too much boilerplate for a simple app?” Sure, it adds setup time. That is a fair critique. If you are building a tool that never handles user files or sensitive data, you might feel like you are over-engineering. I still think the extra five minutes of configuration is worth the peace of mind.
Final thoughts
I admit that my preference for Electron might be biased by my comfort with React. If you are building for macOS exclusively, Swift will always perform better. Electron is a trade-off. You give up raw performance and binary size for developer velocity and UI consistency.
Is there a middle ground? Maybe. Tauri exists, which uses the system webview instead of bundling Chromium. I haven’t used it enough to commit to it, but it looks promising. Have you tried moving away from Electron yet?