NextJS Ebook
NextJS Ebook
The Ultimate
Next.js Ebook
Index 00
Table Of Contents
Chapter 1 Birth 01
Chapter 2 Introduction 07
Chapter 3 Roadmap 15
Chapter 7 Routing 87
Birth
In the first chapter, we explore the evolution of JavaScript and web
Birth
Not too long ago, in 2015, React.js entered the scene. However, even the
journey of JavaScript in the IT industry hasn't been exceptionally long.
Originally developed by Brenden Eich at Netscape in 1995, JavaScript
gained significant popularity during the 2000s.
You might wonder why this information is relevant in the context. The
significance lies in the fact that it highlights the timeless truth that
"change is constant." As we continue to advance and evolve as a
society, our tools and technologies will naturally progress alongside us.
Vanilla JavaScript
document.getElementById('btn')
.addEventListener('click', function () {
alert('Hello, World!');
});
jQuery
$('#btn').click(function () {
alert('Hello, World!');
});
Birth 03
Angular
@Component({
selector: 'app-example',
})
showMessage(): void {
alert("Hello, World!");
React.js
showMessage() {
alert('Hello, World!');
render() {
“Ah? From what I see, there's an increase in the amount of code being
If we look at it solely from this perspective, one would certainly feel that
However, it's important to consider the bigger picture. And that's what
truly matters, doesn't it? In reality, we don't just build "Hello World"
We could have talked about the “big picture” of using React or even
Angular over vanilla code, but that is not the primary focus of this
comparing the previous version of the virtual DOM with the new version.
jQuery. However, even React.js has its own challenges, which have now
Over the course of a year, they continuously added new features such
ability to transform diverse ideas into reality, has caught the attention
achievement!
And that’s how we developers now need to shift our focus to the latest
and greatest version, Next.js 13, to build highly capable and production-
Introduction
In this chapter, we'll dive into Next.js, a flexible React framework. We'll
explore its advantages over React.js, including simplified frontend
development, reduced tooling time, and an easy learning curve. We'll
also discuss how Next.js improves performance, enhances SEO, and
keeps advancing with new features.
Introduction
features and capabilities that we will dive into in the upcoming chapter
in detail.
smooth. If you don’t know React.js, you should familiarize yourself with
To help you learn faster, we have a crash course on React.js that covers
all the important things and includes a project for you to practice and
developing applications.
down the user interface into small pieces of code. You describe states
come in:
With Next.js, we won’t have to worry about configuring these tools, thus
investing more time in writing React code.
The constant updates and help from the community make the
development process even easier.
One of the key aspects of Next.js is that it is not just a Frontend React
Framework but a Full Stack React Framework enabling you to write
backend code alongside your frontend code.
How does it contribute to an "Easy Learning Curve"? Wouldn't it be
another thing to learn?
Absolutely not.
The backend aspect of the code you'll be working with is much simpler
than you might anticipate. There's no need to set up anything or
configure any routes as we have to do for any traditional backend app.
In t rod u ti
c on 10
following viewpoint:
Improved Performance
With SSG or SSR, the server sends the complete HTML file and minimal
SEO is essential for making your website visible and highly ranked in
search engine (browser) results. When you focus on SEO, you get
several benefits, like more people visiting your website, better user
Giving priority to SEO can greatly impact how well your website does
Always Advancing
On top of that, other technologies like Expo, used for building React
Isn’t that great? Master one feature and effortlessly utilize it across
multiple platforms
However, the list of features provided by Next.js goes beyond what has
been mentioned so far.
"Hmm, alright. I'm willing to trust your insights on the new features of
Next.js and such. However, is it actually being used by people? Are
companies actively seeking professionals with Next.js expertise? Is
there a high demand for it in the industry?"
But hey, that’s just a Google trend. What about the industry? Are people
even creating websites using Next.js?
Sure, let’s take a look at “The Next.js Showcase” which shows different
companies using Next.js:
Notio TE Futuris
Hul Auth Material-U
Netflix Job Product Hun Coco Col
Nik Hyunda Ferrar
HBO Ma Porsch Hashnod
Audibl repl.i Verge
Typeform Marvel
Introduction 14
Roadmap
The Roadmap is a concise guide to web development essentials. It
covers HTML for structuring web content, CSS for styling and layout, and
JavaScript for interactivity. Learners will grasp important concepts like
semantic tags, visual effects, variables, control flow, functions, and
manipulating the DOM.
This chapter equips beginners with the skills needed to create dynamic
and interactive web applications.
Roadmap 15
Roadmap
Before we start exploring Next.js, reviewing or relearning some basic
concepts is a good idea to make learning easier. It all begins with
building a solid foundation through fundamentals.
Think of this roadmap as a summary of what you should know as a
foundation for learning Next.js. It's alright if you're unfamiliar with
advanced topics like integrating databases or implementing
authentication.
These points help you understand the main concepts without focusing
on specific coding details.
In Next.js, there are various approaches to implementing these
concepts. You have options like utilizing NextAuth (one of the coolest
features), exploring popular market solutions like Clerk, or even building
everything from scratch.
Similarly, when it comes to databases, you can choose between
different options such as SQL databases like Postgres, NoSQL databases
like MongoDB, or even consider using Prisma as an ORM (Object-
Relational Mapping) manager.
Whether or not you have coding experience is not the most important
factor here. What truly matters is understanding the underlying
concepts. The roadmap is designed to introduce you to these concepts
and familiarize you with the beneficial knowledge when aspiring to
become a Next.js Developer.
Roadmap 16
Later in the next chapters, and with our branded courses, you’ll learn
how to do all the code stuff in Next.js. So don’t worry; you have our back!
These points help you understand the main concepts without focusing
on specific coding details.
Basics
Structure
Elements
Semantics
Forms
Fundamentals
Structure
Box Model
Selectors
Typography
Explore text-related properties like
Display
Learn the various display values like
Position
Explore how to position an element in different ways such as
Flexbox
Master the flexbox layout to create responsive website layouts
Grid
Dive into CSS grid layout for advanced two-dimensional layouts
Roadmap 19
Effects
Transitions
Transformations
Animations
Advanced (Plus)
JavaScript
Operators
Control Flow
Try & test conditional statements such as if else, switch and loops
Functions
DOM Manipulation
block that we use in different ways with tools like React or Next.js in
in vanilla JavaScript and React.js? The basic idea is the same, but
If you're uncertain about how to learn & create a website using HTML,
2 Modern JavaScript
ES6 Features
Arrow Functions
you'll often come across is called the Arrow function. Many prefer
using arrow functions because they are shorter & easier to write.
If you take the time to understand the syntax and how arrow
Destructuring
Spread Syntax
Template Literals
One of the widely used. Using the back sticks ``, we can
interpolate strings with placeholders & expressions
Modules
Asynchronous Programming
Promises
Async/Await
Fetch API
Discover how to use the Fetch API in the browser to send HTTP
requests and handle the resulting responses.
Roadmap 23
Axios (Plus)
Explore the popular third-party library, Axios, which simplifies the
process of making HTTP requests compared to the standard Fetch
API.
Error Handling
One of the crucial part of web development is to catch and
display the errors properly. No user will like to see the complete
red screen with a text — “Error on line 35”. Not even us.
3 The Ecosystem
Before we proceed learning the libraries and frameworks like
React.js and Next.js, we’ll need some kind of config to setup these
projects:
Foundations
Node.js
A tool that manages third party packages. Using it, you can
download different packages needed inside you project like Axios
Webpack
Babel
4 React JS
From here, you’re efficiently learning Next.js. The same concepts
are as it is used in the Next.
Fundamentals
Components
Think in terms of components. Learn to break the code or the UI in
small manageable components for reusability & maintainability
There are two ways in which we can create a component i.e.,
Class Componen
Function Component — Widely used
State
Learn how to create and manage state — A small store that holds
a particular data of the application
Props
Events
Conditional Rendering
P.S., Don’t forget to learn about the special “Key” prop when rendering
the dynamic list with map method.
Roadmap 27
Hooks
Router
State Management
Style
Explore different approaches to styling React components,
including
styled-components Emotion
Forms
Learn to create form validation, handling form submission with or
without using third party libraries like,
HTTP Requests
Learn how to make requests using libraries like Axios or the built-in
Fetch API
If you want to enhance your skills in state management using tools like
Redux Toolkit, you can explore our professional-level course:
5 Backend
Although it’s not a must to know how to do the backend to
become a Next.js developer, it’ll be nice to have the skill to
showcase the ability to do both and become a full-stack Next.js
developer.
Basics
HTTP Protocol
APIs
Learn what is Application Programming Interface (API)
REST
Learn what is Representational State Transfer
HTTP Methods
Status Code
200 — ok
201 — created
HTTP Headers
Request and Response
Resource URI
CRUD
Understand the concept of CRUD operations
User Sessions
JWT — JSON Web Token
Cookies
Permissions and Roles
Database
Relational Database
MySQL
PostgreSQL
NoSQL Database
MongoDB
Redis
Deployment
Environments
Production
Development
Staging
Roadmap 33
Hosting Platforms
Advanced (plus)
Docker
YouTube
If you want to enhance your skills in state management using tools like
Redux Toolkit, you can explore our professional-level course:
And now, at last, we will dive into the Next.js roadmap. It may not be
necessary, as the content of this book is organized in a manner where
each chapter serves as a guiding milestone, and it’s the only resource
you need (alongside some Build and Deploy courses, of course) to
master Next.js!
6 The Next.js
Fundamentals
Architecture
Understand the architecture of a Next.js application including
different files and directories i.e., app directory vs pages directory.
Client Server
Style
Next.js has built-in support for CSS processors like Sass to CSS
modules. Try different types of styling with Next.js to find the one
that best fits your application:
Data Fetching
You have the flexibility to choose between different types of
rendering and data fetching methods for your application. These
methods include:
Authentication
Implementing custom email/password or social authentication
becomes hassle-free with NextAuth in Next.js. Few auth libraries
you can use with Next.js to speed up the development process:
NextAuth Clerk
API routes
Explore how to create API routes — the backend:
Route Handlers
Create custom request handlers
Static Route Handlers Dynamic Route Handlers
Middleware
Supported HTTP Methods
NextResponse
Database
Discover how to incorporate various types of databases into your
Next.js application by utilizing API routes.
If you're someone who prefers video content over reading, you'll find our
best and most up-to-date Crash Course on Next.js 13 on YouTube very
enjoyable. This course not only covers the fundamentals of Next.js but
also guides you in building a Full Stack project with authentication,
utilizing the latest features of Next.js 13:
Keep in mind that real progress happens when you actively do coding.
So, grab coffee, find a quiet spot, and start coding to make things
happen.
Chapter 4
How it works
In this chapter, we lay the foundation by understanding how the web
works before diving into Next.js code. We explore the traditional
approach of HTML, CSS, and JavaScript websites, where the server
sends complete files to the client for each page request.
We also introduce the React way, where the server sends a minimal
HTML file and a bundled JavaScript file, and React manipulates the
virtual DOM for efficient rendering. Finally, we discuss the Next.js way.
How it works 40
How it works
You might be itching to start with Next.js code, right?
If your why isn’t clear, you’ll have no idea what you’re doing, and you’ll
blame it on Next.js by saying that it’s an overrated piece of technology.
That will only showcase your lack of knowledge. It's a foolproof recipe to
amaze everyone with your impressive ignorance.
So, perfect your why and your how will come naturally.
Let’s time-travel a bit to see how things were used to work with
different technologies.
Request
three files i.e., the HTML, CSS, and JavaScript (only if any JavaScript code
analyzing the HTML file. Then, it applies the styles from the CSS file and
The client will send additional requests to the server if the website has
multiple pages. In response, the server will send the three files
However, if the website is complex and the user's device needs more
capabilities, it can strain the browser and create a burden for it to
handle.
Bandwidth
As the server sends complete files to the client for each page request, it
increases bandwidth usage. This becomes particularly significant when
dealing with complex websites containing numerous pages and video
and audio clips scattered throughout the site.
Load Time
The initial page load time may be longer when compared to the latest
technologies. This is due to the complete transfer of files for each
request. Only after the server has sent all the necessary files and the
browser has finished parsing everything will we be able to view the
website's content.
How it works 43
When you access a React website, the client's browser sends a request
to the server for the webpage content. In response, the server sends a
minimal HTML file, which serves as the entry point for the entire
application, along with a bundled JavaScript file.
Processing
Similar to the traditional approach, react primarily performs client-side
rendering. It heavily relies on JavaScript for initial rendering and
subsequent requests to update the user interface, which are all handled
on the client’s browser.
SEO
Yes, if you recall, we previously touched upon a notable drawback of
React compared to Next.js in the Introduction chapter.
The issue is that search engine crawlers might need help fully
accessing the website's content since everything is handled through
JavaScript and only rendered on the client side. As a result, it impacts
the website’s visibility in search engine results
How it works 45
Typically, when a user visits a Next.js site, the client sends the request to
the server, which starts executing the React Components, generates
HTML, CSS, and JavaScript files, and sends back the fully rendered HTML
to the client as a response. This file includes initial content, fetched
data, and React component markup, making the client render it
immediately without waiting for JavaScript to download and execute.
But it doesn’t mean we don’t receive any JavaScript files. The server will
still send the JavaScript code as needed for the user interaction. From
here, Next.js takes over and performs client-side hydration
Have you ever encountered the issue of a hydration error where the
user interface doesn't match what was originally rendered on the
server?
For subsequent requests, you have full control over where to render
your page content i.e., either on the server side (SSR) or the client side
(CSR).
In the following chapters, we’ll talk in-depth about different types of
server-side rendering along with client-side rendering and when and
where to render what.
Chapter 5
Create a Next.js
Application
In this chapter, you will learn how to create a Next.js application. You'll
start by setting up the necessary tools like Node.js and Visual Studio
Code. Then, you'll create a new Next.js project using the create-next-
app command.
If you haven't installed Node.js before, you can visit this link and start
downloading it. The website will give you two options based on your
operating system: LTS and Current. The LTS (Long Term Support) version
is the most stable, while the Current version is like a "Work in Progress"
that adds new features but may have some bugs.
node - v
Create a Next.js Application 48
node -v
18.16.1
After downloading Node.js and VSCode, let's set up your first Next.js
application.
Go to the desired location where you want to create your project. It can
be any location, but it's advisable to maintain an organized structure.
Create a new folder inside that location and name it "NextEbook." If you
prefer a different name, feel free to choose one. This folder will hold all
the code we will cover in this ebook.
Now, let's proceed with the following steps to open the folder we just
created in our chosen code editor, which is VSCode:
Launch VSCode
Click on the "File" option in the top menu bar
From the dropdown menu, choose "Open Folder.
Browse to the location where you created the "NextEbook" folder
Select the "NextEbook" folder
Click on the "Open" button.
Create a Next.js Application 50
Following these steps, you can view your "NextEbook" folder in VSCode.
VSCode provides its own built-in terminal, eliminating the need for
developers to open the OS Terminal or Command Prompt separately.
With the inline terminal in VSCode, we can perform all necessary tasks
within the application.
To open the terminal, press ctrl + `(backtick) or click on the
"Terminal" option in the top menu bar. From the dropdown menu, select
"New Terminal." The terminal window will appear as follows:
For the final, let’s now create our Next.js application. There are two
options:
Automatic Installatio
Manual Installation
Create a Next.js Application 51
our own.
opting for other options, we can set up the complete project with just
one click.
Interface) tool — create-next-app. You can visit this link if you want to
know about this in detail. Inside, you’ll see how the create-next-app has
When you installed Node.js, you also got two other useful tools:
NPM NPX
run our application. For example, packages like Axios for making HTTP
globally on our system. It's important to note that npx is used to run
Let's move on from the theoretical discussion and proceed with the
npx create-next-app@latest
As soon as you press enter, it will prompt you to confirm whether it can
the installation.
Let's choose not to include TypeScript, ESLint, and Tailwind CSS. In the
If you see the installation process carefully, you’ll see “Using npm.”
npx is used solely to execute commands from packages, while npm
handles the installation of those packages.
And there you have it! The Next.js application has been successfully
installed
Now, let's explore what's inside. Click on the "introduction" folder or the
name you chose for your project. Inside, you will find several files and
folders.
App
It’s the root of the application, where we'll create various client
(frontend) routes and potentially write backend code. Initially, you'll find
some starter files in this location, including:
Create a Next.js Application 54
favicon.ico
It represents the website's favicon displayed in the browser's tab. By
default, the favicon will be the Vercel icon. You can replace it with the
one you like.
globals.css
This file holds the CSS code for the application. It is a global file where
you can define CSS variables, import fonts, or perform other CSS
initialization tasks.
You can keep the file, rename it, or even move it to a different location. It
doesn't matter. However, if you make any changes to this file, you must
update any other parts of the application that rely on it.
Create a Next.js Application 55
global.css
:root {
--max-width: 1100px;
--border-radius: 12px;
--foreground-rgb: 0, 0, 0;
--primary-glow: conic-gradient(
#16abff33 0deg,
#0885ff33 55deg,
#54d6ff33 120deg,
#0071ff33 160deg,
transparent 360deg
);
--secondary-glow: radial-gradient(
);............
layout.js
It’s the main entry point of the application. The root. The parent. The
layout. Whatever you prefer to call it.
If you write anything in there, it’ll appear on each & every client
(frontend) route. It’s universal.
If you need to import fonts, add metadata, wrap the application with
Redux, or show a Navbar, this is the place to do it. All these tasks can be
performed within this file.
Create a Next.js Application 56
page.js
It’s an alias of the home route i.e., “/”. It's important not to confuse this
file with layout.js. Whatever you write inside page.js will be displayed
only on the "/" route, while anything inside layout.js will appear across all
routes, including the home route i.e., “/”.
page.module.css
If you closely examine the code, you will notice the presence of the
following:
Node Modules
No need to worry, though. You don't have to interact with or visit this
directory in the future (unless something terrible happens). npm
automatically manages the node_modules folder when we install or
uninstall node packages.
Public
.gitignore
The .gitignore is a special text file that tells Git, the version control
system, to exclude certain files and directories from being tracked.
jsconfig.json
Remember the prompt that appeared when we ran the Next.js CLI tool?
It asked us if we wanted to customize the default import alias, and we
chose "No".
Create a Next.js Application 59
By default, when we want to import code from one file into another, we
use relative paths like this:
This is the correct, but sometimes long and complex, relative path.
"compilerOptions": {
"paths": {
"@/*": ["./*"]
}
Cr ea t e a N xt
e .js A i
ppl ca ti on 60
i.e., using @/* for any files and folders located in this location ./* i.e., the
root!
Feel free to customize the alias to your preference. You can change @/*
package-lock.json
Well, let me tell you, it's actually quite important. This file, called
dependencies.
completing your work, you share the project code with your manager,
but you omit the package-lock.json file, thinking it's not essential.
packages and their dependencies ( i.e., the folder and files we have
Think of this as an info card that tells about you — who you are, where
you are from, etc. but with more complete details.
This way, the package.json file records all the packages required for
the project, making it easier to manage and reproduce the
development and production environments accurately.
Other than that, we can see another part i.e., “scripts”. It contains
executable commands or scripts using npm. We can completely
customize it. Through these commands/scripts, we run tests, build a
project, start a development server, or deploy the application.
README.md
Having a good README helps people understand what our project is all
about and how they can use it or get involved. It's like giving them
directions or instructions on how to make the most of our project.
Now, let's finally run our application. We need to execute one of the
commands from the "scripts" section we just mentioned, specifically the
"dev" command.
cd introduction
Create a Next.js Application 63
The "cd" command, which stands for "change directory," will navigate us
inside the "introduction" folder.
Now run,
http://localhost:3000
Phew, a lot of explaining just to cover the initial file and folder structure.
But it’s of no use if we don’t take any actions. Let’s change few things
from the repo to see how it works.
Create a Next.js Application 64
Open the page.js file and delete all the existing code. We'll start fresh
return (
<main>
</man>
)}
After making the changes, save the file and return to your browser. If
you visit the localhost again, you should see the updated content of
"Hello World " without manually refreshing the page. This is possible
Now, open the layout.js file and add text inside the body tag:
import './globals.css';
};
return (
<html lang="en">
<body className={inter.className}>
{children}
</body>
</html>
);
}
Create a Next.js Application 65
{children}
</body>
Create a Next.js Application 66
<body className={inter.className}>
{children}
</body>
the application, starting from the home route and extending to any
return (
<html lang="en">
<body className={inter.className}>
{children}
</body>
</html>
Clear enough?
Amazing! Before you rush to start the next chapter, I have a few tasks for
you to complete:
Create a Next.js Application 67
Tasks
Comment down the {children} inside the RootLayout and see if you
can still see the “Hello World ”
import './globals.css'
return (
<html lang="en">
<body className={inter.className}>
</body>
</html>
side rendering to get the best of both worlds. But we need to find out
which parts of the application are rendered on the server side. Can we
mean?
Client
The client refers to the device you are currently using, such as your
Server
all the code for our application is stored. When the client, our device,
pages. This meant that only the route pages like "/", "/about", "/projects",
And that, my friends, is where the app directory comes into action. It not
only introduced many features but also brought about a revolutionary
change, i.e., — Component level Server Side Rendering.
And as discussed above, we’ll overcome our limitations with the pages
directory. Rather than fetching and passing data to components
separately, we can fetch the data directly within the component,
turning it into a server component.
Smaller JavaScript bundle size: The size of the JavaScript code that
needs to be downloaded by the browser is reduced.
Client Vs. Server 71
Faster initial page load for better accessibility and user experience:
Users can see the content more quickly, leading to a smoother
browsing experience.
Ask yourself:
Server
Client
Fetch data.
client-side JavaScript
onChange(), etc)
us R du r
e e ce (), us Eff t
e ec (), etc)
U se browser-only APIs
browser-only APIs
Well, it's as simple as writing "use client" at the top of the component
file. It's a straightforward and slick way to indicate that the component
should be treated as a client component.
cd ..
Now go to the app folder, then to the page.js file, and delete all other
app/page.js
console.log("Where do I render?")
return (
<main className={styles.main}>
<h2>Welcome </h2>
</main>
If you prefer, you can delete everything else from the page.module.css
file and keep the styles only for the main tag of HTML.
app/page.module.css
.main {
display: flex;
flex-direction: column;
align-items: center;
padding: 6rem;
min-height: 100vh;
After adding a console log in our page.js file, let's open our web browser
to see if it appears there:
Client Vs. Server 75
http://localhost:3000
The terminal! Let's return to our terminal and check if the mentioned log
Terminal
Now let’s create two more components for each Client and Server.
Inside the root of the folder, i.e., outside of the app folder, create a new
folder and name it components. Create two new files inside it,
ExampleClient.jsx and ExampleServer.jsx.
components/ExampleClient.jsx
"use client";
return (
<div>
</div>
);
};
components/ExampleServer.jsx
return (
<div>
</div>
);
};
Now, first import & use the ExampleClient component inside the app/
page.js file:
app/page.js
console.log("Where do I render?")
return (
<main className={styles.main}>
<h2>Welcome </h2>
<ExampleClient />
</main>
}
Client Vs. Server 78
Let’s play around with these components a little more. Now, import the
ExampleServer component inside the app/page.js file
Client Vs. Server 80
app/page.js
console.log("Where do I render?")
return (
<main className={styles.main}>
<h2>Welcome </h2>
<ExampleClient />
<ExampleServer />
</main>
And now, if we visit the browser, along with showing both client-server
component text on the website, it’ll only show the “I'm Client Component
:)” log inside the browser’s console:
http://localhost:3000
C lien t V s. S er v er 81
Whereas the terminal will show all the three console logs
Terminal
All good!
For the final play, let’s remove the ExampleServer from app/page.js
and add it inside the components/ExampleClient.js
app/page.js
console.log("Where do I render?")
return (
<main className={styles.main}>
<h2>Welcome </h2>
<ExampleClient />
</main>
}
Client Vs. Server 82
components/ExampleClient.jsx
"use client";
return (
<>
<div>
</div>
<ExampleServer />
</>
);
};
Hit save and see the result in both the Terminal and Browser console.
Terminal
- next dev
Where do I render?
http://localhost:3000
Consider "use client" as a dividing line between the server and client
code. Once you set this boundary, everything inside it becomes client
code.
Before we dive into yet another feature of Next.js, take some time out to
work on the below tasks to solidify your learning so far:
Tasks
Add “use client” inside the app/page.js file and see where the
console logs are appearing:
app/page.js
"use client"
console.log("Where do I render?")
return (
<main className={styles.main}>
<h2>Welcome </h2>
<ExampleClient />
</main>
}
Client Vs. Server 85
What are the latest features of the app directory regarding the
client/server rendering?
Chapter 7
Routing
In this chapter, you'll learn about routing in Next.js and how it simplifies
the process compared to React.js. Next.js uses a file-based router
system, where folders and files define routes and UI components,
respectively.
Routing
Now, let’s dive into routing!
One of Next.js’s cool features is its ability to handle routes out of the box.
But before we jump into that, let's first understand how routes are
created in React.js.
App.js
return (
<Router>
<Routes>
</Routes>
</Router>
);
};
App.js
function App() {
return (
<Router>
<Fragment>
<Routes>
</Route>
</Route>
</Route>
</Routes>
</Fragment>
</Router>
);
Scary, isn’t it? Not only do we need to download and handle an external
package, but as our application gets bigger, the routing becomes more
complicated, making it harder to manage and understand!
Routing 89
Now, let's explore what Next.js brings to the table for routing
Meaning,
I'll name the application routing. Before we begin, let's clean up the
existing code to make it more organized and easier to understand for
this use case:
app/globals.css
main {
padding: 2rem;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
Remove the code inside app/page.js and keep only the main & h1 tag
app/page.js
return (
<main>
<h1>Home</h1>
</main>
Navbar.jsx — contains a simple navbar with few links. We’re using the
Link component of next/link to navigate between the different routes
of the application by providing the appropriate route path to the href.
Routing 91
components/Navbar.jsx
return (
<header>
<nav className={styles.nav}>
<p>Next.js</p>
<ul className={styles.links}>
<Link href="/">
<li>Home </li>
</Link>
<Link href="/about">
<li>About </li>
</Link>
<Link href="/contact">
<li>Contact </li>
</Link>
</ul>
</nav>
</header>
);
};
And create the corresponding style modules for the same i.e.,
navbar.module.css
Routing 92
components/navbar.module.css
.nav {
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
.links {
flex: 1;
list-style: none;
display: flex;
justify-content: end;
align-items: center;
gap: 2rem;
.links li {
white-space: nowrap;
cursor: pointer;
.links li:hover,
.links li:active {
color: #0099ff;
Nothing too complex. To ensure that the navbar appears on all route
pages, we have two options:
Routing 93
page
Wrong Method
app/page.js
return (
<main>
<Navbar />
<h1>Home</h1>
</main>
app/about/page.js
return (
<main>
<Navbar />
<h1>About</h1>
</main>
}
Routing 94
Right Method
app/layout.js
import './globals.css'
return (
<html lang="en">
<body className={inter.className}>
<Navbar />
{children}
</body>
</html>
By now, if you have followed all the steps properly, you should see this
inside your browser:
Routing 95
http://localhost:3000
Note: Please follow the Kebab Case writing convention when writing
route names.
After creating the folder with the name about, create the special UI file
page.js inside it to show the UI for that route:
app/about/page.js
return (
<main>
<h1>Home</h1>
</main>
}
Routing 96
App
About
page.js
Contact
page.js
page.js
Well, that’s it! Go to your browser and click the "About " link in the
Navbar. You will notice that the URL changes, and the text displayed on
the page switch from "Home" to "About"!
Routing 97
http://localhost:3000
Go ahead and create the route for “Contact ” in the same way, i.e.,
Add the necessary code to the page.js file to display the desired
text.
app/contact/page.js
return (
<main>
<h1>Contact</h1>
</main>
}
Routing 98
After saving the changes, return to the browser. You will notice that the
modifications are immediately visible without reloading the page, all
thanks to Next.js' Fast Refresh feature.
http://localhost:3000
Routing 99
That was all about creating a simple route in Next.js. But what about
Nested Routes
this, we create two folders: projects and within it another folder called
list. Inside the list folder, we add the page.js file containing the user
app/projects/list/page.js
return (
<main>
<p>ProjectsList</p>
</main>
}
Routing 100
app/projects/list/page.js
return (
<main>
<h1>Home</h1>
<Link href="/projects/list">
See Projects
</Link>
</main>
Now visit the home page, and you’ll see See Projects; clicking on this
http://localhost:3000
Routing 101
Simple nest folders within one another and create whatever route you
Dynamic Routes
nested routes where we need to know the exact route name in advance,
single details page with a consistent layout for all projects. The only
difference will be some data that changes for each project. Instead of
making separate routes for every project detail page, we can use a
We could create these as nested routes, but there are better ways.
Routing 102
Within the existing projects folder, create a new folder with a name
enclosed in square brackets, i.e., app/project/[slug]. I referred to it as
slug to address the segment in general, but you can choose any name
you prefer, like id or name. Additionally, create the corresponding
special UI file, page.js, in the same location folder.
app/projects/[slug]/page.js
return (
<main>
<h1>Project Name</h1>
</main>
}
Routing 103
app/projects/list/page.js
return (
<main>
<h1>My Projects</h1>
<ul className={styles.ul}>
<li>
<Link href='/projects/jobit'>
JobIt
</Link>
</li>
<li>
<Link href="/projects/carrent">
Car Rent
</Link>
</li>
<li>
<Link href="/projects/hipnode">
hipnode
</Link>
</li>
</ul>
</main>
app/projects/list/projects.module.css
.ul {
margin-top: 2rem;
list-style: none;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
gap: 1rem;
width: 100%;
.ul li {
padding: 1rem;
width: 100%;
max-width: 300px;
border-radius: 10px;
text-align: center;
cursor: pointer;
Is there anything else? Nope, that's all there is to it. Simply click on these
project names and witness it in action!
Create Next App
http://localhost:3000
However, something doesn’t feel good. While the route for these
projects changes correctly, it would be great to see the actual project
name displayed on the respective route pages instead of the static
"Project Name." So, how to do that?
The [slug] part over here is our dynamic route segment. And Next.js
provides a way to access what value has been passed to it via the
params prop passed to page.js page.
To utilize the value of this dynamic segment, we need to do this:
Rout ing 106
app/projects/[slug]/page.js
return (
<main>
<h1>Project {params.slug}</h1>
</main>
But that’s not the end of the routing in Next.js. Coming next are,
Route Groups
address this and offer better control over folder organization without
"Route Groups.”
:
Consider the existing structure we already have three folders a : bout,
contact, and projects.
Routing 107
What if we could limit the number of folders inside the app folder to a
maximum of 1-3 and include everything within these folders while
maintaining the same route path?
In this case, if we create these folders, i.e., auth and, let's say, dashboard,
right away and add the corresponding folders & pages inside them, it
will impact our routing. Why? Because, as we've learned, each folder
name serves as a route name.
app
auth
sign-in
page.js
sign-up
page.js
Routing 108
If we do it like the above, the route name for the sign-in page would be
/auth/sign-in, and similarly, for the sign-up page, it would be /auth/
sign-up.
In this case, if we create these folders, i.e., auth and, let's say, dashboard,
right away and add the corresponding folders & pages inside them, it
will impact our routing. Why? Because, as we've learned, each folder
name serves as a route name.
(auth)
Create the (auth) folder inside the app folder and add routes for the
sign-in and sign-up pages. Additionally, create a page.js file within
each of these folders to display the respective UI:
Sign I
Sign Up
Routing 109
Sign In
app/(auth)/sign-in/page.js
return (
<main>
<h1>Sign In</h1>
</main>
Sign Up
app/(auth)/sign-up/page.js
return (
<main>
<h1>Sign Up</h1>
</main>
Next, let's transfer the remaining folders, namely about, contact, and
projects, into our (dashboard) route group.
(dashboard)
Create a folder named (dashboard) within the (app) folder and simply
move the previously created folders (about, contact, and projects)
into it as they are.
app
(auth)
(dashboard)
about
page.js
contact
page.js
projects
[slug]
page.js
list
page.js
http://localhost:3000
There are two more amazing client-side routing features, i.e., Parallel
Routes and Intercepting Routes. Not to forget, we also have API routes
Parallel Routes
This feature allows us to display one or more pages simultaneously or
conditionally within the same layout.
Rather than complicating the code within a single page with multiple
conditions, we can utilize parallel routes that render based on whether
the user is an admin or not.
Intercepting Routes
This feature is handy when displaying a new route while preserving the
current page's context. It allows us to intercept a new route without fully
transitioning from the current layout.
We can utilize this feature to display the content inside the modal on
top of the page from which it was triggered while also updating the URL
to reflect the product previewed.
We’ll fully dive into these two powerful features when creating an
application in the upcoming advanced routing chapter.
Tasks
Create a complete routing structure for an e-commerce project
using different routes. Here are the expected routes:
What is the purpose of route groups, and how can they be created
in Next.js?
Rendering
In this chapter, you'll learn about rendering in Next.js and gain a deep
understanding of key concepts, strategies, and environments. You'll
discover how Next.js handles rendering, the different rendering
strategies it offers, and when to use each one.
Rendering 115
Rendering
"environment," but what do they truly mean, and how does Next.js fit into
the picture?
You might be thinking, "Enough with the theory, show me the code!" Well,
Build and Deploy a Full Stack Build and Deploy a Full Stack
Build and Deploy a Modern Next.js Next.js 13 Full Course 2023 | Build
However, it's important to note that simply watching these videos and
When you eventually venture into your own projects, you might stumble
So always aim to clear your “Why” and sit back to watch yourself
In Next.js 13, there are different ways things are displayed (strategies),
the specific times they run (runtime/build time), and the specific places
Rendering
It’s a process of generating or creating the user interface from the code
Next.js!
Environments
There are two environments where we can render our application code,
i.e., the client (User’s browser) and server (Computer where we deploy
our code).
Rendering 117
Client Server
load time
sharing previews
Load & Reduced server load and Performs well on any slower
f
Per ormance potentially lower hosting device as rendering is done
the rendering.
issues
vulnerabilities
specifications are not a priority for you, and your focus is primarily on
and known, eliminating the need to prioritize SEO since the product is
not intended for a wide public audience. This allows you to prioritize
And if you’re someone who cares about all these points, well, you know
what to choose
The time
Build time
optimization, etc.
In short, build time or compile time is the time period in which we, the
Run Time
In short, run time is the time period when a user is running our
application’s piece of code.
It’s a JavaScript Run Time Environment that allows us, developers, to run
Default runtime that has access to all Node.js APIs and the ecosystem
Next.js offers the flexibility of choosing the runtime. You can do switch
ecosystem emerges. It's like the snap of Thanos's fingers, and suddenly,
Rendering Strategies
environment, and the time period, i.e., build and run time, Next.js
Remember the build time? Well, the famous SSG, static site generation,
During the build process, the content is generated and converted into
requests leading to fast content delivery and less server load. This
time!
websites. All the articles or content are static 90% of the time. It doesn’t
This reduces the build time and improves the overall performance of
With this hybrid strategy, we now have the flexibility to manage content
needed.
An example use case would be the same where we can use SSG for the
article details page and use ISG for showing a list of articles
Yes No?
Yes No
The how of all this is following in the next chapter, so keep reading. But
before you go, as usual, pause and try to answer these questions:
Rendering 125
Tasks
What does rendering mean? Explain different rendering
strategies of Next.js
What is build time and run time? Explain the difference between
them in a Web application life
What are the benefits of rendering content in a Client vs Server
environment?
Imagine, you are developing a large-scale e-commerce
platform that requires a rendering strategy to handle a high
volume of product listings. The platform needs to display
product information, pricing, availability, and customer reviews.
Additionally, the platform aims to provide a fast and interactive
user experience.
Considering the complex requirements of the e-commerce
platform, discuss the trade-offs and factors you would consider
when choosing between Static Site Generation (SSG) and Server
Side Rendering (SSR) as the primary rendering strategy.
Client Vs. Server 126
We're just scratching the surface. Stay tuned for the next update as we
release more chapters that unlock the full potential of Next.js 13.
Give yourself a pat on the back for completing all the chapters thus far.
We would greatly appreciate hearing your suggestions or feedback.
Feel free to provide your honest input through this link.
With your feedback and collaboration, we will bring you the best version
of Next.js in the coming weeks. Thank you!