saltyshiomix / nextron

⚡ Next.js + Electron ⚡
https://npm.im/nextron
MIT License
3.97k stars 229 forks source link

Replace electron-serve #247

Open HaNdTriX opened 2 years ago

HaNdTriX commented 2 years ago

First of all thank you for this awesome package.

Problem

Currently we mount the BrowserWindow in two different ways, depending on the NODE_ENV.

  1. in production we use electron-serve to mount the application (mainWindow.loadURL('app://./home.html'))
  2. in development we load the next app from localhost (mainWindow.loadURL('http://localhost:${port}/home');)

This creates many gotchas, that could be avoided:

  1. Path may differ between production and development
  2. CORS may block specific resources
  3. URLs differ between production and development
  4. Nextron needs to wait for 8s for next to start
  5. Next.js 404 pages are not working properly

Solution

To solve these issues I'have created a package that allows us to mount Next.js on the same route inside electron no matter what mode it is currently in.

This is done, be using electrons registerStreamProtocol api, that implements a proxy to the localhost server of Next.js in development.

Replacing electron-serve with next-electron-server removes all the gotchas above and can simplify the bootup logic of nextron.

Example: background.js

import { app } from "electron";
import serveNextAt from "next-electron-server";
import { createWindow } from "./helpers";

serveNextAt("next://app", {
  outputDir: "./app",
  port: 8888,
});

(async () => {
  await app.whenReady();

  const mainWindow = createWindow("main", {
    width: 1000,
    height: 600,
  });

  await mainWindow.loadURL("next://app/home");
  // mainWindow.loadURL("next://app/page1");
  // mainWindow.loadURL("next://app/page2");
})();

next-electron-server has no external dependencies and could be integrated inside nextron.

What do you think about this proposal?

HaNdTriX commented 2 years ago

Due to changes regarding WebSockets in Next.js 12, I will close this issue for now, since the new Next.js DevServer will have issues using this approach.

In detail: Before Next.js 12 the DevServer was using Server Side Events to notify the client. This was working with the custom scheme approach very well. WebSockets change this because they use a different protocol.

https://nextjs.org/blog/next-12#other-improvements

niteshbalusu11 commented 2 years ago

@HaNdTriX I opened an issue on your repo, please take a look when you have a chance.

HaNdTriX commented 2 years ago

Reopening because we found a working solution: https://github.com/HaNdTriX/next-electron-server/issues/7#issuecomment-1143371567

andirsun commented 2 years ago

@HaNdTriX do you think you can upload an PR with an example ? I am glad to test it and if works we can merge it. I like the idea of having a single URL for both enviroments.