electron-best-practices

jwynia/agent-skills · updated Apr 10, 2026

MDX-style export adds YAML metadata + attribution linking explainx.ai and this canonical listing URL.

$npx skills add https://github.com/jwynia/agent-skills --skill electron-best-practices
0 commentsdiscussion
summary

Guide AI agents in building secure, production-ready Electron applications with React. This skill provides security patterns, type-safe IPC communication, project setup guidance, packaging and code signing workflows, and tools for analysis, scaffolding, and type generation.

skill.md

Electron + React Best Practices

Guide AI agents in building secure, production-ready Electron applications with React. This skill provides security patterns, type-safe IPC communication, project setup guidance, packaging and code signing workflows, and tools for analysis, scaffolding, and type generation.

When to Use This Skill

Use this skill when:

  • Generating Electron main, preload, or renderer process code
  • Configuring electron-vite or Electron Forge
  • Setting up IPC communication between processes
  • Implementing security patterns (contextBridge, sandbox, CSP)
  • Packaging, signing, and notarizing desktop applications
  • Testing Electron apps with Playwright
  • Designing multi-window architectures

Do NOT use this skill when:

  • Building Tauri apps (different paradigm, use Tauri-specific guidance)
  • Building pure web apps with no desktop requirements
  • Targeting Electron versions below 20 (security defaults differ)
  • Using non-React renderer frameworks (use framework-specific skills)

Core Principles

1. Security First Architecture

Modern Electron security relies on three defaults that became standard in Electron 20+: context isolation, sandbox mode, and nodeIntegration disabled. Disabling any of them allows XSS attacks to escalate to full remote code execution. All main-renderer communication must flow through contextBridge:

// preload.ts - SECURE pattern
contextBridge.exposeInMainWorld('electronAPI', {
  loadPreferences: () => ipcRenderer.invoke('load-prefs'),
  saveFile: (content: string) => ipcRenderer.invoke('save-file', content),
  onUpdateCounter: (callback: (value: number) => void) => {
    const handler = (_event: IpcRendererEvent, value: number) => callback(value);
    ipcRenderer.on('update-counter', handler);
    return () => ipcRenderer.removeListener('update-counter', handler);
  }
});

Set Content Security Policy via HTTP headers for apps loading local files, restricting script sources to 'self'.

2. Type-Safe IPC Communication

The invoke/handle pattern is preferred over send/on for request-response communication, providing proper async/await semantics and error propagation. For typed channels, use a mapped type pattern:

type IpcChannelMap = {
  'load-prefs': { args: []; return: UserPreferences };
  'save-file': { args: [content: string]; return: { success: boolean } };
};

For complex applications, electron-trpc provides full type safety using tRPC's router pattern with Zod validation:

export const appRouter = t.router({
  greeting: t.procedure
    .input(z.object({ name: z.string() }))
    .query(({ input }) => `Hello, ${input.name}!`),
});

Error handling across the IPC boundary requires attention because Electron only serializes the message property of Error objects. Wrap responses in a { success, data, error } result type to preserve full error context.

3. Modern Project Setup

The recommended stack uses electron-vite for development and Electron Forge for packaging. electron-vite provides a unified configuration managing main, preload, and renderer processes with sub-second dev server startup and instant HMR. Electron Forge uses first-party Electron packages for signing and notarization.

src/
├── main/           # Main process (Node.js environment)
│   ├── index.ts
│   └── ipc/        # IPC handlers
├── preload/        # Secure bridge via contextBridge
│   ├── index.ts
│   └── index.d.ts  # TypeScript declarations for exposed APIs
└── renderer/       # React application (pure web, no Node access)
    ├── src/
    └── index.html

4. React Integration Patterns

React 18's concurrent features work normally in Electron's Chromium-based renderer. Strict Mode's double-invocation of effects catches IPC listener leaks that would otherwise cause memory issues. Always return cleanup functions from effects that register IPC listeners:

useEffect(() => {
  const cleanup = window.electronAPI.onUpdateCounter((value) => {
    setCount(value);
  });
  return cleanup;
}, []);

For multi-window applications, the main process should serve as the single source of truth for shared state. Use electron-store for persistence combined with IPC broadcasting so any window's mutation updates all others.

Quick Reference

Category Prefer Avoid
Security contextBridge.exposeInMainWorld() nodeIntegration: true
IPC invoke/handle pattern send/on for request-response
Preload Typed function wrappers Exposing raw ipcRenderer
Build tool electron-vite webpack-based toolchains
Packaging Electron Forge Manual packaging
State Zustand + electron-store Redux for simple apps
Testing Playwright E2E Spectron (deprecated)
Updates electron-updater Manual update checks
Signing CI-integrated code signing Unsigned releases
CSP HTTP headers, 'self' only No CSP
Error handling Result type {success, data, error} Raw Error across IPC
Multi-window Main process as state hub Direct window-to-window

Code Generation Guidelines

When generating Electron code, follow these patterns:

BrowserWindow Creation

const win = new BrowserWindow({
  webPreferences: {
    preload: path.join(__dirname, '../preload/index.js'),
    contextIsolation: true,
    sandbox: true,
    nodeIntegration: false,
  },
});

Always enable contextIsolation and sandbox. Never enable nodeIntegration. The preload path must resolve to the built output location.

IPC Handler Module

export function registerFileHandlers(): void {
  ipcMain.handle('save-file', async (_event, content: string) => {
    try {
      await fs.writeFile(filePath, content);
      return { success: true, data: filePath };
    } catch (err) {
      return { success: false, error: (err as Error).message };
    }
  });
}

Group related handlers into modules. Use the result type pattern for all return values. Validate all arguments received from the renderer process.

Common Anti-Patterns

Avoid these patterns when generating Electron code:

Anti-Pattern Problem Solution
nodeIntegration: true XSS escalates to full RCE Keep disabled (default)
Exposing ipcRenderer directly Full IPC access from renderer Wrap in contextBridge functions
Missing contextIsolation Renderer accesses preload scope Keep enabled (default since Electron 12)
No code signing OS security warnings, Gatekeeper blocks Sign and notarize for all platforms
BrowserWindow without sandbox Preload has full Node.js access Enable sandbox (default since Electron 20)
Unvalidated IPC arguments Injection attacks from renderer Validate with Zod or manual checks
0.0.0.0 server binding Network-exposed local server Always bind to 127.0.0.1
Missing CSP headers Script injection vectors Set strict CSP via HTTP headers
No IPC error serialization Lost error context across boundary Use Result type pattern
Spectron for testing Deprecated, Electron 13 max Use Playwright

See references/security/security-checklist.md for the full security audit checklist.

Scripts Reference

analyze-security.ts

Analyze Electron projects for security misconfigurations:

deno run --allow-read scripts/analyze-security.ts <path> [options]

Options:
  --strict    Enable all checks
  --json      Output JSON for CI
  -h, --help  Show help

Examples:
  # Analyze a project
  deno run --allow-read scripts/analyze-security.ts ./src

  # Strict mode for CI pipeline
  deno run --allow-read scripts/analyze-security.ts ./src --strict --json

scaffold-electron-app.ts

Scaffold a new Electron + React project with secure defaults:

deno run --allow-read --allow-write scripts/scaffold-electron-app.ts [options]

Options:
  --name <name>     App name (required)
  --path <path>     Target directory (default: ./)
<
how to use electron-best-practices

How to use electron-best-practices on Cursor

AI-first code editor with Composer

1

Prerequisites

Before installing skills in Cursor, ensure your development environment meets these requirements:

  • Cursor installed and configured on your development machine
  • Node.js version 16.0+ with npm package manager (verify with node --version)
  • Active project directory or workspace where you want to add electron-best-practices
2

Execute installation command

Execute the skills CLI command in your project's root directory to begin installation:

$npx skills add https://github.com/jwynia/agent-skills --skill electron-best-practices

The skills CLI fetches electron-best-practices from GitHub repository jwynia/agent-skills and configures it for Cursor.

3

Select Cursor when prompted

The CLI will show a list of available agents. Use arrow keys to navigate and space to select Cursor:

◆ Which agents do you want to install to?
│ ── Universal (.agents/skills) ── always included ────
│ • Amp
│ • Antigravity
│ • Cline
│ • Codex
│ ●Cursor(selected)
│ • Cursor
│ • Windsurf
4

Verify installation

Confirm successful installation by checking the skill directory location:

.cursor/skills/electron-best-practices

Reload or restart Cursor to activate electron-best-practices. Access the skill through slash commands (e.g., /electron-best-practices) or your agent's skill management interface.

Security & Verification Notice

We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.

Skills execute code in your development environment. Always verify the publisher's identity, review recent commits, and test in isolated environments before production deployment.

List & Monetize Your Skill

Submit your Claude Code skill and start earning

GET_STARTED →

Use Cases

User Story & Requirements Generation

Create detailed user stories, acceptance criteria, and feature specs

Example

Generate user stories for 'password reset feature' with acceptance criteria, edge cases, and test scenarios

Reduce spec writing time by 50%, ensure comprehensive coverage

Competitive Analysis

Research competitors, compare features, identify gaps

Example

Analyze 5 competitor products, create feature comparison matrix, suggest differentiation opportunities

Complete competitive research in 2 hours instead of 2 days

Roadmap Prioritization

Evaluate features using frameworks (RICE, ICE, Kano) and create prioritized backlogs

Example

Score 20 feature ideas using RICE framework, generate prioritized roadmap with rationale

Make data-driven prioritization decisions faster

Stakeholder Communication

Draft PRDs, status updates, and stakeholder presentations

Example

Create executive summary of Q3 roadmap, monthly progress report, feature launch announcement

Save 3-5 hours/week on communication overhead

Implementation Guide

Prerequisites

  • Claude Desktop or compatible AI client
  • Access to product documentation and roadmap tools (Jira, Notion, etc.)
  • Understanding of product management frameworks (RICE, Jobs-to-be-Done, etc.)
  • Stakeholder contact information and communication channels

Time Estimate

30-60 minutes to see productivity improvements

Installation Steps

  1. 1.Install product management skill
  2. 2.Start with user story generation for known feature
  3. 3.Progress to competitive analysis: research 2-3 competitors
  4. 4.Use for roadmap prioritization: apply RICE/ICE scoring
  5. 5.Draft stakeholder communications and refine based on feedback
  6. 6.Build template library for recurring PM tasks
  7. 7.Share effective prompts with product team

Common Pitfalls

  • Not validating competitive research—verify facts before sharing
  • Accepting user stories without involving engineering team
  • Over-relying on frameworks without qualitative judgment
  • Not customizing outputs to company culture and communication style
  • Skipping stakeholder validation of generated requirements

Best Practices

✓ Do

  • +Validate research and competitive analysis with real data
  • +Collaborate with engineering when generating technical requirements
  • +Customize frameworks and templates to your company context
  • +Use skill for first drafts, refine with stakeholder input
  • +Document successful prompt patterns for PM tasks
  • +Combine AI efficiency with human judgment and intuition

✗ Don't

  • Don't publish competitive analysis without fact-checking
  • Don't finalize user stories without engineering review
  • Don't make prioritization decisions solely on AI scoring
  • Don't skip customer validation of generated requirements
  • Don't ignore company-specific context and culture

💡 Pro Tips

  • Provide context: company goals, constraints, customer feedback
  • Ask for alternatives: 'Show 3 ways to prioritize this roadmap'
  • Request stakeholder-specific formatting: 'Executive summary vs. engineering spec'
  • Use skill for 70% generation + 30% customization to company needs

When to Use This

✓ Use When

Use for user story writing, competitive research, roadmap prioritization, stakeholder communication, and PRD drafting. Best for reducing repetitive documentation and research work.

✗ Avoid When

Avoid for strategic product vision (requires deep customer empathy), pricing decisions (needs market and financial expertise), or when face-to-face customer discovery is more valuable than speed.

Learning Path

  1. 1Basic: user stories, feature specs, status updates
  2. 2Intermediate: competitive analysis, prioritization frameworks, PRDs
  3. 3Advanced: product strategy, go-to-market planning, OKR setting
  4. 4Expert: product vision, market positioning, business model innovation

Discussion

Product Hunt–style comments (not star reviews)
  • No comments yet — start the thread.
general reviews

Ratings

4.862 reviews
  • Shikha Mishra· Dec 16, 2024

    I recommend electron-best-practices for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.

  • Valentina Anderson· Dec 16, 2024

    Keeps context tight: electron-best-practices is the kind of skill you can hand to a new teammate without a long onboarding doc.

  • Noah Gonzalez· Dec 8, 2024

    Useful defaults in electron-best-practices — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.

  • Kwame Chen· Dec 4, 2024

    electron-best-practices is among the better-maintained entries we tried; worth keeping pinned for repeat workflows.

  • Carlos Diallo· Nov 27, 2024

    I recommend electron-best-practices for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.

  • Ama Gupta· Nov 23, 2024

    Keeps context tight: electron-best-practices is the kind of skill you can hand to a new teammate without a long onboarding doc.

  • Yash Thakker· Nov 7, 2024

    Useful defaults in electron-best-practices — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.

  • Soo Yang· Nov 7, 2024

    electron-best-practices is among the better-maintained entries we tried; worth keeping pinned for repeat workflows.

  • Dhruvi Jain· Oct 26, 2024

    electron-best-practices has been reliable in day-to-day use. Documentation quality is above average for community skills.

  • Valentina Gonzalez· Oct 26, 2024

    electron-best-practices fits our agent workflows well — practical, well scoped, and easy to wire into existing repos.

showing 1-10 of 62

1 / 7