Book Image

Real-World Next.js

By : Michele Riva
Book Image

Real-World Next.js

By: Michele Riva

Overview of this book

Next.js is a scalable and high-performance React.js framework for modern web development and provides a large set of features, such as hybrid rendering, route prefetching, automatic image optimization, and internationalization, out of the box. If you are looking to create a blog, an e-commerce website, or a simple website, this book will show you how you can use the multipurpose Next.js framework to create an impressive user experience. Starting with the basics of Next.js, the book demonstrates how the framework can help you reach your development goals. You'll realize how versatile Next.js is as you build real-world applications with step-by-step explanations. This Next.js book will guide you in choosing the right rendering methodology for your website, securing it, and deploying it to different providers, all while focusing on performance and developer happiness. By the end of the book, you'll be able to design, build, and deploy modern architectures using Next.js with any headless CMS or data source.
Table of Contents (19 chapters)
Part 1: Introduction to Next.js
Part 2: Hands-On Next.js
Part 3: Next.js by Example

Getting started with Next.js

Now that we have some basic knowledge about Next.js use cases and the differences between client-side React and other frameworks, it's time to look at the code. We'll start by creating a new Next.js app and customizing its default webpack and Babel configurations. We'll also see how to use TypeScript as the primary language for developing Next.js apps.

Default project structure

Getting started with Next.js is incredibly easy. The only system requirement is to have both Node.js and npm installed on your machine (or development environment). The Vercel team created and published a straightforward but powerful tool called create-next-app for generating the boilerplate code for a basic Next.js app. You can use it by typing the following command in the terminal:

npx create-next-app <app-name>

It will install all the required dependencies and create a couple of default pages. At this point, you can just run npm run dev, and a development server will start on port 3000, showing a landing page.

Next.js will initialize your project using the Yarn package manager if installed on your machine. You can override this option by passing a flag to tell create-next-app to use npm instead:

npx create-next-app <app-name> --use-npm

You can also ask create-next-app to initialize a new Next.js project by downloading the boilerplate code from the Next.js GitHub repository. In fact, inside the Next.js repository, there's an examples folder containing tons of great examples about how to use Next.js with different technologies.

Let's say that you want to do some experiments with using Next.js on Docker – you can just pass the --example flag to the boilerplate code generator:

npx create-next-app <app-name> --example with-docker

create-next-app will download the code from and will install the required dependencies for you. At this point, you only have to edit the downloaded files, customize them, and you're ready to go.

You can find other great examples at If you're already familiar with Next.js, feel free to explore how Next.js can integrate with different services and toolkits (we'll see some of them in more detail later on in this book).

Now, let's go back to a default create-next-app installation for a moment. Let's open the terminal and generate a new Next.js app together:

npx create-next-app my-first-next-app --use-npm

After a few seconds, the boilerplate generation will succeed, and you'll find a new folder called my-first-next-app with the following structure:

- next.config.js
- node_modules/
- package-lock.json
- package.json
- pages/
  - _app.js
  - api/
    - hello.js
  - index.js
- public/
  - favicon.ico
  - vercel.svg
- styles/
  - Home.module.css
  - globals.css

If you're coming from React, you may be used to react-router or similar libraries for managing client-side navigation. Next.js makes navigation even easier by using the pages/ folder. In fact, every JavaScript file inside the pages/ directory will be a public page, so if you try to duplicate the index.js page and rename it about.js, you'll be able to go to http://localhost:3000/about and see an exact copy of your home page. We'll look in detail how Next.js handles client-side and server-side routes in the next chapter; for now, let's just think of the pages/ directory as a container for your public pages.

The public/ folder contains all the public and static assets used in your website. For example, you can put your images, compiled CSS stylesheets, compiled JavaScript files, fonts, and so on there.

By default, you will also see a styles/ directory; while this is very useful for organizing your application stylesheets, it is not strictly required for a Next.js project. The only mandatory and reserved directories are public/ and pages/, so make sure not to delete or use them for different purposes.

That said, you're free to add more directories and files to the project root, as it won't negatively interfere with the Next.js build or development process. If you want to organize your components under a components/ directory and your utilities under a utilities/ directory, feel free to add those folders inside your project.

If you're not into boilerplate generators, you can bootstrap a new Next.js application by just adding all the required dependencies (as previously listed) and the basic folder structure that we just saw to your existing React application, and it'll just work with no other configuration required.

TypeScript integration

The Next.js source code is written in TypeScript and natively provides high-quality type definitions to make your developer experience even better. Configuring TypeScript as the default language for your Next.js app is very easy; you just have to create a TypeScript configuration file (tsconfig.json) inside the root of your project. If you try to run npm run dev, you'll see the following output:

It looks like you're trying to use TypeScript but do not have the required package(s) installed.
Please install typescript and @types/react by running:
     npm install --save typescript @types/react
     If you are not trying to use TypeScript, please remove
     the tsconfig.json file from your package root (and any 
     TypeScript files in your pages directory).

As you can see, Next.js has correctly detected that you're trying to use TypeScript and asks you to install all the required dependencies for using it as the primary language for your project. So now you just have to convert your JavaScript files to TypeScript, and you're ready to go.

You may notice that even if you created an empty tsconfig.json file, after installing the required dependencies and rerunning the project, Next.js fills it with its default configurations. Of course, you can always customize the TypeScript options inside that file, but keep in mind that Next.js uses Babel to handle TypeScript files (via the @babel/plugin-transform-typescript), and it has some caveats, including the following:

  • The @babel/plugin-transform-typescript plugin does not support const enum, often used in TypeScript. To support it, make sure to add babel-plugin-const-enum to the Babel configuration (we'll see how in the Custom Babel and webpack configuration section).
  • Neither export = nor import = are supported because they cannot be compiled to valid ECMAScript code. You should either install babel-plugin-replace-ts-export-assignment, or convert your imports and exports to valid ECMAScript directives, such as import x, {y} from 'some-package' and export default x.

There are other caveats, too; I'd suggest you read them before going further with using TypeScript as the main language for developing your Next.js app:

Also, some compiler options might be a bit different from the default TypeScript ones; once again, I'd suggest you read the official Babel documentation, which will always be up to date:

Next.js also creates a next-env.d.ts file inside the root of your project; feel free to edit it if you need, but make sure not to delete it.

Custom Babel and webpack configuration

As already mentioned in the TypeScript Integration section, we can customize Babel and webpack configurations.

There might be many reasons we would like to customize our Babel configuration. If you're not very familiar with it, let me quickly explain what I'm talking about. Babel is a JavaScript transcompiler mainly used for transforming modern JavaScript code into a backward-compatible script, which will run without problem on any browser.

If you're writing a web app that must support older browsers such as Internet Explorer (IE) 10 or Internet Explorer 11, Babel will help you a lot. It allows you to use modern ES6/ESNext features and will transform them into IE-compatible code at build time, letting you maintain a beautiful developer experience with very few compromises.

Also, the JavaScript language (standardized under the ECMAScript specification) is quickly evolving. So while some fantastic features have already been announced, you'll have to wait for years before being able to use them in both browsers and Node.js environments. That's because after the ECMA committee has accepted these features, the companies developing web browsers and communities working on the Node.js project will have to plan a roadmap for adding support for these enhancements. Babel solves this problem by transpiling modern code into a compatible script for today's environments.

For example, you may be familiar with this code:

export default function() {
  console.log("Hello, World!");

But if you try to run it in Node.js, it will throw a syntax error because the JavaScript engine won't recognize the export default keywords.

Babel will transform the preceding code into this equivalent ECMAScript code, at least until Node.js gets support for the export default syntax:

"use strict";
Object.defineProperty(exports, "__esModule", {
  value: true
exports.default = _default;
function _default() {
  console.log("Hello, World!");

This makes it possible to run this code on Node.js with no problems.

You can customize your default Next.js Babel configuration by simply creating a new file called .babelrc inside the root of your project. You will notice that if you leave it empty, the Next.js build/development process will throw an error, so make sure to add at least the following code:

  "presets": ["next/babel"]

This is the Babel preset created by the Vercel team specifically for building and developing Next.js applications. Let's say that we're building an application, and we want to use an experimental ECMAScript feature such as the pipeline operator; if you're not familiar with it, it basically allows you to re-write this code as follows:

console.log(Math.random() * 10);
// written using the pipeline operator becomes:
  |> x => x * 10
  |> console.log

This operator has not been officially accepted yet by TC39 (the technical committee behind the ECMAScript specification), but you can start using it today, thanks to Babel.

To provide support for this operator in your Next.js app, all you need to do is install the Babel plugin using npm:

npm install --save-dev @babel/plugin-proposal-pipeline-operator @babel/core

Then update your custom .babelrc file as follows:

  "presets": ["next/babel"],
  "plugins": [
      { "proposal": "fsharp" }

You can now restart your development server and use this experimental feature.

If you're interested in using TypeScript as the main development language for your Next.js app, you can just follow the same procedure for adding all the TypeScript-specific plugins to your Babel configuration. There are chances that during your Next.js development experience, you may also want to customize the default webpack configuration.

While Babel only takes modern code as input and produces backward-compatible scripts as output, webpack creates the bundles containing all the compiled code for a specific library, page, or feature. For instance, if you create a page containing three components from three different libraries, webpack will merge everything into a single bundle to be shipped to the client. To put it simply, we can think of webpack as an infrastructure for orchestrating different compilation, bundle, and minification tasks for every web asset (JavaScript files, CSS, SVG, and so on).

If you want to use CSS preprocessors such as SASS or LESS to create your app styles, you will need to customize the default webpack configuration to parse SASS/LESS files and produce plain CSS as output. The same, of course, occurs for JavaScript code using Babel as a transpiler.

We talk more in detail about CSS preprocessors in the following chapters, but for now, we just need to keep in mind that Next.js provides an easy way for customizing the default webpack configuration.

As we saw earlier, Next.js provides a convention-over-configuration approach, so you don't need to customize most of its settings for building a real-world application; you just have to follow some code conventions.

But if you really need to build something custom, you'll be able to edit the default settings via the next.config.js file most of the time. You can create this file inside the root of your project. It should export an object by default, where its properties will override the default Next.js configurations:

module.exports = {
  // custom settings here

You can customize the default webpack configuration by creating a new property inside this object called webpack. Let's suppose that we want to add a new imaginary webpack loader called my-custom-loader; we can proceed as follows:

module.exports = {
  webpack: (config, options) => {
      test: /\.js/,
      use: [
        // This is just an example
        //don't try to run this as it won't work
          loader: "my-custom-loader", // Set your loader
          options: loaderOptions, // Set your loader 
    return config;

So, as you can see, we're writing a proper webpack configuration that will later be merged with Next.js' default settings. This will allow us to extend, override, or even delete any setting from the default configuration, as although deleting default settings is generally never a good idea, there might be cases where you need it (if you're brave enough!).