Next.js is a fast, scalable framework for React Applications, supporting Hybrid Static and Server Renders. While it's made for static deployments on Vercel, it works very well with any existing server (e.g. express) you may have. This shows you how.
Deploying a Next.js Application on Express
Ah Next.js, the cool kids' react framework! It's quite good, has almost all the features you'd expect from a production framework with 70000 GitHub stars — Fast, Scalable, Hybrid Rendering, Splitting and Bundling, Routing, and even API Routes.
Created by, and made for Vercel, Next.js has evolved into the modern React framework of choice by thousands of developers – and for good reason.
Deployment of a Next.js app on Vercel is very simple. This site is actually deployed on Vercel.
So why deploy with Express?
Next.js also supports API routing, so deploying on a custom VM gives you the benefit of controlling the API routes instead of using them as serverless functions on the Vercel cloud – useful when the APIs are using the file system, or database running on the same VM, rather than a hosting service where it can be accessed by cloud functions.
Alright then, how do I set it up?
Next.js includes deployment scripts for running within a node.js server, but we're actually going to run an express server and let Next handle all the routes we want it to handle.
package.json will look like
In our node application start point,
index.js we can initialize the Next app as such
Next.js includes a request handler that you can pass into your express instance. This will be available after preparation
expressApp is your Express app instance initialized with
all (GET/POST/etc) the
* (wildcard) routes through Next above, but this functionality can be customized, for example, if you're only hosting your blog with Next.js, you can do away with routing all the
That's it, simple as that. When you run
expressApp.listen(), Next.js will take over all routes passed to it. You can even have multiple Next.js applications running together (not recommended, but still).
As long as you're running in development mode, Next.js will also support hot reloading for any pages (And also pages/api).
You mentioned deployment?
The node application is also ready to be deployed on a production environment, you'll need to build the next application(s) first (with
next build script). You can spawn multiple instances on a virtual machine using a process manager such as pm2.
which will spool cluster mode instances like these
Each of these instances run independently of one another, you can identify which instance it is by accessing the
NODE_APP_INSTANCE environment variable from within the app. (0 for root process, and so forth)