How to solve “Missing X server or $DISPLAY” when starting an ElectronJs App on Ubuntu 24 (X11)?

When I try to launch an ElectonJs application in development, I get the error [13117:1104/071616.998450:ERROR:ozone_platform_x11.cc(245)] Missing X server or $DISPLAY. The system used is Ubuntu 24.04.1 LTS and the windowing system is X11.

I get this error even with a minimum of code, just two files (main.js and index.html):

main.js

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

const createWindow = () => {
    const win = new BrowserWindow({
        width: 800,
        height: 600,
    });

    win.loadFile("index.html");
};

app.whenReady().then(() => {
    createWindow();
});

index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Hello World!</title>
    </head>
    <body>
        <div>Hello World from Humans !</div>
    </body>
</html>

Before the Missing X server or $DISPLAY error, I was getting the error [16018:1104/074700.492381:FATAL:setuid_sandbox_host.cc(163)] The SUID sandbox helper binary was found, but is not configured correctly.
But I solved it by executing in the terminal:

sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=1

I don’t know if this is the cause, it’s more detailed here The SUID sandbox helper binary was found, but is not configured correctly

I tried to set the $DISPLAY environment variable by adding to the end of the ~/.bashrc file :

export DISPLAY=127.0.0.1:0.0

As descript here Electron: Missing X server or $DISPLAY, but with no result