HOWTO API-Routes - Using a server inside a Nextron/Electron app (express) #254
thiscantbeserious
started this conversation in
Ideas
Replies: 1 comment 1 reply
-
Sorry for late reply. We can't use Electron as a nodejs server because of security issues. Actually, we can use API routes in development mode (because this is a real nodejs server), but in production mode Electron can handle only static files so API routes won't work. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Since child_process.spawn/fork is supported officially by electron-builder after bundling - shipping a custom express server with dynamic routing is possible.
I tested this and am using this by myself after developing it first via a classic Next.js-Application using API-Routes.
Migration is as easy as using an electron router instead of using the Next.js API-Routes yourself.
In your background.js:
inside api/index.js:
for communicating via the api you need to override the CORS Headers to allow all (or just your local) origins like (also in your background.js):
Afterwards the server is accessible, not just in development mode - but also after building on the port you specified
(in this example its http://localhost:3000)
This was tested with Electron 16-18 and different Versions of Node from 16.0.0 up.
It's as easy as this - if you use asar (by default enabled) just make sure to unpack the api-folder with asarUnpack or disable asar as a simple fix after building.
The router itself will have access to all node_module dependencies shipped with the application.
Only drawback is that it's a "pure node-module" - means you won't have any of the electron-bits within those modules.
This also means much easier migration since you can just use all existing logic from HTTP-Routes and not have to implement routing via things like IPC and special funky dependencies that are often outdated
(IPC in itself is understandable but counter-intuitive with an app that should share the code between server/app-implementation without having to write large and complicated proxies).
This also solves heck a lot of issues introduced by trying to spawn a "background"-service via a New Browser-Window. Since those share the same process they also possibly block the Main UI and many node-modules won't work since they aren't context-aware (e.g. opencv4nodejs).
ping @saltyshiomix
Beta Was this translation helpful? Give feedback.
All reactions