Using Next.js with Electron

Faruk Çakı
2 min readJan 24, 2019

In this blog post, we will see how to use Next.js, a quite popular React framework, with Electron framework for building cross-platform desktop applications.

If you don’t know about Next.js and looking for a React solution simply read this.

What is Next.js?

Next.js is easy to use React framework for server-side rendered web apps. With Next.js, you don’t need to use React Router nor such additional libraries, routing and creating pages are super easy with Next! Go here and follow the official guides if you are not familiar with Next.

Creating an Electron Project

Open a new folder and create a basic starter applicationon it, you can use electron-quick-start code from official docs.

Create Next.js App and Start

I assume that you already know that. If not, create a hello-world application by following this. (Keep your Next.js app in a separate folder, don’t mix it up with Electron)

Start your app with npm run dev, now your React application runs on localhost:3000

Using Next.js and Electron Together

Now, we want to use our React/Next application as an interface of our Electron app instead of static .html we created for our starter project.

Go to your Electron project’s folder, open main.js and find that line:

win.loadFile(‘index.html’)

As you probably aware, your Electron app is using index.html file and displaying that as a view. We don’t want to use that static HTML file, we will use our React application instead.

Change that line with:

win.loadURL(‘http://localhost:3000’)

Now run your Electron app: “electron .”

Tadaa! We got our Next app inside our electron window!

Now you can start coding your desktop applications using Next.js

Umm... What about Production?

You may ask what will happen when we package our Electron app into production, how to handle React app etc. Don’t worry, it is so simple, all we need to do is export our Next.js as static HTML, then we will replace the line we changed above with win.loadFile(“./next-directory/index.html”).

I will make another blog post for that hopefully soon.

But… We are not done yet since we need to use some Node.js modules which are not available on React/Next since they run on the browser and doesn’t support backend libraries. Such as electron’s IPC module for communication between React and Electron. We are going to hack config file a bit in order to accomplish that, it is also super simple 😏

That’s the next blog post’s topic. See you soon! 🤞

--

--