Next - Js Ebook
Next - Js Ebook
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
written. It appears to be in complete opposition to what was mentioned
earlier” — Are you thinking the same?
If we look at it solely from this perspective, one would certainly feel that
the original language and framework require less code.
Birth 04
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.
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
Next.js — A flexible React Framework. But what does that mean?
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
test your skills:
With Next.js, we won’t have to worry about configuring these tools, thus
investing more time in writing React code.
If you are familiar with React.js, you will discover Next.js is considerably
simpler.
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.
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.
Introduction 10
Improved Performance
Search engine crawlers are like busy visitors to websites. They come
and ask for the content of pages. They explore the links on those pages,
carefully examining and organizing them for ranking purposes. This is
what they do every day. To do their job well, they need to be able to
access the content of the website pages.
On the other hand, Next.js provides the option of Static Site Generation
(SSG) or Server Side Rendering (SSR).
Introduction 11
With SSG or SSR, the server sends the complete HTML file and minimal
JavaScript code to render only the content requiring client-side
interaction. This enables search engine crawlers to access easily and
index every page of the Next.js website accurately.
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
experience, increased trust and credibility, and an advantage over your
competitors because your website shows up higher in search results.
Giving priority to SEO can greatly impact how well your website does
and how many people find it online.
Always Advancing
Next.js, the ever-evolving framework, consistently introduces new
features to simplify developers' lives. With over 7+ versions released last
year, Next.js focuses on innovation and improvement for a better user
experience. This is precisely what frameworks like Next.js aim to achieve,
making development easier and more efficient.
On top of that, other technologies like Expo, used for building React
Native projects, are also adopting Next.js's groundbreaking features.
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
Now is the perfect time to seize the opportunity and prepare for the
With this book and the courses we have done and will continue to do,
So, grab a cup of coffee, and let's get started on this exciting journey!
Chapter 3
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.
These points help you understand the main concepts without focusing
on specific coding details.
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
Basics
Structure
Elements
Semantics
Forms
Fundamentals
Structure
Box Model
Selectors
Typography
Display
Position
Flexbox
Grid
Effects
Transitions
Learn to create smooth transitions using different CSS properties like
Transformations
Explore 2D and 3D transformations like
Animations
Learn how to create animations using keyframes
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,
CSS, and JavaScript, you can immediately build an attractive Sushi
Website by simply following the right free course:
2 Modern JavaScript
ES6 Features
Arrow Functions
In JavaScript, there are different kinds of functions. One type that
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
functions work, it will help you write shorter and more
straightforward functions. This can make your code look cleaner
and easier to read.
Destructuring
A helpful concept that will come in handy when we have to extract
values from arrays and objects
Roadmap 22
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)
Array Methods
Error Handling
3 The Ecosystem
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
Webpack
Babel
4 React JS
Fundamentals
Components
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
Vercel Netlify Firebase Render
Advanced (plus)
CI/CD — Continuous Integration/Continuous Deployment
Docker
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
Database
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 15 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 15:
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
client or server.
Typically, when a user visits a Next.js site, the client sends the request to
HTML, CSS, and JavaScript files, and sends back the fully rendered HTML
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
Have you ever encountered the issue of a hydration error where the
server?
what’s being rendered on the client side, you see that error.
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).
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
With the inline terminal in VSCode, we can perform all necessary tasks
"Terminal" option in the top menu bar. From the dropdown menu, select
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
Let's move on from the theoretical discussion and proceed with the
command that will automatically install the necessary packages for
running a Next.js application.
npx create-next-app@latest
As soon as you press enter, it will prompt you to confirm whether it can
download the required packages. Please select "yes" to proceed with
the installation.
Let's choose not to include TypeScript, ESLint, and Tailwind CSS. In the
upcoming chapters, we will explore these options in detail.
Create a Next.js Application 53
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
default, the favicon will be the Vercel icon. You can replace it with the
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
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
If you write anything in there, it’ll appear on each & every client
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
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 eate a Next.js Application 60
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
Now run,
3000. To see the application in action, open your preferred web browser
and type the URL: http://localhost:3000. If you have followed all the
running as expected:
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
Open the page.js file and delete all the existing code. We'll start fresh
by creating the Home component.
export default function Home() {
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
because of the Fast Refresh feature of Next.js, which automatically
reflects the changes in real time as we edit the code.
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",
differences between the pages directory and the app directory in Next.js
Link to blog
And that, my friends, is where the app directory comes into action. It not
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.
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)
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
Client Vs. Server 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.
First, let’s see what the terminal shows:
Terminal
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.
components.
discuss it in detail in its dedicated section, where we'll dive into the
Before we dive into yet another feature of Next.js, take some time out to
Tasks
Add “use client” inside the app/page.js file and see where the
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,
Next.js, we only need to create two folders named about and contact.
We'll create a special file associated with that route segment inside
I'll name the application routing. Before we begin, let's clean up the
Add the CSS properties for the main tag inside the globals.css file.
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
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
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.,
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.
Create Next App
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
link will take you to the route we created, which is /projects/list.
Create Next App
http://localhost:3000
Routing 101
Simple nest folders within one another and create whatever route you
want. Moving forward, we have,
Dynamic Routes
Think of it as nested routes but with a slight difference. Unlike traditional
nested routes where we need to know the exact route name in advance,
dynamic routes allow for more flexibility.
The route is determined based on changing data in the application, so
we don't need to predict it beforehand.
For instance, if we need to show various project details, we can design a
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
dynamic route of Next.js.
To create a dynamic route, we’ll have to wrap the folder's name in
square brackets, symbolizing that the content inside this square
bracket is variable, i.e., [folder-name].
Continuing our current application, let's add a feature for displaying
project details. Imagine we have three projects named jobit, carrent
and hipnode. We need three routes to showcase these projects:
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 in g 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.”
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
complete sales data and the list of users and products. However, for
while hiding the list of users. All of this should be on the same route.
Rather than complicating the code within a single page with multiple
Intercepting Routes
This feature is handy when displaying a new route while preserving the
information about the product in a modal format, and the URL should
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
We’ll fully dive into these two powerful features when creating an
Tasks
What is the purpose of route groups, and how can they be created
in Next.js?
in web applications?
Chapter 8
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
We have previously discussed terms like "rendering," "runtime, and
"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,
we can definitely do that. In fact, we have already done some best-in-
class Next.js 15 project videos for you to dive right into.
Build and Deploy a Full Stack Build and Deploy a Full Stack
MERN Next.js Threads App... Next.js Application | React...
Watch and Code Now Watch and Code Now
Build and Deploy a Modern Next.js Next.js Full Course 2024 | Build
Application | React, Next JS, Typ... and Deploy a Full Stack App...
Watch and Code Now Watch and Code Now
However, it's important to note that simply watching these videos and
successfully deploying your application might not suffice.
Rendering 116
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 15, 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 & Reduced server load and Performs well on any slower
And if you’re someone who cares about all these points, well, you know
what to choose
The time
Once the compilation process is complete, which involves converting
code from a higher-level programming language to a lower-level
representation (binary code), our application goes through two crucial
phases: Build Time and Run Time.
Build time
It’s a series of steps where we prepare our application code for
production involving the steps of code compilation, bundling,
optimization, etc.
In short, build time or compile time is the time period in which we, the
developer, is compiling the code.
Rendering 119
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
the website by updating only requested pages for regeneration.
With this hybrid strategy, we now have the flexibility to manage content
updates. We can cache the static content as well as revalidate them if
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.
Chapter 9
Data Fetching
This chapter explores data fetching strategies in Next.js. We'll compare
React's traditional hooks with Next.js' React Server Components (RSC)
for efficient API and database interactions. Learn about Next.js' caching
methods and rendering strategies like SSG, SSR, and ISR to enhance
performance and data reliability in your applications.
Data Fetching 126
Data Fetching
Earlier, we explored various rendering environments and strategies,
enabling us to determine the optimal approach for maximizing our
app's performance in different scenarios.
But how do we actually use these strategies in code? It's easy. The hard
part was understanding how these different strategies work.
App.js
function App() {
useEffect(() => {
try {
setData(jsonData);
} catch (error) {
setError(error);
} finally {
setIsLoading(false);
};
fetchData();
}, []);
Data Fetching 127
if (isLoading) {
return <div>Loading...</div>;
if (error) {
return (
<div>
</div>
);
Yep, it's the usual fetch using useEffect, where we call the API when the
component mounts, retrieve the data, store it in the state, and then
display it.
But the same thing, with RSC — React Server Components in Next.js
would look like this,
return (
<div>
</div>
);
For example, if we want to make a call to our database and get a list of
items, we can do this in RSC,
return (
<div>
</div>
);
Function execution contexts are pushed onto the call stack, and
when a function returns, its context is popped off the stack.
Scope Chain: During execution, JavaScript resolves variable and
function references by traversing the scope chain, which includes
the local scope, the outer (enclosing) function scopes, and finally the
global scope.
Garbage Collection: As the code executes, the JavaScript engine
keeps track of objects and variables no longer in use. These are
marked for garbage collection to free up memory.
For the above code, JavaScript will do the same (of course, Next.js &
React.js will act first to execute code to turn this component into vanilla
JavaScript), but where? Any guess?
Of course, you know. On Server!!
By default, any kind of components you’ll write in Next.js are React
Server Components which are guaranteed to run only on Server.
Then how can we write components that run on a client in Next.js?
As easy, okay, I really need to stop doing that.
We do so by adding a flag at the top of that component file, like this,
Data Fetching 131
App.js
'use client';
function App() {
useEffect(() => {
try {
setData(jsonData);
} catch (error) {
setError(error);
} finally {
setIsLoading(false);
};
fetchData();
}, []);
if (isLoading) {
return <div>Loading...</div>;
if (error) {
return (
<div>
</div>
);
1. On Demand
We can explicitly tell Next.js not to cache anything and thus render
content on each request to get fresh data
import React from 'react';
cache: 'no-store',
});
return (
<div>
</div>
);
2. Time based
The whole basis of these rendering strategies is to cache the data
depending on time.
And how do we do that? As simple as… Yes, I know, another analogy. But
it’s really that simple.
Do keep in mind that the fetch we’re using here isn’t the actual
Web API Fetch. It has been extended by Next.js to automatically
cache requests. It’s an extension to the original fetch API.
So if you see someone using fetch in Next.js applications instead of
axios or other, then it’s there for some reason.
But “forever” may not always work (like the real world). Although
Next.js will keep the cache, HTTP cache might decide to get rid of
older stuff eventually to make room for new things.
0: It’s similar to setting revalidate to false. Same effect. It’ll tell Next.js
page or route in its memory (cache) before refreshing it. For example,
page for 5 minutes. After that, it will get a fresh version, save it, and
Think!!
can you now give me an example of how we can do SSR with time-
based validation?
next: { revalidate: 0 },
});
return (
<div>
</div>
);
return (
<div>
</div>
);
return (
<div>
</div>
);
And if we just want to implement ISR only for a particular fetch, we do,
});
return (
<div>
</div>
);
Time to revise what you learned in this chapter. Take a pause and
answer these questions.
Tasks
What are the methods for fetching data in Next.js?
Explain the implementation of SSG, ISR, and SSR in Next.js with
examples for each.
What is the process for data revalidation in Next.js?
Define the distinction between Time-Based and On-Demand
Validation
Explain the difference between these two examples and when we
should use which.
Scenario 1
);
return (
<div>
</div>
);
Scenario 2
return (
<div>
</div>
);
The better you do this, the more your cat (search engine) will show off
Keywords
Keywords are like labels that tell web crawlers what your content is
about. When a user searches for something using these words, the
Content Quality
High-quality content is like a magnet for both users and crawlers. Users
Meta Tags
Think of meta tags as your page's ID card. It tells search engines and
more clicks.
Website Structure
chapters and headings, making it easy for search engines to read and
Site Speed
Faster websites are like express lanes. Search engines love it because
they can quickly check and list your pages. Users love it because they
And that’s what we learned so far throughout this ebook on how using
performance.
Backlinks
yours, it's like saying, "This site is trustworthy." Search engines notice and
Clear URLs
URLs are like street addresses. Clear ones make it easy for search
visitors.
… and a few more. But now let’s see how we can actually implement
There are two ways through which we can add metadata to our website
using Next.js’s Metadata API that decides the look & feel of our website
engines)
But before that, we need to address the difference between static and
Static Metadata
Simply put, it’s information that doesn't change very often, if at all.
This includes things like the page title, meta description, and meta
keywords. Once set, these elements remain the same unless
intentionally updated by a website owner or developer.
It's like writing your name on a label that's stuck on a box - it's there to
stay unless you physically change it.
Dynamic Metadata
As you can guess, it’s information that can change based on various
factors like user interactions, search queries, or other conditions.
This type of metadata is often generated automatically by a website's
content management system (CMS) or scripting languages.
For instance, the meta description might change depending on the
specific search term a user uses or based on the content of the page.
It's like a label that updates itself depending on what's inside the box or
who's looking at it.
1. Config Based
All we have to do is create a javascript object in any layout or page file
and export it. Next.js will automatically detect it and turn it into relevant
meta tags for those routes
layout.tsx | page.tsx
description:
"Gain Real-world Experience And Land That Dev Job You've Always Imagined",
};
The title key within this metadata object will be transformed into the
HTML <title /> tag, while the description will be converted into a
<meta /> tag within the <head /> section of the HTML document.
Output
<!DOCTYPE html>
<html lang="en">
<head>
<title>JS Mastery</title>
</head>
<body>
</body>
</html>
SEO and Metadata 146
Next.js gives us many ways to make our website better for search
engines. It covers everything from setting up metadata for social media
to organizing bookmarks and categories. You can check the complete
metadata fields list here:
Dynamic Metadata
If there are dynamically generated pages, i.e., dynamic routes, that we
want search engines to index—which is a best practice—we can use the
generateMetadata function in Next.js to produce metadata specifically
tailored for these pages.
For the main Resource page, you’ll see different titles and descriptions
and if now you click on one of the resources, you’ll see a change in title
https://jsmastery.pro/resource/1e
Same for other resources. Each has its own title, description, and image,
Okay, but how can we achieve this in Next.js? Achieving this is super
layout.tsx | page.tsx
const { id } = params;
const seoDescription =
return {
title,
description: seoDescription,
other: {
'og:title': title,
'og:description': seoDescription,
'og:image': resource.image,
'twitter:title': title,
'twitter:image': resource.image,
'twitter:description': seoDescription,
},
};
The og: and twitter: fields in metadata are used for social media
optimization (SMO). They provide information to social media
platforms like Facebook and Twitter about how shared links from
your website should be displayed.
og:: These are Open Graph meta tags, which are used by
Facebook and other platforms to understand and display shared
content. Examples include og:title, og:description, and
og:image. These tags help control how your content appears
when shared on social media platforms.
SEO and Metadata 149
Some of you who have taken our Next.js course may have a question:
For example,
> ap
favicon.ic
icon.(ico|jpg|jpeg|png|svg
apple-icon.(jpg|jpeg|png
opengraph-image.(jpg|jpeg|png|gif
twitter-image.(jpg|jpeg|png|gif
opengraph-image.alt.tx
twitter-image.alt.tx
...
SEO and Metadata 151
It’s just about adding files with these names (has to be the same name)
directly inside the app folder. It’ll work out the same as the config-based
approach. You can find the full list of all files that can be created to
define metadata here:
One thing worth noting here is, file based metadata has the higher
priority and will override any config-based metadata. So if you set
metadata in a file, it will be used instead of the same metadata field
you set in the configuration.
So, can you now create proper SEOized applications using Nextjs?
Before we dive into another interesting topic, take your time to
complete these,
Tasks
Explain the concept of search engine optimization (SEO) and its
importance in web development.
Imagine you're hired by an online retailer that uses Next.js for their
website. The company wants to improve its product pages' visibility
in search engine results to drive more organic traffic and increase
sales. How would you approach optimizing the product pages for
SEO, considering factors such as product descriptions, images, and
reviews?
Chapter 11
Backend
In this chapter, we dive into backend development using Next.js,
Backend
Having reached this point, perhaps some of you may have thought, 'Ah,
I've had my fill of Frontend!'
In this chapter, we’ll learn how we can do “back” stuff in the latest
Next.js.
If you've ever tried some backend work, even creating a simple "Hello
World from Server" message requires a fair bit of setup. It involves,
Backend 154
Setting up a projec
});
app.listen(port, () => {
});
Running i
It might not seem like a big deal when you're just reading or looking at
the above code (for first time), but things start getting complicated
when you have to write various routes, middleware, and so on.
In the newest version of Next.js, it's much like what we did on the
frontend — just create a special file within a folder for the specific route,
and you're all set. No need to set up, manage, or monitor an active
server separately.
app/hello-world/route.js
That's all there is to it. Your folder name serves as your API route name,
with your business logic neatly encapsulated within this special route
file.
This might not seem like a big deal if you've never built an API before. In
our masterclass, we often share worksheets demonstrating various
methods for creating backends and explaining the differences between
them. This is to help people understand why we choose Next.js over
Express or when Express might be the better option.
Worksheet Backend
Link to worksheet
Moving ahead,
Backend 156
Nested Routes
As you're aware, your folder name essentially represents a route name.
If you want a route with multiple names (such as a long one), which is
known as a nested route, you can create additional nested folders.
Example,
app
api
users
route.js
Dynamic Routes
Expanding on the nested routes mentioned earlier, and similar to
frontend dynamic routes, we can create dynamic routes like this,
app
api
users
route.js
[userId]
posts
route.js
B k
ac end 157
using req.params.
dynamic segment will be the same name you use to access its
works the same for other scenarios. Any name will do!
that often gets confused with it, and that's none other than URL search/
query parameters
U r nde standing PI P r m r
A a a ete s
1. Query Parameters
Location: S ?
ituated after the in the URL
Example: /api/products?category=electronics
2. Route Parameters
required
Example: /api/users/{userId}
that often gets confused with it, and that's none other than URL search/
query parameters
We define URL query parameters in Next.js by using the router or the Link
We define URL query parameters in Next.js by using the router or the Link
router.push({
pathname: '/products',
});
<Link
3. String Interpolation
Both of the above can then be used with String Interpolation to achieve
similar results of adding Query parameters to the URL
const page = 1;
router.push(`/products?category=${category}&page=${page}`);
<Link href={`/products?category=${category}&page=${page}`}>
</Link>;
That's about how we can include query parameters, which occur on the
frontend side of the application.
But, How do we access them on the backend side, through API routes?
Middleware
In Next.js, middleware works similarly to how it does in other frameworks
(Express.js), though it's a bit different because Next.js is both a server-
side and client-side rendering framework for React.
Middleware in Next.js sits between the incoming request and the route
handler. It's like a series of checkpoints that the request has to pass
through before reaching its final destination (the route handler or the
page).
Right now, while writing this ebook, we’re limited to one middleware per
middleware.js/ts
Even though we're limited to one main middleware file, we can still
organize your middleware logic into separate files. This means we can
For example,
Auth Middleware
lib/authMiddleware.js
console.log('Authentication middleware')
}
Backend 162
Logging Middleware
lib/logMiddleware.js
console.log('Logging middleware')
middleware.js
authenticate(request, () => {
logRequest(request)
})
go through.
implementation isn't supported directly in the app folder for API routes,
Surprise
Cache.
Cache
results even after adding new data through the API, don't worry, and
don't b
lame Next.js. That's just how it operates.
If you would like to disa ble that feature, you can add,
Revalidation
You can also utilize the revalidate option for time-based validation to
determine when you want to revalidate an API route.
Different Runtimes
Another interesting configuration available in Next.js is choosing the
runtime environment. By default, Next.js operates on the Node.js
runtime. However, we can switch to the edge runtime at the route level
like this,
In the following chapter, you’ll learn the difference between these two
run times and when to use each of them.
Tasks
Develop a CRUD API application using Next.js’s app directory.
Explain the concept of middleware chaining in Next.js and provide
strategies for effective management
Backend 165
You'll gain insights into their distinct features, use cases, limitations,
and how to leverage them effectively for optimizing application
performance and user experience.
Node vs Edge Runtime 166
Now it’s time to talk about something interesting, i.e., edge vs. node
runtime.
Rendering
Strategy Environment
Static Dynamic
Server Client
Node Edge
Node Edge Runtime
vs 167
Edge Runtime
Edge runtime is like having a mini-computer close to where you are or
where your devices are. Instead of doing everything on a faraway big
computer, it does some tasks nearby.
This makes things faster, especially for stuff like websites, smart devices,
or anything that needs quick responses. It's like having a helper right
next to you instead of calling someone far away for every little thing.
So, how does edge compare with node.js runtime?
Edge Runtime Node Runtime
distributed locations.
m ementation or example, Vercel's Edge Uses the Node.js
Runtime, is built on the environment, which is widely
I pl F
W eb ssembly engine.
A
W hile there are specific use cases for both, as usual, both have some
limitations.
Node vs Edge Runtime 168
Vercel, who has built its own edge runtime, shares a nice difference
between all these and which features do edge and node support in
Next.js applications:
Node.js Runtimes
Link to docs
Moving on, let’s understand what edge and serverless functions are and
Edge Function
network, closer to the user. It is a smart and quick responder. It does its
job near you, making things faster, especially for applications that need
In Next.js, we can decide the runtime of our choice in any layout, page,
or even route. Switching between runtime is as easy as changing TV
channels with a remote control. Too dreamy, isn’t it?
But that’s 100% true. You get the power of whatever you want to do and
wherever you want to do with Next.js and Vercel powers. You just have
to be a good developer writing better code.
Demo
Now let’s try it out inside code and see how it goes. We’ll create two
simple API routes with and without edge having the same content.
Node Route
app/api/node/route.ts
return NextResponse.json(
{ status: 200 },
);
Edge Route
app/api/edge/route.ts
return NextResponse.json(
{ status: 200 },
);
That’s it. Let’s deploy the application on Vercel to see what happens.
Node vs Edge Runtime 172
runtime
seconds initially. So, they're like speedy helpers, but they can't take
including all the code. It's like having a small backpack—fit what you
Mind the Distance: If your data source is far from where the Edge
Function works, it might take a bit longer. It's like asking a friend to do
something, but they need to travel a bit first. You can tweak settings
to reduce this travel time.
Not All Tricks Allowed: Some cool tricks that regular JavaScript
knows, Edge Functions might not. It's like having a special toolbox;
not all tools are there. You can check a list to see which APIs work for
Edge here
Okay, that’s clear, but then when should we consider using edge over
node runtime?
Latency-Sensitive Task?
Yes
No Yes
No?
Yes No
Use Case
Few use case examples of Edge Runtime
Notifications
Geolocation Services
… and similar other specific use case. Edge functions are also often used
in CDNs to deliver web content like images, videos, and scripts from
servers closer to users. This reduces loading times for websites,
improving the overall user experience. We learned that, don’t we?
That’s it about Edge vs. Node Runtime, Edge vs. Serverless functions,
when to use them, how to use them, and everything else.
Data Fetching 177
Tasks
What are the fundamental differences between edge runtime and
node.js runtime?
Explain the limitations associated with edge runtime as outlined in
the text. How might these limitations impact development
decisions?
In what scenarios might developers prefer node.js runtime over
edge runtime, considering their respective advantages and
limitations?
How can we switch between edge and node.js runtimes in Next.js
applications? What implications does this flexibility offer in terms of
application development?
You are a developer tasked with optimizing the performance of a
real-time notification system for a social media platform.
Server Actions
In this chapter, we dive into the concept of Server Actions in Next.js,
Server Actions
Maybe one of the hot topics of the recent tech world
Have you ever seen this before "use server" in any kind of Next.js
application?
You might had a gut feeling that this is to symbolize whatever is written
inside that file is treated as server things. And you’re absolutely right!
We can use these server actions in both server and client components
which makes them a handy feature to use. While Vercel might be
inclined to showcase the use of this feature for form submissions or
mutations, we can use them to query as well.
Aren’t convinced yet? Let’s see a demo, and we’ll see how useful and
handy they are while building an application.
Server Components
We add a “use server” directive of React inside any function, make it
async, and turn it into a server action
Server Component
function Home() {
// Server Action
'use server'
// ...
return (
// ...
Client Components
The way of using server actions inside client components is a little
different.
Client Components
'use server';
// ...
/// ...
name: '',
email: '',
});
setFormData({
...formData,
[e.target.name]: e.target.value,
});
};
e.preventDefault();
await create(formData)
};
Server Actions 181
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input
type="text"
name="name"
value={formData.name}
onChange={handleChange}
/>
</label>
<br />
<label>
Email:
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
/>
</label>
<br />
<button type="submit">Submit</button>
</form>
);
};
And as you might be wondering — Yes, we don’t need to create any API
to perform any normal CRUD. Server Actions have you covered. Next.js
has made things that simple to do.
But now you might think — How do they work? How are we able to call a
server function right inside a client component?
Any kind of server actions, be that for getting some information, adding
some data to the database, updating or deleting it, Next.js calls our
server through POST request only. But that is for server actions inside
client components only
Demo
function Home() {
'use server';
const data = {
name: event.get('name'),
email: event.get('email'),
};
console.log(data);
return (
<input
type="text"
name="name"
className="p-2 text-zinc-800"
placeholder="Your name"
/>
<input
type="email"
name="email"
className="p-2 text-zinc-800"
placeholder="Your email"
/>
Submit
</button>
</form>
</main>
);
For showing, if a form is submission process or not letting the user keep
clicking on the form button while it’s processing, we can show the form
status and disable the button while a request is being made.
To do that, let’s create another page inside this same application and
see how we can show the form status
We’ll use the same code as we did on the home page, but now we have
to separate the button component from the main form as we’ll have to
turn it into a client component in order to use a specific form hook that
React provides us.
Server Actions 184
useFormStatus - React
Link to docs
function Interactive() {
"use server";
const data = {
name: formData.get("name"),
email: formData.get("email"),
};
console.log(data);
return (
<input
type="text"
name="name"
className="p-2 text-zinc-800"
placeholder="Your name"
/>
<input
type="email"
name="email"
className="p-2 text-zinc-800"
placeholder="Your email"
/>
<Button />
</form>
</main>
);
We can use that hook in our custom Button component like this
'use client';
function Button() {
return (
<button
type="submit"
disabled={pending}
>
</button>
);
useFormState - React
Link to docs
Example
Link to example
Now you might be wondering, can we not use server actions in a client
form? The way we typically build forms using state and everything? Of
course, we can
"use client";
function Page() {
event.preventDefault();
try {
setLoading(true);
setError(null);
const data = {
name: formData.get("name"),
email: formData.get("email"),
};
await submitForm(data);
setError(error);
} finally {
setLoading(false);
return (
<input
type="text"
name="name"
className="p-2 text-zinc-800"
placeholder="Your name"
/>
<input
type ="email
Server "
Actions 188
name="email"
className="p-2 text-zinc-800"
placeholder="Your email"
/>
<button
type="submit"
disabled={loading}
>
</button>
</form>
{error && (
{error.message}
</div>
)}
</main>
);
'use server';
}) {
console.log(data);
}
Server Actions 189
That’s it above server actions. While we may have used small examples
To show you what I mean, let me show you the repository of my Next.js
course. In this course, we cover all the querying and complex mutations.
Link to repository
There had been some concerns all over the internet when Next.js made
a statement that server actions are stable from Next.js 14 and onwards.
People got a bit confused, thinking SQL is now directly inside JSX. Some
even remembered their PHP days and started making fun of it.
As I mentioned earlier, it's not actual code inside the component. Even if
it looks like it, Next.js will turn it into a POST request behind the scenes.
And when it comes to security, you can use anything inside a server
action to check the input first before making the actual DB operations.
Here's an example:
name: z.string().nonempty(),
email: z.string().email(),
});
try {
// check session
if (!session) {
if (!validatedFields.success) {
throw {
errors: validatedFields.error.flatten().fieldErrors,
};
} catch (error) {
}
Server Actions 191
You can add as many security measures as you want to make it safe.
It's in your hands!
Limitations
While server actions might seem cool to try—and they are—there are
some drawbacks too:
Testing might feel challenging with server actions because you can't
use tools like Postman. Testing has to be done directly. On the
positive side, it enhances security since your API isn't exposed
For some, using POST requests for events like updates or deletes may
not align with the best practices of HTTP protocols.
But overall, it's best to use if you want to build and ship applications
faster. That's where they shine—in improving the developer experience.
Chapter 14
Styling
In this chapter, we'll explore various styling strategies available for
Styling
So far we learned some cool core concepts of Next.js. Now coming back
to the frontend again to see how we can make it better using different
styling strategies.
Plain CSS
It's straightforward. You write your CSS rules in separate files just like you
normally would and refer those class/id names in components/
elements
It's straightforward. You write your CSS rules in separate files just like you
normally would and refer those class/id names in components/
elements
styles.css
.container {
max-width: 960px;
margin: 0 auto;
.title {
font-size: 24px;
color: #333;
}
Styling 193
page.js
import './styles.css';
return (
<div className="container">
</div>
);
};
It's straightforward. You write your CSS rules in separate files just like you
normally would and refer those class/id names in components/
elements
styles.scss
$primary-color: #007bff;
.container {
max-width: 960px;
margin: 0 auto;
.title {
font-size: 24px;
color: $primary-color;
page.js
import './styles.scss';
return (
<div className="container">
</div>
);
};
CSS Modules
CSS Modules provide local scoping for styles, which helps prevent style
conflicts between components
page.module.css
.container {
max-width: 960px;
margin: 0 auto;
.title {
font-size: 24px;
color: #333;
page.js
return (
<div className="container">
</div>
);
};
While it’s cool, you need to import styles for each component, which can
be tedious and may clutter your codebase. Additionally, there's a
learning curve for developers unfamiliar with this approach.
Styling 196
TailwindCSS
I can’t recommend this enough. If you want my suggestion for styling, I'd
pick Tailwind CSS every single time. Any day!
While I'd love to outline the steps for setting up Tailwind CSS, it's
evolving. The anticipated v4 of Tailwind CSS is on its way, and it will
bring changes to the setup process we currently use. You can find more
information about it here.
However, just to mention it here, you can refer to this resource to learn
how to set up Tailwind CSS in Next.js.
If you want to learn more about how Tailwind CSS works and why it's
advantageous compared to other options, I highly recommend
watching this crash course.
But you might think — Which is the best option for styling?
The choice between Plain CSS, Sass, CSS Modules, and TailwindCSS for
styling depends on various factors such as project requirements, team
preferences, scalability, and maintainability. Each option has its
advantages and disadvantages:
Styling 197
Plain CSS
Suitable for small projects or when you don't need complex styling
grows.
CSS
CSS Modules
naming collisions
improving encapsulation
TailwindCSS
Utility-first CSS framework that provides a set of pre-defined utility
classes
Might have a steeper learning curve for developers not familiar with
utility-first approaches.
In the end, as I have always said, It’s on you and your needs!
Chapter 15
More of Next.js
In this chapter, we'll explore additional advanced topics and resources
More of Next.js
Up to this point, we've covered the fundamental concepts of Next.js,
including its functionality, usage, and the new architecture it brings to
both the frontend and backend. Now, let's dive into some additional
topics.
Intercepting Routes
Intercepting routes is like redirecting a path in your application. Let's say
you have different pages in your app, like a feed and a photo viewer.
Normally, when you click on something in your feed to see a photo, the
whole page might change to show the photo.
But intercepting routes means you can load just that part of the app
without changing the whole page.
Meaning, instead of taking you to a separate page just for that photo, it
pops up right there in the feed. That's intercepting routes in action. It's
like the app catches that request to see the photo and shows it to you
in a special way, without making you leave the feed.
You can check out the convention next.js suggests for creating
Intercepting routes here.
More of Next.js 200
Parallel Routes
with team info and analytics. Parallel routes let you show these sections
Database
Again, it depends on your needs. What you want to do and how well you
want to d-. Several factors come into play, including the specific
constraints.
Resources
Recently, I was invited to conduct a session on Next.js for GitNation,
where I dive into the complexities of Next.js and its functionality within
the context of RSC. I provided deeper insights into how Next.js operates.
For a more comprehensive understanding, feel free to check it out.
… that may/may not be the end of the list. But for now, it is! Finally
We talked about a lot of stuff regarding Next.js and how it can improve
our application in different aspects. I hope this helps you become a
better Next.js Developer
Happy coding!