javascriptreactjscookieselectronreact-cookie

How to set Cookie in Electron React using npm react-cookie package?


i am trying to set cookie in electron-react app using npm react-cookie package

and setting cookie like that

import { useCookies } from "react-cookie";
const [cookies, setCookie, removeCookie] = useCookies();
setCookie("isWorking", 121, { path: "/" });

its work fine in development mode but as i build electron application its not set my cookies in build application

SnapShot of cookies in development

SS_of_cookie

Snapshot in Production/electron build application enter image description here


Solution

  • In production, mode electron runs your react application in the file system so cookies never be saved in the file system in order to save cookies you have to run electron-react application in serve mode

      const server = require("./server");
    
        const createServer = async () => {
          if (isDev) {
            createWindow();
            win.loadURL("http://localhost:3000");
          } else {
            let port = null;
            for (let i = 5001; i < 6000; i++) {
              let isFree = await isPortFree(i);
          
              if (isFree) {
                port = i;
                break;
              }
            }
            currentPort = port;
            server.listen(port, () => {
              console.log(`Example app listening at http://localhost:${port}`);
              createWindow();
              win.loadURL(`http://localhost:${currentPort}`);
            });
          }
        };
    app.whenReady().then(createServer);
    

    and you server.js file will be like that

    const path = require("path");
    const express = require("express");
    
    const app = express();
    
    app.use(express.static(path.join(__dirname, "/app")));
    
    app.get("/", (req, res) => {
      res.sendFile(path.join(__dirname, "/app/index.html"));
    });
    
    module.exports = app;