Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $9.99/month after trial. Cancel anytime.

Real-World Next.js: Build scalable, high-performance, and modern web applications using Next.js, the React framework for production
Real-World Next.js: Build scalable, high-performance, and modern web applications using Next.js, the React framework for production
Real-World Next.js: Build scalable, high-performance, and modern web applications using Next.js, the React framework for production
Ebook608 pages9 hours

Real-World Next.js: Build scalable, high-performance, and modern web applications using Next.js, the React framework for production

Rating: 0 out of 5 stars

()

Read preview

About this ebook

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.

LanguageEnglish
Release dateFeb 28, 2022
ISBN9781801079877
Real-World Next.js: Build scalable, high-performance, and modern web applications using Next.js, the React framework for production

Related to Real-World Next.js

Related ebooks

Internet & Web For You

View More

Related articles

Reviews for Real-World Next.js

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Real-World Next.js - Michele Riva

    Cover.png

    BIRMINGHAM—MUMBAI

    Real-World Next.js

    Copyright © 2022 Packt Publishing

    All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

    Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

    Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

    Group Product Manager: Pavan Ramchandani

    Publishing Product Manager: Aaron Tanna

    Senior Editor: Aamir Ahmed

    Content Development Editor: Feza Shaikh

    Technical Editor: Simran Udasi

    Copy Editor: Safis Editing

    Project Coordinator: Manthan Patel

    Proofreader: Safis Editing

    Indexer: Manju Arasan

    Production Designer: Roshan Kawale

    Marketing Coordinator: Anamika Singh

    First published: January 2022

    Production reference: 1310122

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham

    B3 2PB, UK.

    ISBN 978-1-80107-349-3

    www.packt.com

    I want to dedicate this book to Alice. It wouldn't have been possible without your patience, support, and love

    - Michele Riva

    Contributors

    About the author

    Michele Riva is a passionate and experienced software architect and Google Developer Expert from Milan, Italy. Over the years, he has contributed to many open source projects from big companies and foundations in many different programming languages and paradigms, including Haskell, Elixir, Go, and TypeScript. He has also written dozens of public domain articles on a broad range of topics and given many talks at international conferences and meetups.

    While writing this book, he worked as a senior software engineer in the architecture team of ViacomCBS, building a multi-tenant Node.js application at the heart of their streaming websites and networks.

    Currently, he's employed as a senior software architect at NearForm.

    About the reviewers

    Alberto Schiabel (@jkomyno) is a software engineer from Venice who sold his first apps in his teenage years. He obtained a master's degree in computer science from the University of Padua and has collaborated with other universities in Europe. Alberto has worked in several product and consulting software companies, but he has also worked as a freelancer and start-up cofounder. He enjoys mentoring colleagues and learning something new every day. Alberto discovered Node.js and React.js in 2015 and has worked with these technologies ever since, also as an open source maintainer. He's now primarily interested in distributed backend architectures and strongly typed functional programming, but he's amazed by the beauty of Next.js nonetheless.

    Christian Sarnataro is a software engineer with more than 15 years of experience in web development. He is always trying to keep up to date with the latest technologies and best practices with a specific focus, in the last few years, on frontend development.

    He is currently a senior SW engineer at Arduino, an open source hardware and software company well known for its electronic prototyping and IoT platforms.

    In the past, he has worked for mid-to-large companies as a web architect, mobile developer, and teacher.

    Table of Contents

    Preface

    Part 1: Introduction to Next.js

    Chapter 1: A Brief Introduction to Next.js

    Technical requirements

    Introducing Next.js

    Comparing Next.js to other alternatives

    Gatsby

    Razzle

    Nuxt.js

    Angular Universal

    So, why Next.js?

    Moving from React to Next.js

    Getting started with Next.js

    Default project structure

    TypeScript integration

    Custom Babel and webpack configuration

    Summary

    Chapter 2: Exploring Different Rendering Strategies

    Technical requirements

    Server-side rendering (SSR)

    Client-side rendering (CSR)

    Using the React.useEffect hook

    Using the process.browser variable

    Using dynamic component loading

    Static site generation

    Summary

    Chapter 3: Next.js Basics and Built-In Components

    Technical requirements

    Routing system

    Using route variables inside our pages

    Using route variables inside components

    Client-side navigation

    Serving static assets

    Next.js' automatic image optimization

    Running automatic image optimization on external services

    Handling metadata

    Grouping common meta tags

    Customizing _app.js and _document.js pages

    The _app.js page

    The _document.js page

    Part 2: Hands-On Next.js

    Chapter 4: Organizing the Code Base and Fetching Data in Next.js

    Technical requirements

    Organizing the folder structure

    Organizing the components

    Organizing utilities

    Organizing static assets

    Organizing styles

    Lib files

    Data fetching

    Fetching data on the server side

    Consuming REST APIs on the server side

    Fetching data on the client side

    Consuming REST APIs on the client side

    Consuming GraphQL APIs

    Summary

    Chapter 5: Managing Local and Global States in Next.js

    Technical requirements

    Local state management

    Global state management

    Using the Context APIs

    Using Redux

    Summary

    Chapter 6: CSS and Built-In Styling Methods

    Technical requirements

    Exploring and using Styled JSX

    CSS modules

    Integrating SASS with Next.js

    Summary

    Chapter 7: Using UI Frameworks

    Technical requirements

    An introduction to UI libraries

    Integrating Chakra UI in Next.js

    Building an employee directory with Chakra UI and Next.js

    Conclusive words about Chakra UI

    Integrating TailwindCSS in Next.js

    Integrating Headless UI

    Summary

    Chapter 8: Using a Custom Server

    Technical requirements

    About using a custom server

    Using a custom Express.js server

    Using a custom Fastify server

    Summary

    Chapter 9: Testing Next.js

    Technical requirements

    An introduction to testing

    Running unit and integration tests

    End-to-end testing with Cypress

    Summary

    Chapter 10: Working with SEO and Managing Performance

    Technical requirements

    SEO and performance – an introduction

    Rendering strategies, from a performance and SEO perspective

    The reasoning behind a real-world website example

    Rendering the image detail page

    Private routes

    A quick recap regarding our decisions

    Working with SEO

    Dealing with performance

    Summary

    Chapter 11: Different Deployment Platforms

    Technical requirements

    A brief introduction to different deployment platforms

    Deploying to the Vercel platform

    Deploying a static site to a CDN

    Choosing a CDN

    Deploying Next.js on any server

    Running Next.js in a Docker container

    Summary

    Part 3: Next.js by Example

    Chapter 12: Managing Authentication and User Sessions

    Technical requirements

    A brief introduction to user sessions and authentication

    Understanding JSON web tokens

    Custom authentication – the good, the bad, and the ugly

    Implementing authentication using Auth0

    Customizing Auth0

    Summary

    Chapter 13: Building an E-Commerce Website with Next.js and GraphCMS

    Technical requirements

    Creating e-commerce websites for the modern web

    Setting up GraphCMS

    Creating the storefront, cart, and product detail pages

    Processing payments using Stripe

    Summary

    Chapter 14: Example Projects and Next Steps for Learning More

    One framework, endless possibilities

    Real-world applications for practicing with Next.js

    Streaming website

    Blogging platform

    Real-time chat website

    Next steps

    Summary

    Other Books You May Enjoy

    Preface

    Next.js is a scalable and high-performance React.js framework for modern web development. It provides a large set of features, such as hybrid rendering, route prefetching, automatic image optimization, and internationalization, out of the box.

    Next.js is an exciting technology that can be used for many purposes. If you (or your company) want to create an e-commerce platform, a blog, or a simple website, with this book, you can learn how to do it without compromising on performance, user experience, or developer happiness. Starting from the basics of Next.js, you will understand how the framework can help you reach your goals, and you will realize how versatile Next.js is by building real-world applications with step-by-step explanations. You will learn how to choose the proper rendering methodology for your website, how to secure it, and how to deploy it to different providers. We'll always keep a focus on performance and developer happiness.

    By the end of this book, you will be able to design, build, and deploy beautiful and modern architectures using Next.js with any headless CMS or data source.

    Who this book is for

    This book is for web developers who want to improve their React skills by building scalable and maintainable full-stack applications using a modern web framework – Next.js. Intermediate-level knowledge of ES6+, React, Node.js, and REST is assumed.

    What this book covers

    Chapter 1, A Brief Introduction to Next.js, serves as an introduction to the framework, showing how to set up a new project, customize its configurations, and (if needed) how to adopt TypeScript as the primary programming language for Next.js development.

    Chapter 2, Exploring Different Rendering Strategies, dives into rendering methods, teaching the differences between server-side rendering, static site generation, incremental static regeneration, and more.

    Chapter 3, Next.js Basics and Built-In Components, provides a complete explanation of the Next.js routing system and essential built-in components, focusing on search engine optimization and performance.

    Chapter 4, Organizing the Code Base and Fetching Data in Next.js, covers some helpful tips about organizing a Next.js project and fetching data on both the server and client side.

    Chapter 5, Managing Local and Global States in Next.js, introduces state management via React Context and Redux, teaching you how to handle local state (at the component level) and global state (application-wide).

    Chapter 6, CSS and Built-In Styling Methods, introduces the basic styling methods built into Next.js, such as Styled JSX and CSS modules. It also shows how to enable the SASS preprocessor for local development and production builds.

    Chapter 7, Using UI Frameworks, concludes the conversation around styling by introducing some modern UI frameworks, such as TailwindCSS, Chakra UI, and Headless UI.

    Chapter 8, Using a Custom Server, explores the reasons why we might (and might not!) need a custom server for our Next.js applications. It also shows how to integrate Next.js with Express.js and Fastify, two of the most popular web frameworks for Node.js.

    Chapter 9, Testing Next.js, introduces some unit and end-to-end testing best practices by adopting Cypress and react-testing-library.

    Chapter 10, Working with SEO and Managing Performance, dives into SEO and performance enhancements by introducing useful tips and tricks for improving any Next.js application.

    Chapter 11, Different Deployment Platforms, shows how to choose the right platform to host a Next.js app, depending on its features and many other aspects.

    Chapter 12, Managing Authentication and User Session, describes how to manage user authentication securely by choosing the right authentication provider. It also shows how to integrate Auth0, a popular identity management platform, with any Next.js app.

    Chapter 13, Building an E-Commerce Website with Next.js and GraphCMS, dives into creating a real-world Next.js e-commerce platform with Next.js, Chakra UI, and GraphCMS.

    Chapter 14, Example Projects and Next Steps for Learning More, concludes the book by giving some valuable tips on how to proceed with learning the framework and provides some example projects to implement to acquire even more confidence with Next.js.

    To get the most out of this book

    To get the most out of this book, you can follow along by writing all the code examples displayed in the following chapters. If you find yourself stuck with an error, you can download all the working code examples from the book's GitHub repository.

    If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book's GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

    Download the example code files

    You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Real-World-Next.js. If there's an update to the code, it will be updated in the GitHub repository.

    We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

    Download the color images

    We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here:

    https://static.packt-cdn.com/downloads/9781801073493_ColorImages.pdf.

    Conventions used

    There are a number of text conventions used throughout this book.

    Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: We're going to use Next.js' built-in getServerSideProps function to dynamically get the [name] variable from the URL and greet the user.

    A block of code is set as follows:

    export async function getServerSideProps({ params }) { const { name } = params; return { props: { name } } }function Greet(props) { return (

    Hello, {props.name}!

    )}export default Greet;

    When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

    Read post Read post Read post

    Any command-line input or output is written as follows:

    echo Hello, world! >> ./public/index.txt

    Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: In fact, if we open the Google Chrome developer tools and go to Network, we can select the HTTP request for the endpoint above and see the authorization token in plain text under the Request Headers section.

    Tips or Important Notes

    Appear like this.

    Get in touch

    Feedback from our readers is always welcome.

    General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

    Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

    Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

    If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

    Share Your Thoughts

    Once you’ve read Real-World Next.js, we’d love to hear your thoughts! Please click here to go straight to the Amazon review pagefor this book and share your feedback.

    Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content..

    Part 1: Introduction to Next.js

    In this part, we will cover the basics of Next.js, starting with what differentiates it from other frameworks, its unique features, and how to bootstrap a new project from scratch.

    This section comprises the following chapters:

    Chapter 1, A Brief Introduction to Next.js

    Chapter 2, Exploring Different Rendering Strategies

    Chapter 3, Next.js Basics and Built-In Components

    Chapter 1: A Brief Introduction to Next.js

    Next.js is an open source JavaScript web framework for React that ships with a rich set of features out of the box, such as server-side rendering, static site generation, and incremental static regeneration. These are just some of the many built-in components and plugins that make Next.js a framework ready for both enterprise-level applications and small websites.

    This book aims to show you the full potential of this framework while building real-world applications and use cases, such as e-commerce websites and blogging platforms. You will learn the basics of Next.js, how to choose between different rendering strategies and deployment methodologies, and different tips and approaches for making your web application both scalable and maintainable.

    In this chapter, we will cover the following topics:

    Introduction to the Next.js framework

    Comparing Next.js with other popular alternatives

    Differences between Next.js and client-side React

    Anatomy of a default Next.js project

    How to develop Next.js applications using TypeScript

    How to customize both Babel and webpack configurations

    Technical requirements

    To get started with Next.js, you need to install a couple of dependencies on your machine.

    First of all, you need to install Node.js and npm. Please refer to this blog post if you need a detailed guide for installing them: https://www.nodejsdesignpatterns.com/blog/5-ways-to-install-node-js.

    If you don't want to install Node.js on your local machine, some online platforms will let you follow the code examples in this book using an online IDE for free, such as https://codesandbox.io and https://repl.it.

    Once you have both Node.js and npm installed (or you're using an online environment), you'll only need to follow the instructions displayed in each section of this book for installing the required project-specific dependencies using npm.

    You can find complete code examples on GitHub under the following repository: https://github.com/PacktPublishing/Real-World-Next.js. Feel free to fork, clone, and edit this repository for any experimentation with Next.js.

    Introducing Next.js

    Web development has changed a lot over the last few years. Before the advent of modern JavaScript frameworks, creating dynamic web applications was complex, and it required many different libraries and configurations to make them work as expected.

    Angular, React, Vue, and all the other frameworks have enabled the web to evolve very quickly, and brought with them some very innovative ideas to frontend web development.

    React, in particular, was created by Jordan Walke at Facebook and was heavily influenced by the XHP Hack Library. XHP allowed Facebook's PHP and Hack developers to create reusable components for the frontend of their applications. The JavaScript library became open source in 2013 and forever changed how we build websites, web apps, native apps (with React Native later on), and even VR experiences (with React VR). As a result, React has quickly become one of the most loved and popular JavaScript libraries, with millions of websites using it in production for many different purposes.

    There was just one problem: by default, React runs on the client side (meaning that it runs on the web browser), so a web application written entirely with that library could negatively affect Search Engine Optimization (SEO) and initial load performance, as it takes some time to be correctly rendered on screen. In fact, to display the complete web app, the browser had to download the entire application bundle, parse its content, then execute it and render the result in the browser, which could take up to a few seconds (with very large applications).

    Many companies and developers started investigating how to pre-render the application on the server, letting the browser display the rendered React app as plain HTML, making it interactive as soon as the JavaScript bundle has been transferred to the client.

    Then, Vercel came up with Next.js, which has turned out to be a game-changer.

    Since its first release, the framework has provided many innovative features out of the box, such as automatic code-splitting, server-side rendering, file-based routing systems, route pre-fetching, and so on. Next.js showed how easy it should be to write universal web applications by allowing developers to write reusable code for both client and server sides and making very complex tasks (such as code-splitting and server-side rendering) effortless to implement.

    Today, Next.js provides tons of new features out of the box, such as the following:

    Static site generation

    Incremental static generation

    Native TypeScript support

    Automatic polyfills

    Image optimization

    Support for internationalization

    Performance analytics

    All this, along with many other great features that we'll look at in depth later on in this book.

    Today, Next.js is used in production by top-level companies such as Netflix, Twitch, TikTok, Hulu, Nike, Uber, Elastic, and many others. If you're interested, you can read the complete list at https://nextjs.org/showcase.

    Next.js showed how versatile React could be for building many different applications at any scale, and it's not surprising to see it in use by both big companies and small start-ups. By the way, it is not the only framework that lets you render JavaScript on the server side, as we'll see in the next section.

    Comparing Next.js to other alternatives

    As you may be wondering, Next.js is not the only player in the server-side rendered JavaScript world. However, alternatives might be considered depending on the final purpose of a project.

    Gatsby

    One popular alternative is Gatsby. You may want to consider this framework if you seek to build static websites. Unlike Next.js, Gatsby only supports static site generation and does it incredibly well. Every page is pre-rendered at build time and can be served on any Content Delivery Network (CDN) as a static asset, allowing the performance to be incredibly competitive compared to dynamically server-side rendered alternatives. The biggest downside of using Gatsby over Next.js is that you'll lose the ability of dynamic server-side rendering, which is an important feature for building more dynamically data-driven and complex websites.

    Razzle

    Less popular than Next.js, Razzle is a tool for creating server-side rendered JavaScript applications. It aims to maintain the ease of use of create-react-app while abstracting all the complex configurations needed for rendering the application both on the server and client sides. The most significant advantage of using Razzle instead of Next.js (or the following alternatives) is that it is framework agnostic. You can choose your favorite frontend framework (or language), such as React, Vue, Angular, Elm, or Reason-React… it's your choice.

    Nuxt.js

    If you have experience with

    Enjoying the preview?
    Page 1 of 1