JSPM

  • Created
  • Published
  • Downloads 29246
  • Score
    100M100P100Q163198F
  • License MIT

Electron support for tRPC

Package Exports

  • electron-trpc

Readme

electron-trpc

NPM MIT

Build IPC for Electron with tRPC

  • Expose APIs from Electron's main process to one or more render processes.
  • Build fully type-safe IPC.
  • Secure alternative to opening servers on localhost.
  • Subscription support coming soon.

Installation

# Using yarn
yarn add electron-trpc

# Using npm
npm install --save electron-trpc

Setup

  1. Add your tRPC router to the Electron main process using createIPCHandler:

    import { app, ipcMain } from 'electron';
    import { createIPCHandler } from 'electron-trpc';
    import { router, createContext } from './api';
    
    app.on('ready', () => {
      createIPCHandler({ ipcMain, router, createContext }));
    
      // ...
    });
  2. Expose the IPC to the render process from the preload file:

    import { contextBridge, ipcRenderer } from 'electron';
    import { exposeElectronTRPC } from 'electron-trpc';
    
    contextBridge.exposeInMainWorld('electron-trpc', exposeElectronTRPC(ipcRenderer));

    Note: using exposeInMainWorld depends on contextIsolation to be enabled, which is the default.

  3. When creating the client in the render process, use the ipcLink (instead of the HTTP or batch HTTP links):

    import * as trpc from '@trpc/client';
    import { ipcLink } from 'electron-trpc';
    
    export const trpcClient = trpc.createClient({
      links: [ipcLink()],
    });
  4. Now you can use the client in your render process as you normally would (e.g. using @trpc/react).