Using a Custom Server

Learn when to use the custom web server with Next.js and some common use cases.

As we’ve already seen, Next.js ships with its own server, so we don’t need to configure a custom one to get started with writing web applications with this framework. Still, there are some cases where we may want to serve a Next.js app from a custom web server, such as Express.js or Fastify, and the framework makes this possible by exposing some straightforward APIs that we’ll be looking into in just one moment. But before looking at the implementation, let’s answer an important question: do we really need a custom server?

The short answer is, most of the time, no. Next.js is such a complete framework that we rarely need to customize the server-side logic via Express.js, Fastify, or any other server-side framework. But sometimes, it’s just inevitable because it can solve specific problems.

Use cases for a custom server

Some common use cases for a custom server are as follows:

  • Integrating Next.js into an existing server: Suppose we’re refactoring an existing web application to adopt Next.js. We may want to maintain as much server-side logic as possible, our middlewares, and routes. In that case, we can progressively add Next.js by choosing which pages of our websites will be served from the framework and which ones will be rendered by something else.

  • Multitenancy: Even though Next.js supports multiple domains and conditional rendering depending on the current hostname, there are cases where we may need more control and a simplified workflow for handling up to thousands of different domains.

  • We want more control: Even though Next.js provides everything we need for creating a robust and complete user experience, there are cases where our app is growing in complexity, and we want to organize the back-end code using different approaches, such as adopting the MVC philosophyThe MVC philosophy involves structuring software into three roles: Models managing data, Views presenting data, and Controllers handling interactions., where Next.js is just the “view” part of the process.

Note: Check out this GitHub page for a native solution and this second page to study more about Express.js/Fastify multitenant middleware for Next.js.

Limitations of custom servers and Vercel compatibility for Next.js

While a custom server could solve some problems, it also has some downsides. For instance, we cannot deploy a custom server to Vercel, the platform created by the Next.js authors, which is highly optimized for the framework. Also, we’ll need to write and maintain more code, which can be a significant downside if we’re working on a side project, in a small team, or for a small company.

Get hands-on with 1200+ tech skills courses.