How do I use cookies in a react electron app?

Viewed 1243

I'm trying to use cookies in my electron react app.
At the moment I am completely unable to get it to work.
Requiring electron or importing it in a react component throws "TypeError: fs.existsSync is not a function".
Example code that breaks (in App.js for example):

import { WebContent } from 'electron';

or

const { session } = require('electron');

What I got to work was the following code in the Main.js file:

const { app, BrowserWindow, session } = require('electron');

session.defaultSession.cookies.get({}).then(cookies => {
    console.log(cookies)
});

I followed this tutorial Using Electron with React: The Basics to set up my electron react app.

I also followed this answer to a similar question but when i do this:

const { session } = window.require('electron');
console.log(session.defaultSession.cookies);

It says that session is undefined.

1 Answers

I guess, you want to use cookies within the renderer process (the js files used for rendering the UI). Since the cookies are normally only accessible within the main process and 'remote' access is turned off by default since version 10 of electron, this has to be turned on again by setting enableRemoteModule: true in main.js (main process) within the creation of the browser window. For me this looks like that

const mainWindow = new BrowserWindow({
  width: 800,
  height: 600,
  webPreferences: {
    nodeIntegration: true,
    enableRemoteModule: true,
  }
});

(Also, nodeIntegration: true is necessary in my case but maybe not in your case to prevent errors of process being undefined.)

Setting that, you can access the session object just by doing

import electron from 'electron';
const {remote} = electron;
const {session} = remote;

console.log(session.defaultSession.cookies);

in your renderer code. Also, you can access all the others objects usually only accessible in the main process via electron.remote. Cheers.

Related