Reader small image

You're reading from  Real-World Next.js

Product typeBook
Published inFeb 2022
Reading LevelBeginner
PublisherPackt
ISBN-139781801073493
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Michele Riva
Michele Riva
author image
Michele Riva

Michele Riva is a passionate and experienced Software Engineer and Google Developer Expert from Milan, Italy. During the last years, he has contributed to many open-source projects from big companies and foundations, such as Facebook and Apache, in many different programming languages and paradigms, including Haskell, Erlang, Go, and JavaScript. He has also written dozens of public domain articles on different topics (software architecture, functional programming, performance enhancements, etc.) and gave many talks at conferences and meetups. He is currently working as a Senior Software Engineer in the architecture team at ViacomCBS, where he is building a multi-tenant Node.js application at the heart of their websites and streaming services.
Read more about Michele Riva

Right arrow

Chapter 8: Using a Custom Server

Next.js is an incredibly powerful framework. In the first seven chapters of this book, we've been able to create some nice server-side rendered web applications without really caring about tweaking and customizing the web server. Of course, there are few chances for us to discuss implementing a Next.js application inside an Express.js or Fastify server in a real-life scenario, but knowing how to do so is likely to be handy on many occasions.

Talking for myself, in the past years, I've created dozens of large-scale web applications using Next.js, and I rarely needed to use a custom server. However, in some cases, it is inevitable.

We will look at the following topics in detail:

  • What using a "custom server" means, when we might need to use it, and what are the options.
  • How to use Express.js and Next.js together
  • How to use Fastify and Next.js together
  • What are the requirements for deploying a custom server...

Technical requirements

To run the code examples in this chapter, you need to have both Node.js and npm installed on your local machine.

If you prefer, you can use an online IDE such as https://repl.it or https://codesandbox.io; they both support Next.js, and you don't need to install any dependency on your computer. As with the other chapters, you can find the codebase for this chapter on GitHub: https://github.com/PacktPublishing/Real-World-Next.js.

About using a custom server

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 is just inevitable, as it can solve specific problems.

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

  • Integrating Next.js into an existing server: Suppose you're refactoring an...

Using a custom Express.js server

Writing a custom Express.js server to render Next.js pages is easier than you might think. Let's create a new project and install the following dependencies:

yarn add express react react-dom next

Once we've installed these four packages, we can start writing a custom Express.js server. Let's create an index.js file inside the project root and start by importing the required dependencies:

const { parse } = require('url');
const express = require('express');
const next = require('next');

We now need to instantiate the Next.js app, and we can do that by adding the following code right after the import statements:

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });

Let's complete our server by writing the main function, which takes every incoming GET request and passes it to Next.js for server-side rendering:

async function main() {
  try...

Using a custom Fastify server

Fastify is an incredible web framework for Node.js. As the name suggests, it can be attractive as it is really, really fast when compared to other web frameworks, such as Express.js, Koa, and Hapi. If you're interested in learning more about its performance, you can find the official benchmarks in the following repository: https://github.com/fastify/benchmarks.

This web framework is developed and maintained by some of Node.js' core developers, such as Matteo Collina (Node.js technical steering committee member). So, as you can imagine, the people behind Fastify perfectly know how the runtime works and have made the framework as optimized as possible.

But Fastify is not just about the performance: it also enforces excellent best practices to keep the developer experience as good as possible. It also has a robust plugin system that allows everyone to write their own plugin or middleware with ease. If you haven't already, I highly recommend...

Summary

In this chapter, we've seen how to integrate Next.js with two of the most popular web frameworks for Node.js: Express.js and Fastify. It is possible to integrate Next.js with other web frameworks, and the implementation won't be different from what we've seen in the previous sections.

One thing to consider when using a custom server of any kind (be it Express.js, Fastify, or any other framework) is that we cannot deploy it to some providers, such as Vercel or Netlify.

Technically speaking, many providers (Vercel, Netlify, Cloudflare, and so on) provide a great way to serve Node.js-powered applications: serverless functions. However, since this is quite an advanced topic, we will discuss it in depth in Chapter 11, Different Deployment Platforms.

As we'll see in Chapter 11, Different Deployment Platforms, Next.js is a framework highly optimized to run on Vercel, the infrastructure provided by the company behind the creation (and maintenance) of the...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Real-World Next.js
Published in: Feb 2022Publisher: PacktISBN-13: 9781801073493
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Michele Riva

Michele Riva is a passionate and experienced Software Engineer and Google Developer Expert from Milan, Italy. During the last years, he has contributed to many open-source projects from big companies and foundations, such as Facebook and Apache, in many different programming languages and paradigms, including Haskell, Erlang, Go, and JavaScript. He has also written dozens of public domain articles on different topics (software architecture, functional programming, performance enhancements, etc.) and gave many talks at conferences and meetups. He is currently working as a Senior Software Engineer in the architecture team at ViacomCBS, where he is building a multi-tenant Node.js application at the heart of their websites and streaming services.
Read more about Michele Riva