Next.js 15

What is Next.js ?

Next.js is a React-based framework designed for creating

full-stack web applications.

What is Next.js ?

Next.js is a React-based framework designed for creating

full-stack web applications.

React.js

It's challenging to develop a fully-functional application that is ready for production.

What is Next.js ?

Next.js is a React-based framework designed for creating

full-stack web applications.

React.js

It's challenging to develop a fully-functional application that is ready for production.

React is a library designed specifically for creating

user interfaces.

What is Next.js ?

Next.js is a React-based framework designed for creating

full-stack web applications.

React.js

It's challenging to develop a fully-functional application that is ready for production.

React is a library designed specifically for creating

user interfaces.

For routing, data fetching etc.. you have to install

other libraries

What is Next.js ?

Next.js

Next.js uses React for building user interfaces.

Next.js has additional tools that allow you to build applications that are ready

for production.

What is Next.js ?

Next.js

Next.js uses React for building user interfaces.

Next.js has additional tools that allow you to build applications that are ready

for production.

Routing, Optimized Rendering, Data Fetchihg, Bundling, Compiling and more

What is Next.js ?

Next.js

Next.js uses React for building user interfaces.

Next.js has additional tools that allow you to build applications that are ready

for production.

Routing, Optimized Rendering, Data Fetchihg, Bundling, Compiling and more

We do not have to install any additional packages for that.

What is Next.js ?

Next.js

Next.js uses React for building user interfaces.

Next.js has additional tools that allow you to build applications that are ready

for production.

Routing, Optimized Rendering, Data Fetchihg, Bundling, Compiling and more

We do not have to install any additional packages for that.

To achieve these features you have to follow convention

Why learn Next.js ?

Why learn Next.js ?

Next.js makes it easier to build production-ready web applications.

1. Routing

Why learn Next.js ?

Next.js makes it easier to build production-ready web applications.

1. Routing

2. API Routing

Why learn Next.js ?

Next.js makes it easier to build production-ready web applications.

1. Routing

2. API Routing

3. Rendering

Why learn Next.js ?

Next.js makes it easier to build production-ready web applications.

1. Routing

2. API Routing

3. Rendering

4. Data Fetching

Why learn Next.js ?

Next.js makes it easier to build production-ready web applications.

1. Routing

2. API Routing

3. Rendering

4. Data Fetching

5. Styling

Why learn Next.js ?

Next.js makes it easier to build production-ready web applications.

1. Routing

2. API Routing

3. Rendering

4. Data Fetching

5. Styling

5. Optimization

Why learn Next.js ?

Next.js makes it easier to build production-ready web applications.

1. Routing

2. API Routing

3. Rendering

4. Data Fetching

5. Styling

5. Optimization

5. Dev and prod build system

Why learn Next.js ?

Next.js makes it easier to build production-ready web applications.

1. Routing

2. API Routing

3. Rendering

4. Data Fetching

5. Styling

5. Optimization

5. Dev and prod build system

What You Need Before Getting Started ?

What You Need Before Getting Started ?

HTML

What You Need Before Getting Started ?

HTML

CSS

What You Need Before Getting Started ?

HTML

CSS

JavaScript

What You Need Before Getting Started ?

HTML

CSS

JavaScript

React.js Fundamentals

What You Need Before Getting Started ?

HTML

CSS

JavaScript

React.js Fundamentals

React Server Component (RSC)

React Server Component (RSC)

React Team introduced a new architecture called React Server Component (RSC) and Next.js quickly adopted it. 

React Server Component (RSC)

React Team introduced a new architecture called React Server Component (RSC) and Next.js quickly adopted it. 

This architecture offers a fresh way of building React components by categorizing them into two distinct types.

React Server Component (RSC)

React Team introduced a new architecture called React Server Component (RSC) and Next.js quickly adopted it. 

This architecture offers a fresh way of building React components by categorizing them into two distinct types.

2. Client Component

1. Server Component

React Server Component (RSC)

Server Component

By default, Next.js considers all components to be server components.

React Server Component (RSC)

Server Component

By default, Next.js considers all components to be server components.

These components can perform server-side tasks like reading files or fetching data directly from a database.

React Server Component (RSC)

Server Component

By default, Next.js considers all components to be server components.

These components can perform server-side tasks like reading files or fetching data directly from a database.

GSAP & Next.js 15 : The Complete GSAP Masterclass for Beginners in Hindi

React Server Component (RSC)

Client Component

To create a client component in Next.js we have to use "use client" directive at the top of your component file. 

React Server Component (RSC)

Client Component

To create a client component in Next.js we have to use "use client" directive at the top of your component file. 

Client component can not perform server-side tasks like reading files, but we can use hooks and handle user interaction.

React Server Component (RSC)

Client Component

To create a client component in Next.js we have to use "use client" directive at the top of your component file. 

Client component can not perform server-side tasks like reading files, but we can use hooks and handle user interaction.

Client component same as we create a component in react.js 

Routing

Routing

Next.js has a file-system based routing system

Routing Conventions

Routing Conventions

All routes must live inside the app folder

Routing Conventions

All routes must live inside the app folder

Route files must be named either page.js or page.tsx

Routing Conventions

All routes must live inside the app folder

Route files must be named either page.js or page.tsx

If we follow these conventions, the file automatically becomes

available as a route

Text

app

about

page.tsx

contact

page.tsx

layout.tsx

page.tsx

http://localhost:3000

Text

Home Page

Text

app

about

page.tsx

contact

page.tsx

layout.tsx

page.tsx

http://localhost:3000/about

About Page

Text

app

about

page.tsx

contact

page.tsx

layout.tsx

page.tsx

http://localhost:3000/contact

Contact Page

Text

Dynamic Routes

Text

Dynamic Routes

app

about

page.tsx

contact

page.tsx

layout.tsx

page.tsx

product

page.tsx

Products

Product 1

Product 2

Product 3

Product 4

Product 5

Product 6

Product 7

Product 8

Product 9

http://localhost:3000/product

[productId]

page.tsx

Dynamic Routes

Products Details

Product

http://localhost:3000/product/productId

Product Title

Category: ABC

Price: $1234

About this item

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Add to Cart

Buy Now

app

about

page.tsx

contact

page.tsx

layout.tsx

page.tsx

product

page.tsx

[productId]

page.tsx

Dynamic Routes

Products Details

Product

http://localhost:3000/product/1234

Product Title

Category: ABC

Price: $1234

About this item

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Add to Cart

Buy Now

Reviews

Naina

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Mohit

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

More...

app

about

page.tsx

contact

page.tsx

layout.tsx

page.tsx

product

page.tsx

[productId]

page.tsx

Nested Dynamic Routes

Nested Dynamic Routes

Products

Product 1

Product 2

Product 3

Product 4

Product 5

Product 6

Product 7

Product 8

Product 9

http://localhost:3000/product

app

about

page.tsx

contact

page.tsx

layout.tsx

page.tsx

product

page.tsx

[productId]

page.tsx

Products Details

Product

http://localhost:3000/product/1234

Product Title

Category: ABC

Price: $1234

About this item

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Add to Cart

Buy Now

Nested Dynamic Routes

Reviews

Naina

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Mohit

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

More...

app

about

page.tsx

contact

page.tsx

layout.tsx

page.tsx

product

page.tsx

[productId]

page.tsx

reviews

page.tsx

[reviewId]

Reviews

http://localhost:3000/product/1234/1

Nested Dynamic Routes

Naina

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

app

about

page.tsx

contact

page.tsx

layout.tsx

page.tsx

product

page.tsx

[productId]

page.tsx

reviews

page.tsx

[reviewId]

Catch all Segments

Catch all Segments

Math Lecture

  • Lacture 1
    • Sub Lecture 1
    • Sub Lecture 2
  • Lacture 2
  • Lacture 3
  • Lacture 4

Physics Lecture

  • Lacture 1
    • Sub Lecture 1
    • Sub Lecture 2
  • Lacture 2
  • Lacture 3
  • Lacture 4

Chemistry Lecture

  • Lacture 1
    • Sub Lecture 1
    • Sub Lecture 2
  • Lacture 2
  • Lacture 3
  • Lacture 4

Text

Lectures

Catch all Segments

Text

app

about

page.tsx

contact

page.tsx

layout.tsx

page.tsx

product

page.tsx

[productId]

page.tsx

lectures

[...slug]

page.tsx

http://localhost:3000/lectures/lecture1

Text

Private Folders

Text

Private Folders

Text

That folder and subfolders are excluded from routing

Text

Private Folders

Text

That folder and subfolders are excluded from routing

Add and underscore ( _ ) at the begning of your folder name

Text

Private Folders

Text

That folder and subfolders are excluded from routing

Add and underscore ( _ ) at the begning of your folder name

Even if you have page.tsx inside folder with default export it will not route.

_my-folder

Catch all Segments

Text

app

about

page.tsx

contact

page.tsx

layout.tsx

page.tsx

product

page.tsx

[productId]

page.tsx

lectures

[...slug]

page.tsx

http://localhost:3000/lectures/lecture1/sub-lecture1

Text

Route Groups

Text

Route Groups

This helps in organizing routes and project files in a logical way while keeping the URL structure intact.

Text

Route Groups

This helps in organizing routes and project files in a logical way while keeping the URL structure intact.

We will Create

- Register

- Login

Text

Layout

Text

Layout

Layout is UI component where all your routes render as children.

Text

Layout

Layout is UI component where all your routes render as children.

Whatever code you write in your layout will share all those routes

which is rendering on that layout

Text

How to create layouts ?

Text

How to create layouts ?

We have to create layout.tsx or layout.js file

Text

How to create layouts ?

We have to create layout.tsx or layout.js file

That component takes children prop, and children are nothing but

your route page.

Text

How to create layouts ?

app

about

contact

layout.tsx

page.tsx

product

lectures

How to create layouts ?

app

about

contact

layout.tsx

page.tsx

product

lectures

Multiple Root Layouts

Multiple Root Layouts

Use of Route Group

Multiple Root Layouts

Use of Route Group

We can organize our project in a batter way without affecting URLs

Multiple Root Layouts

Use of Route Group

We can organize our project in a batter way without affecting URLs

We can also apply layout specific modules/part of our application.

Routing Metadata

Routing Metadata

Metadata plays a crucial role in enhancing SEO and improving web shareability by providing essential information about your web pages.

Routing Metadata

Metadata plays a crucial role in enhancing SEO and improving web shareability by providing essential information about your web pages.

We have two ways to add Metadata in next.js

Routing Metadata

Metadata plays a crucial role in enhancing SEO and improving web shareability by providing essential information about your web pages.

We have two ways to add Metadata in next.js

1. Static Metadata

Routing Metadata

Metadata plays a crucial role in enhancing SEO and improving web shareability by providing essential information about your web pages.

We have two ways to add Metadata in next.js

1. Static Metadata

2. Dynamic Metadata

Routing Metadata

Metadata plays a crucial role in enhancing SEO and improving web shareability by providing essential information about your web pages.

We have two ways to add Metadata in next.js

1. Static Metadata

We can add this metadata export in page.tsx or in layout.tsx 

Routing Metadata

Metadata plays a crucial role in enhancing SEO and improving web shareability by providing essential information about your web pages.

We have two ways to add Metadata in next.js

2. Dynamic Metadata

We can add this metadata export in page.tsx or in layout.tsx 

Loading

Special File

Loading

This helps you create meaningful Loading UI with React Suspense

Loading

This helps you create meaningful Loading UI with React Suspense

You can show an instant loading state from the server while the content of a route takes time to load.

Loading

This helps you create meaningful Loading UI with React Suspense

You can show an instant loading state from the server while the content of a route takes time to load.

To create loading in Next.js we have to create a file loading.tsx or loading.js

Loading

This helps you create meaningful Loading UI with React Suspense

You can show an instant loading state from the server while the content of a route takes time to load.

To create loading in Next.js we have to create a file loading.tsx or loading.js

Error Handling

Special File

Error Handling

This allows you to handle unexpected runtime errors and display fallback UI

Error Handling

This allows you to handle unexpected runtime errors and display fallback UI

To handle errors we can create an error file with the name error.tsx or error.js

Error Handling

This allows you to handle unexpected runtime errors and display fallback UI

To handle errors we can create an error file with the name error.tsx or error.js

This wraps a route segment and its nested children in a React Error Boundary

Error Handling

This allows you to handle unexpected runtime errors and display fallback UI

To handle errors we can create an error file with the name error.tsx or error.js

This wraps a route segment and its nested children in a React Error Boundary

Error in Layout

Error in Layout

Error in Layout

Parallel Routes

Parallel Routes

What is Paralel Routes ?

Parallel Routes

What is Paralel Routes ?

With Parallel Routes, you can render one or more pages simultaneously

or conditions, all within the same layout

Parallel Routes

Charts

Line Chart

Bar Chart

Heatmap

app

about

contact

layout.tsx

page.tsx

product

charts

line-chart

bar-chart

heatmap

layout.tsx

Parallel Routes

How to Setup Parallel Routes ?

Parallel Routes

How to Setup Parallel Routes ?

Parallel routes are created using named slots. 

Parallel Routes

How to Setup Parallel Routes ?

Parallel routes are created using named slots. 

Slots are defined with the @folder convention.

Parallel Routes

How to Setup Parallel Routes ?

Parallel routes are created using named slots. 

Slots are defined with the @folder convention.

Each defined slot automatically becomes props in corresponding layout.tsx file

Parallel Routes

app

about

contact

layout.tsx

page.tsx

product

charts

@line-chart

@bar-chart

@heatmap

layout.tsx

page.tsx

page.tsx

page.tsx

Charts

Line Chart

Bar Chart

Heatmap

Parallel Routes

Parallel Routes benefits?

Parallel Routes

Parallel Routes benefits?

It is very useful for highly dynamic sections of an app, such as dashboards and feeds on social sites.

Parallel Routes

Parallel Routes benefits?

It is very useful for highly dynamic sections of an app, such as dashboards and feeds on social sites.

Independent route handling

Parallel Routes

Parallel Routes benefits?

It is very useful for highly dynamic sections of an app, such as dashboards and feeds on social sites.

Independent route handling

Sub-navigation

Parallel Routes

Independent route handling

Parallel Routes

Independent route handling

Each slot can have its own loading and error states. 

Parallel Routes

Independent route handling

Each slot can have its own loading and error states. 

This is very useful when you want to handle loading and error separately for each slot.

Parallel Routes

Independent route handling

Each slot can have its own loading and error states. 

This is very useful when you want to handle loading and error separately for each slot.

Charts

Line Chart

Heatmap

Parallel Routes

Independent route handling

Each slot can have its own loading and error states. 

This is very useful when you want to handle loading and error separately for each slot.

Charts

Line Chart

Error loading heatmap

Parallel Routes

Sub-navigation

Parallel Routes

Sub-navigation

Each can work as mini application

Parallel Routes

Sub-navigation

Each can work as mini application

We can work with each separately like, apply filters, sorting or navigation without effecting any other pages or slot

Parallel Routes

Sub-navigation

Each can work as mini application

We can work with each separately like, apply filters, sorting or navigation without effecting any other pages or slot

Charts

Line Chart

Bar Chart

Heatmap

Pie chart

Unmatched Routes

Unmatched Routes

Navigation from UI

Unmatched Routes

Navigation from UI

When you navigate through the UI Next.js keep showing whatever was in the

unmatch slots before

Unmatched Routes

Navigation from UI

When you navigate through the UI Next.js keep showing whatever was in the

unmatch slots before

Page Reload

Unmatched Routes

Navigation from UI

When you navigate through the UI Next.js keep showing whatever was in the

unmatch slots before

Page Reload

Next.js looks for a 'default.tsx' file in each unmatch slot

Unmatched Routes

Navigation from UI

When you navigate through the UI Next.js keep showing whatever was in the

unmatch slots before

Page Reload

Next.js looks for a 'default.tsx' file in each unmatch slot

This file is critical as it serves as a fallback to render content when the framework cannot reterive a slot's active state from the current URL

Unmatched Routes

Navigation from UI

When you navigate through the UI Next.js keep showing whatever was in the

unmatch slots before

Page Reload

Next.js looks for a 'default.tsx' file in each unmatch slot

This file is critical as it serves as a fallback to render content when the framework cannot reterive a slot's active state from the current URL

Without default.tsx file you will get 404 error.

Intercepting Routes

Intercepting Routes

1. Parallel Routes

Intercepting Routes

1. Parallel Routes

2. Intercepting Routes

Intercepting Routes

http://localhost:3000/

Login

Logo

http://localhost:3000/login

http://localhost:3000/login

Login

Logo

Click

Share

Intercepting Routes Conventions

Intercepting Routes Conventions

(.) to match segments on the same level

Intercepting Routes Conventions

(.) to match segments on the same level

(..) to match segments one level above

Intercepting Routes Conventions

(.) to match segments on the same level

(..) to match segments one level above

(..)(..) to match segments on two levels above 

Intercepting Routes Conventions

(.) to match segments on the same level

(..) to match segments one level above

(..)(..) to match segments on two levels above 

(...) to match segments from the root app directory

Parallel Intercepting Routes

Route Handlers

Route Handlers

Using app router we can create custom request handlers for your routes using a feature called Route Handlers

Route Handlers

Using app router we can create custom request handlers for your routes using a feature called Route Handlers

Page routes are used to serve HTML content, whereas Route Handlers empower us to build RESTful endpoints with total control over the response

Route Handlers

Using app router we can create custom request handlers for your routes using a feature called Route Handlers

Page routes are used to serve HTML content, whereas Route Handlers empower us to build RESTful endpoints with total control over the response

As we build RESTful APIs using Node and Express, we can do all CRUD operations

with Route Handlers

Route Handlers

Using app router we can create custom request handlers for your routes using a feature called Route Handlers

Page routes are used to serve HTML content, whereas Route Handlers empower us to build RESTful endpoints with total control over the response

As we build RESTful APIs using Node and Express, we can do all CRUD operations

with Route Handlers

And we don't need to configure separate server.

Route Handlers

Using app router we can create custom request handlers for your routes using a feature called Route Handlers

Page routes are used to serve HTML content, whereas Route Handlers empower us to build RESTful endpoints with total control over the response

As we build RESTful APIs using Node and Express, we can do all CRUD operations

with Route Handlers

And we don't need to configure separate server.

In Route handlers, we can also make external API requests. like if we need to talk with third-party services.

Route Handlers

Using app router we can create custom request handlers for your routes using a feature called Route Handlers

Page routes are used to serve HTML content, whereas Route Handlers empower us to build RESTful endpoints with total control over the response

As we build RESTful APIs using Node and Express, we can do all CRUD operations

with Route Handlers

And we don't need to configure separate server.

In Route handlers, we can also make external API requests. like if we need to talk with third-party services. 

Since route handlers run on the server side, sensitive data like private keys are kept safe.

Route Handlers

Using app router we can create custom request handlers for your routes using a feature called Route Handlers

Page routes are used to serve HTML content, whereas Route Handlers empower us to build RESTful endpoints with total control over the response

As we build RESTful APIs using Node and Express, we can do all CRUD operations

with Route Handlers

And we don't need to configure separate server.

In Route handlers, we can also make external API requests. like if we need to talk with third-party services.

Since route handlers run on the server side, sensitive data like private keys are kept safe.

Route handlers are equvelant to API routes. 

Route Handlers

Using app router we can create custom request handlers for your routes using a feature called Route Handlers

Page routes are used to serve HTML content, whereas Route Handlers empower us to build RESTful endpoints with total control over the response

As we build RESTful APIs using Node and Express, we can do all CRUD operations

with Route Handlers

And we don't need to configure separate server.

In Route handlers, we can also make external API requests. like if we need to talk with third-party services.

Since route handlers run on the server side, sensitive data like private keys are kept safe.

Route handlers are equvelant to API routes. 

Next.js supports GET, POST, PUT, PATCH, DELETE, HEAD, AND OPTIONS

Route Handlers

Next.js will return a 405 Method Not Allowed response when an unsupported method is used

Headers in Route Handlers

Headers in Route Handlers

HTTP headers provide information about the metadata of an API request

and its response.

Headers in Route Handlers

HTTP headers provide information about the metadata of an API request

and its response.

Request Headers

Headers in Route Handlers

HTTP headers provide information about the metadata of an API request

and its response.

Request Headers

These are sent by the clients, such as a web browser, to the server. They contain essential information about the request, which helps the server understand and process it correctly

Headers in Route Handlers

HTTP headers provide information about the metadata of an API request

and its response.

Request Headers

These are sent by the clients, such as a web browser, to the server. They contain essential information about the request, which helps the server understand and process it correctly

"User-Agent" 

They indicate details about the server's browser and operating system

Headers in Route Handlers

HTTP headers provide information about the metadata of an API request

and its response.

Request Headers

These are sent by the clients, such as a web browser, to the server. They contain essential information about the request, which helps the server understand and process it correctly

"User-Agent" 

They indicate details about the server's browser and operating system

"Accept" 

They indicate the types of content, like text, video, or image formats, that the client can handle

Headers in Route Handlers

HTTP headers provide information about the metadata of an API request

and its response.

Request Headers

These are sent by the clients, such as a web browser, to the server. They contain essential information about the request, which helps the server understand and process it correctly

"Authorization" 

enables the client to provide authentication credentials to the server.

"User-Agent" 

They indicate details about the server's browser and operating system

"Accept" 

They indicate the types of content, like text, video, or image formats, that the client can handle

Headers in Route Handlers

HTTP headers provide information about the metadata of an API request

and its response.

Response Headers

Headers in Route Handlers

HTTP headers provide information about the metadata of an API request

and its response.

Response Headers

These are sent back from the server to the client. They provide information about the server and the data being sent in the response.

Headers in Route Handlers

HTTP headers provide information about the metadata of an API request

and its response.

Response Headers

These are sent back from the server to the client. They provide information about the server and the data being sent in the response.

"Content-Type" 

header which indicates the media type of the response. it tells the client what the data type of the returned content is, such as text/html or HTML documents,

application/json for JSON data. etc.

Headers in Route Handlers

HTTP headers provide information about the metadata of an API request

and its response.

Response Headers

These are sent back from the server to the client. They provide information about the server and the data being sent in the response.

"Content-Type" 

header which indicates the media type of the response. it tells the client what the data type of the returned content is, such as text/html or HTML documents,

application/json for JSON data. etc.

Cookies in Route Handlers

Cookies in Route Handlers

Cookies are small pieces data that server send to your browser to identify you and remember your preferences

Cookies in Route Handlers

Cookies are small pieces data that server send to your browser to identify you and remember your preferences

Your browser can store the cookies and send them back to the server whenever you

request the server again

Cookies in Route Handlers

Cookies are small pieces data that server send to your browser to identify you and remember your preferences

Your browser can store the cookies and send them back to the server whenever you

request the server again

Use of Cookies ?

Cookies in Route Handlers

Cookies are small pieces data that server send to your browser to identify you and remember your preferences

Your browser can store the cookies and send them back to the server whenever you

request the server again

Use of Cookies ?

User Authentication: To identify users and maintain logged-in sessions.

Cookies in Route Handlers

Cookies are small pieces data that server send to your browser to identify you and remember your preferences

Your browser can store the cookies and send them back to the server whenever you

request the server again

Use of Cookies ?

User Authentication: To identify users and maintain logged-in sessions.

User Preferences: To remember user-specific settings and preferences

Cookies in Route Handlers

Cookies are small pieces data that server send to your browser to identify you and remember your preferences

Your browser can store the cookies and send them back to the server whenever you

request the server again

Use of Cookies ?

User Authentication: To identify users and maintain logged-in sessions.

User Preferences: To remember user-specific settings and preferences

Session Management: To keep track of active sessions for users.

Caching in Route Handlers

Caching in Route Handlers

By default, route handlers are not cached; however, caching can be enabled when using the get method.

Caching in Route Handlers

By default, route handlers are not cached; however, caching can be enabled when using the get method.

Caching only work with get method

Caching in Route Handlers

By default, route handlers are not cached; however, caching can be enabled when using the get method.

Caching only work with get method

Methods like POST, PUT, or DELETE in HTTP are never cached.

Caching in Route Handlers

By default, route handlers are not cached; however, caching can be enabled when using the get method.

Caching only work with get method

Methods like POST, PUT, or DELETE in HTTP are never cached.

Caching will not work if you are using dynamic functions like headers() and cookies() or working with the request object in your GET method.

Middleware

Middleware

In Next.js, middleware provides a powerful way to intercept and control how requests and responses are handled across your application.

Middleware

In Next.js, middleware provides a powerful way to intercept and control how requests and responses are handled across your application.

It operates globally, boosting capabilities such as redirects, URL rewrites, authentication, managing headers, cookies, and much more.

Middleware

In Next.js, middleware provides a powerful way to intercept and control how requests and responses are handled across your application.

It operates globally, boosting capabilities such as redirects, URL rewrites, authentication, managing headers, cookies, and much more.

Middleware allows you to define specific paths where it should be applied.

Middleware

In Next.js, middleware provides a powerful way to intercept and control how requests and responses are handled across your application.

It operates globally, boosting capabilities such as redirects, URL rewrites, authentication, managing headers, cookies, and much more.

Middleware allows you to define specific paths where it should be applied.

- Custom matcher config

Middleware

In Next.js, middleware provides a powerful way to intercept and control how requests and responses are handled across your application.

It operates globally, boosting capabilities such as redirects, URL rewrites, authentication, managing headers, cookies, and much more.

Middleware allows you to define specific paths where it should be applied.

- Custom matcher config

- Conditional Statements

Rendering

Rendering

It is the process of transforming the code that you write into user interfaces so that users can see and interact with it. 

Rendering

It is the process of transforming the code that you write into user interfaces so that users can see and interact with it. 

In Next.js the tricky part to building a performant application is figuring out when and where this transformation should happen

Rendering

It is the process of transforming the code that you write into user interfaces so that users can see and interact with it. 

In Next.js the tricky part to building a performant application is figuring out when and where this transformation should happen

CSR, SSR and RSCs?

Rendering

It is the process of transforming the code that you write into user interfaces so that users can see and interact with it. 

In Next.js the tricky part to building a performant application is figuring out when and where this transformation should happen

CSR, SSR and RSCs?

Before we go deep into rendering let's look how rendering work in React.

Rendering

It is the process of transforming the code that you write into user interfaces so that users can see and interact with it. 

In Next.js the tricky part to building a performant application is figuring out when and where this transformation should happen

CSR, SSR and RSCs?

Before we go deep into rendering let's look how rendering work in React.

Next.js build on top of React if we understand how rendering work in React we will understand rendering very well.

Rendering in React

Rendering in React

We will look at how React's rendering has transformed over the past years.

Rendering in React

We will dive into React different rendering strategies and see

how they change over time.  

We will look at how React's rendering has transformed over the past years.

Rendering in React

If you have worked with React so long you may remember that React is primarily used for building Single Page Applications (SPAs) 

We will dive into React different rendering strategies and see

how they change over time.  

We will look at how React's rendering has transformed over the past years.

Rendering in React

Client

Server

Rendering in React

Client

Server

Client Request to Server

Rendering in React

Client

Server

Client Request to Server

Blank Screen

HTML with JavaScript Refrence

Rendering in React

Client

Server

Client Request to Server

Blank Screen

HTML with JavaScript Refrence

Request JavaScript

Rendering in React

Client

Server

Client Request to Server

Blank Screen

HTML with JavaScript Refrence

Request JavaScript

JavaScript

Rendering in React

Client

Server

Client Request to Server

Blank Screen

HTML with JavaScript Refrence

Request JavaScript

JavaScript

Generate HTML

Rendering in React

Client

Server

Client Request to Server

Blank Screen

Interactive UI

APP

HTML with JavaScript Refrence

Request JavaScript

JavaScript

Generate HTML

Client-side Rendering

The whole approach we have seen - where your browser (client) transforms React code into what you see on the screen - that's what we call client-side rendering (CSR) 

Client-side Rendering

The whole approach we have seen - where your browser (client) transforms React code into what you see on the screen - that's what we call client-side rendering (CSR) 

CSR became very popular for SPAs applications, and everyone was using it.

Client-side Rendering

The whole approach we have seen - where your browser (client) transforms React code into what you see on the screen - that's what we call client-side rendering (CSR) 

CSR became very popular for SPAs applications, and everyone was using it.

Developers after using CSR noticing drawbacks in to this approach.

CSR Drawbacks

SEO

CSR Drawbacks

SEO

When search engines crawl your site, they're mainly looking at HTML content. But with CSR, your initial HTML is basically just an empty div - it is not good for SEO because search engines will not be able to figure out about the page.

CSR Drawbacks

SEO

When search engines crawl your site, they're mainly looking at HTML content. But with CSR, your initial HTML is basically just an empty div - it is not good for SEO because search engines will not be able to figure out about the page.

When you have many nested components and making API calls, content of your pages will load might slowly for search engines to even catch it.

CSR Drawbacks

Performance

If you notice your browser (client) has to do everything with this approach: fetch data, build the UI, make everything interactive... that's a lot of work!

CSR Drawbacks

Performance

If you notice your browser (client) has to do everything with this approach: fetch data, build the UI, make everything interactive... that's a lot of work!

If you notice your browser (client) has to do everything with this approach: fetch data, build the UI, make everything interactive... that's a lot of work!

With this approach (CSR), Users often end up staring at a blank screen or a loading spinner while all this happens

CSR Drawbacks

Performance

If you notice your browser (client) has to do everything with this approach: fetch data, build the UI, make everything interactive... that's a lot of work!

If you notice your browser (client) has to do everything with this approach: fetch data, build the UI, make everything interactive... that's a lot of work!

With this approach (CSR), Users often end up staring at a blank screen or a loading spinner while all this happens

Whenever you add new features or modules to your application, that JavaScript bundle gets bigger, and it will make users wait even longer.

CSR Drawbacks

Performance

If you notice your browser (client) has to do everything with this approach: fetch data, build the UI, make everything interactive... that's a lot of work!

If you notice your browser (client) has to do everything with this approach: fetch data, build the UI, make everything interactive... that's a lot of work!

With this approach (CSR), Users often end up staring at a blank screen or a loading spinner while all this happens

Whenever you add new features or modules to your application, that JavaScript bundle gets bigger, and it will make users wait even longer.

If users have slower internet user will be frustrated with this.

CSR Drawbacks

Developer need batter solution for SEO and Performance we will see up Next.

Server-side Rendering (SSR)

Server-side Rendering (SSR)

With CSR we have two drawbacks SEO and Performance

Server-side Rendering (SSR)

With CSR we have two drawbacks SEO and Performance

Modern framework like Next.js move to server-side solutions

Server-side Rendering (SSR)

With CSR we have two drawbacks SEO and Performance

Modern framework like Next.js move to server-side solutions

We will see how Server-side improve this

Server-side Rendering (SSR)

Client

Server

Server-side Rendering (SSR)

Client

Server

Client Request to Server

Server-side Rendering (SSR)

Client

Server

Client Request to Server

Generate HTML

Server-side Rendering (SSR)

Client

Server

Client Request to Server

FullHTML with JavaScript Refrence

Generate HTML

User Can not Interact with UI

Server-side Rendering (SSR)

Client

Server

Client Request to Server

Request JavaScript

Generate HTML

User Can not Interact with UI

FullHTML with JavaScript Refrence

Server-side Rendering (SSR)

Client

Server

Client Request to Server

Request JavaScript

JavaScript

Generate HTML

FullHTML with JavaScript Refrence

User Can not Interact with UI

Server-side Rendering (SSR)

Client

Server

Client Request to Server

Request JavaScript

JavaScript

Hydration

Generate HTML

FullHTML with JavaScript Refrence

User Can not Interact with UI

Server-side Rendering (SSR)

Client

Server

Client Request to Server

Interactive UI

APP

Request JavaScript

JavaScript

Hydration

Generate HTML

FullHTML with JavaScript Refrence

User Can not Interact with UI

Server-side Rendering (SSR)

With this approach, Search engines can now easily index the server-rendered content, and it will solve our SEO problem.

Server-side Rendering (SSR)

With this approach, Search engines can now easily index the server-rendered content, and it will solve our SEO problem.

Now server sends HTML so users see actual HTML content right away instead blank screen or loading a spinner

Server-side Rendering (SSR)

With this approach, Search engines can now easily index the server-rendered content, and it will solve our SEO problem.

Now server sends HTML so users see actual HTML content right away instead blank screen or loading a spinner

Now SSR makes content visible faster but it also introduces its drawbacks.

Server-side Rendering (SSR)

With this approach, Search engines can now easily index the server-rendered content, and it will solve our SEO problem.

Now server sends HTML so users see actual HTML content right away instead blank screen or loading a spinner

Now SSR makes content visible faster but it also introduces its drawbacks.

HTML Page can not become fully interactive before the HTML and js bundle are fully downloaded and executed in the browser. 

Server-side Rendering (SSR)

With this approach, Search engines can now easily index the server-rendered content, and it will solve our SEO problem.

Now server sends HTML so users see actual HTML content right away instead blank screen or loading a spinner

Now SSR makes content visible faster but it also introduces its drawbacks.

HTML Page can not become fully interactive before the HTML and js bundle are fully downloaded and executed in the browser. 

This important face known as Hydration

Hydration

While Hydration, React takes control in the browser and reconstructs our component tree in the memory, using the server-rendered HTML as a blueprint.

Hydration

While Hydration, React takes control in the browser and reconstructs our component tree in the memory, using the server-rendered HTML as a blueprint.

It precisely maps where all the interactive elements should go, and then add the JavaScript logics.

Hydration

While Hydration, React takes control in the browser and reconstructs our component tree in the memory, using the server-rendered HTML as a blueprint.

It precisely maps where all the interactive elements should go, and then add the JavaScript logics.

Like initializing the application state, adding events like click and mouseover, and setting up all the dynamic features needed for a fully interactive user experience.

Server-side Rendering

This is categories in two main categories.

Server-side Rendering

This is categories in two main categories.

1. Static Site Generation (SSG)

2. Server-side Rendering (SSR)

Server-side Rendering

1. Static Site Generation (SSG)

Static Site Generation happens during build time when you deploy your

application to the server

Server-side Rendering

1. Static Site Generation (SSG)

Static Site Generation happens during build time when you deploy your

application to the server

It means when you request to the server the SSG page will immediately

be sent to the client 

Server-side Rendering

1. Static Site Generation (SSG)

Static Site Generation happens during build time when you deploy your

application to the server

It means when you request to the server the SSG page will immediately

be sent to the client 

We can use SSG with blog post

Server-side Rendering

2. Server-side Rendering (SSR)

Server-side Rendering renders the pages when you request the server. 

Server-side Rendering

2. Server-side Rendering (SSR)

Server-side Rendering renders the pages when you request the server. 

It is beneficial for personalized content like social media feeds where HTML changes based on user login.

Server-side Rendering

2. Server-side Rendering (SSR)

Server-side Rendering renders the pages when you request the server. 

It is beneficial for personalized content like social media feeds where HTML changes based on user login.

We have seen how rendering improves with CSR to SSR.

But SSR also has its challenges.

SSR Drawbacks

You have to fetch everything before you can show anything

SSR Drawbacks

You have to fetch everything before you can show anything

Your component will not start rendering and then pause or "wait" while

data is still being loaded

SSR Drawbacks

You have to fetch everything before you can show anything

Your component will not start rendering and then pause or "wait" while

data is still being loaded

If you are fetching data from a database in a component or any other sources (like third-party API), the fetching of the data must be completed before

the server can begin rendering the component

SSR Drawbacks

You have to fetch everything before you can show anything

Your component will not start rendering and then pause or "wait" while

data is still being loaded

If you are fetching data from a database in a component or any other sources (like third-party API), the fetching of the data must be completed before

the server can begin rendering the component.

While data fetching and rendering this process can delay the server's response

time to the browser.

SSR Drawbacks

You have to fetch everything before you can show anything

Your component will not start rendering and then pause or "wait" while

data is still being loaded

If you are fetching data from a database in a component or any other sources (like third-party API), the fetching of the data must be completed before

the server can begin rendering the component.

While data fetching and rendering this process can delay the server's response

time to the browser.

It will be delayed because the server must need to finish the collection of all necessary data before sending any part of the page to the client.

SSR Drawbacks

You have to load everything before you can hydrate anything

SSR Drawbacks

You have to load everything before you can hydrate anything

To achieve successful hydration, where React adds interactivity to the server-rendered HTML, your component tree in the browser must exactly match

the server-generated component tree.

SSR Drawbacks

You have to load everything before you can hydrate anything

To achieve successful hydration, where React adds interactivity to the server-rendered HTML, your component tree in the browser must exactly match

the server-generated component tree.

This means that all the JavaScript for the components must be loaded on the client before you can start hydrating any of them.

SSR Drawbacks

You can not interact with anything Before hydration

SSR Drawbacks

You can not interact with anything Before hydration

React performs hydration in a single pass, processing the entire component tree from start to finish without interruption.

SSR Drawbacks

You can not interact with anything Before hydration

React performs hydration in a single pass, processing the entire component tree from start to finish without interruption.

This means that every component must undergo hydration before it becomes interactive.

SSR Drawbacks

Load data for entire page.

Load the JS for entire pages

Hydrate the entire page

SSR Drawbacks

Load data for entire page.

Load the JS for entire pages

Hydrate the entire page

This is very problematic when some parts of pages take time to load.

SSR Drawbacks

Load data for entire page.

Load the JS for entire pages

Hydrate the entire page

This is very problematic when some parts of pages take time to load.

Because of these problems React Team develop new improved SSR Architecture.

SSR Drawbacks

You can not interact with anything Before hydration

You have to load everything before you can hydrate anything

You have to fetch everything before you can show anything

SSR Drawbacks

You can not interact with anything Before hydration

You have to load everything before you can hydrate anything

You have to fetch everything before you can show anything

Because of these problems React Team develop new improved SSR Architecture.

Suspense SSR Architecture

Suspense SSR Architecture

In Suspense SSR architecture React Team introduced a new Component

called <Suspense>

Suspense SSR Architecture

In Suspense SSR architecture React Team introduced a new Component

called <Suspense>

With Suspense, it unlocks two major features.

Suspense SSR Architecture

In Suspense SSR architecture React Team introduced a new Component

called <Suspense>

With Suspense, it unlocks two major features.

1. HTML Streaming on the server

   2. Selective hydration on the client

Suspense SSR Architecture

Client

Server

Suspense SSR Architecture

Client

Server

Client Request to Server

Generate HTML

Suspense SSR Architecture

Client

Server

Client Request to Server

Generate HTML

FullHTML with JavaScript Refrence

Suspense SSR Architecture

Client

Server

Client Request to Server

Request JavaScript

Generate HTML

FullHTML with JavaScript Refrence

User Can not Interact with UI

Suspense SSR Architecture

Client

Server

Client Request to Server

Request JavaScript

JavaScript

Generate HTML

FullHTML with JavaScript Refrence

User Can not Interact with UI

Suspense SSR Architecture

Client

Server

Client Request to Server

Request JavaScript

JavaScript

Hydration

Generate HTML

FullHTML with JavaScript Refrence

User Can not Interact with UI

Suspense SSR Architecture

Client

Server

Client Request to Server

Interactive UI

APP

Request JavaScript

JavaScript

Hydration

Generate HTML

FullHTML with JavaScript Refrence

User Can not Interact with UI

Text

Render

Text

Header

Banner

Footer

Text

Header

Banner

Footer

Main

Text

HTML streaming on the server

HTML streaming on the server

With this approach, you don't have to fetch everything before you can show anything

HTML streaming on the server

With this approach, you don't have to fetch everything before you can show anything

If any of section taking time in load other sections will load immidiatly.

HTML streaming on the server

With this approach, you don't have to fetch everything before you can show anything

If any of section taking time in load other sections will load immidiatly.

It can be seamlessly integrated into the stream later when it's ready

We have another problem here

We know HTML will download faster, but until it loads all JavaScript for the main section it will not start hydrating.

We have another problem here

We know HTML will download faster, but until it loads all JavaScript for the main section it will not start hydrating.

If we have a big chunk of code, the user will still have to wait to interact with the page.

Code Splitting

with this, it will tell your bundler, "These parts of the code arn't urgent - split them into separate scripts."

Code Splitting

with this, it will tell your bundler, "These parts of the code arn't urgent - split them into separate scripts."

If we use "React.lazy" for code splitting it will separates your main section's code from the core JavaScript bundle

Code Splitting

with this, it will tell your bundler, "These parts of the code arn't urgent - split them into separate scripts."

If we use "React.lazy" for code splitting it will separates your main section's code from the core JavaScript bundle

This means if the main sections take time to load browser can download React and most of your app's code independently.

Selective Hydration on the client

When you wrap your main section with the <Suspense> component, it is not just enables streaming but also tells React to hydrate other parts of the page before everything ready.

Selective Hydration on the client

When you wrap your main section with the <Suspense> component, it is not just enables streaming but also tells React to hydrate other parts of the page before everything ready.

This is called Selective Hydration

Header

Banner

Footer

Main

Header

Banner

Footer

Main

Selective Hydration on the client

Selective Hydration also solves the third problem: the necessary to "hydrate everything to interact with anything"

Selective Hydration on the client

Selective Hydration also solves the third problem: the necessary to "hydrate everything to interact with anything"

React will start hydrating as soon as it can, which means users can interact with the other part of the page if some part of the page taking time to load.

Selective Hydration on the client

Selective Hydration also solves the third problem: the necessary to "hydrate everything to interact with anything"

React will start hydrating as soon as it can, which means users can interact with the other part of the page if some part of the page taking time to load.

React also prioritises hydration based on user interaction.

Header

Banner

Footer

Blogs

Social Feed

Header

Banner

Footer

Blogs

Social Feed

Header

Banner

Footer

Blogs

Social Feed

Drawbacks of SSR

Data fetching must be completed before the server can begin rendering HTML

Required JavaScript for the components need to be fully loaded on the client side before the hydration process can start.

All components have to hydrate before becoming interactive.

Drawbacks of Suspense SSR

Even though we're streaming JavaScript code to the browser bit by bit, eventually users still end up downloading the entire code for a webpage.

1

Drawbacks of Suspense SSR

When we add more features or modules to our app the code will more larger.

Even though we're streaming JavaScript code to the browser bit by bit, eventually users still end up downloading the entire code for a webpage.

1

Drawbacks of Suspense SSR

Do We need to downlaod so much data?

When we add more features or modules to our app the code will more larger.

Even though we're streaming JavaScript code to the browser bit by bit, eventually users still end up downloading the entire code for a webpage.

1

Drawbacks of Suspense SSR

If you see every React component hydrated on the client side,

whether it needs interactivity or not

2

Drawbacks of Suspense SSR

If you see every React component hydrated on the client side,

whether it needs interactivity or not

2

This means we are using many resources and slowing down load time to interactivity by hydrating that might just be static components.

Drawbacks of Suspense SSR

If you see every React component hydrated on the client side,

whether it needs interactivity or not

2

This means we are using many resources and slowing down load time to interactivity by hydrating that might just be static components.

Now we have another question

Drawbacks of Suspense SSR

If you see every React component hydrated on the client side,

whether it needs interactivity or not

2

This means we are using many resources and slowing down load time to interactivity by hydrating that might just be static components.

Now we have another question

Should all components be hydrated, even those that don't need interactivity?

Drawbacks of Suspense SSR

If you think your server is better to handle heavy processing, but we are still making user devices do the bulk of JavaScript work.

3

Drawbacks of Suspense SSR

If you think your server is better to handle heavy processing, but we are still making user devices do the bulk of JavaScript work.

3

This will slow things down if user devices are not powerful.

Drawbacks of Suspense SSR

If you think your server is better to handle heavy processing, but we are still making user devices do the bulk of JavaScript work.

3

This will slow things down if user devices are not powerful.

Now we have another important question

Drawbacks of Suspense SSR

If you think your server is better to handle heavy processing, but we are still making user devices do the bulk of JavaScript work.

3

This will slow things down if user devices are not powerful.

Now we have another important question

Shouldn't we be using our servers more?

React Server Components (RSC)

React Rendering

CSR   >  SSR   >  Suspense for SSR

React Rendering

CSR   >  SSR   >  Suspense for SSR

Suspense for SSR solve meany problem but also left some challenges.

CSR   >  SSR   >  Suspense for SSR

React Rendering

CSR   >  SSR   >  Suspense for SSR

CSR   >  SSR   >  Suspense for SSR

Large bundle sizes causing excessive downloads for users

Suspense for SSR solve meany problem but also left some challenges.

React Rendering

CSR   >  SSR   >  Suspense for SSR

CSR   >  SSR   >  Suspense for SSR

Large bundle sizes causing excessive downloads for users

Unnessary hydration delay interactivity

Suspense for SSR solve meany problem but also left some challenges.

React Rendering

CSR   >  SSR   >  Suspense for SSR

CSR   >  SSR   >  Suspense for SSR

Large bundle sizes causing excessive downloads for users

Unnessary hydration delay interactivity

Suspense for SSR solve meany problem but also left some challenges.

Heavy client-side processing leads to poor performance.

React Server Components (RSC)

React Server Components (RSC)

This is a new design architecture by the React Team called React Server Components (RSC)

React Server Components (RSC)

This is a new design architecture by the React Team called React Server Components (RSC)

With this approach, we can create server and client components to optimize efficiency,

load times, and interactivity.

React Server Components (RSC)

This is a new design architecture by the React Team called React Server Components (RSC)

With this approach, we can create server and client components to optimize efficiency,

load times, and interactivity.

With RSC architecture we can create component with two ways.

React Server Components (RSC)

This is a new design architecture by the React Team called React Server Components (RSC)

With this approach, we can create server and client components to optimize efficiency,

load times, and interactivity.

With RSC architecture we can create component with two ways.

1. Client Component

  2. Server Component

Client Component

Client components are similar to normal React components that we already using.

Client Component

Client components are similar to normal React components that we already using.

Client component rendered on the client-side (CSR) but, it can also be render to

HTML on the server (SSR)

Client Component

Client components are similar to normal React components that we already using.

Client component rendered on the client-side (CSR) but, it can also be render to

HTML on the server (SSR)

This means the user will not see the blank screen and will see HTML content immediately because it is rendered on the server.

Client Component

Client components are similar to normal React components that we already using.

Client component rendered on the client-side (CSR) but, it can also be render to

HTML on the server (SSR)

This means the user will not see the blank screen and will see HTML content immediately because it is rendered on the server.

Client components mainly function on the client but can, and ideally should, run once on the server to enhance performance.

Client Component

Client components are similar to normal React components that we already using.

Client component rendered on the client-side (CSR) but, it can also be render to

HTML on the server (SSR)

This means the user will not see the blank screen and will see HTML content immediately because it is rendered on the server.

Client components mainly function on the client but can, and ideally should, run once on the server to enhance performance.

Client components have complete access to the client environment, including the browser, enabling them to utilize state, effects, and event listeners to manage interactivity.

Client Component

Client components are similar to normal React components that we already using.

Client component rendered on the client-side (CSR) but, it can also be render to

HTML on the server (SSR)

This means the user will not see the blank screen and will see HTML content immediately because it is rendered on the server.

Client components mainly function on the client but can, and ideally should, run once on the server to enhance performance.

Client components have complete access to the client environment, including the browser, enabling them to utilize state, effects, and event listeners to manage interactivity.

Client components can also access browser APIs like geolocation or storage allowing you to build UI for your use cases.

Server Component

Server components introduce a new type of React component specifically meant for

server-side operation only.

Server Component

Server components introduce a new type of React component specifically meant for

server-side operation only.

Client components code is downloaded to the client whereas Server components stay on the server and are never downloaded to the client.

Server Component

Server components introduce a new type of React component specifically meant for

server-side operation only.

Client components code is downloaded to the client whereas Server components stay on the server and are never downloaded to the client.

This Server and Client Components offer multiple benefits to our React applications.

Benefits of Server Components

App Bundle Size Smaller

Benefits of Server Components

App Bundle Size Smaller

Server components introduce a new type of React component specifically meant for

server-side operation only.

Benefits of Server Components

App Bundle Size Smaller

Server components introduce a new type of React component specifically meant for

server-side operation only.

Now if any user has slower connections or less powerful devices, they don't need to download, parse, and execute the JavaScript.

Benefits of Server Components

App Bundle Size Smaller

Server components introduce a new type of React component specifically meant for

server-side operation only.

Now if any user has slower connections or less powerful devices, they don't need to download, parse, and execute the JavaScript.

Also, no hydration step, making your app load and become interactive faster.

Benefits of Server Components

Direct access to server-side resources

Benefits of Server Components

Direct access to server-side resources

Server components introduce a new type of React component specifically meant for

server-side operation only.

Benefits of Server Components

Direct access to server-side resources

Server components introduce a new type of React component specifically meant for

server-side operation only.

Server Components can directly access database and file systems, making data fetching super efficient without any client-side processing.

Benefits of Server Components

Enhanced Security

Benefits of Server Components

Enhanced Security

Server Components run on the server, and all the sensitive data like API keys or any other private keys are very much secured.

Benefits of Server Components

Improved Data Fetching

Benefits of Server Components

Improved Data Fetching

Server Components allow us to fetch data on the server.

Benefits of Server Components

Improved Data Fetching

Server Components allow us to fetch data on the server.

With this application performance will improve and rendering time will also be reduced.

Benefits of Server Components

Caching

Benefits of Server Components

Caching

We can catch the result on the server and we can reuse them for different users and requests.

Benefits of Server Components

Faster initial page load and First Contentful Paint

Benefits of Server Components

Faster initial page load and First Contentful Paint

Users can see HTML content immediately as HTML is generated on the server. No need to wait for JavaScript download and execute.

Benefits of Server Components

SEO Improved

Benefits of Server Components

SEO Improved

Now Search Engin can easily index your server-render HTML.

Benefits of Server Components

Efficient streaming

Benefits of Server Components

Efficient streaming

Server Components can divide the rendering process into chunks and stream them to the client as they become available.

Benefits of Server Components

Efficient streaming

Server Components can divide the rendering process into chunks and stream them to the client as they become available.

This allows users to view HTML content sooner, rather than waiting for the server to render the entire page.

Benefits of Server Components

Efficient streaming

Server Components can divide the rendering process into chunks and stream them to the client as they become available.

This allows users to view HTML content sooner, rather than waiting for the server to render the entire page.

Server Components manage data fetching and static rendering, while Client Components are responsible for rendering interactive elements.

This is All about React's Rendering, but how does this connect to Next.js

The App Router in Next.js is fully designed using the React Server Components (RSC) architecture.

RSC Rendering Lifecycle

RSC Rendering Lifecycle

When referring to React Server Components (RSC), we are addressing three main elements.

RSC Rendering Lifecycle

When referring to React Server Components (RSC), we are addressing three main elements.

Your Browser

RSC Rendering Lifecycle

When referring to React Server Components (RSC), we are addressing three main elements.

Your Browser

Next.js (framework)

RSC Rendering Lifecycle

When referring to React Server Components (RSC), we are addressing three main elements.

Your Browser

Next.js (framework)

React (Library)

RSC Loading Sequence

Client

RSC Loading Sequence

Client

Client Request

RSC Loading Sequence

Client

Client Request

Match
Request URL

RSC Loading Sequence

Client

Client Request

Match
Request URL

Render Server Component

RSC Loading Sequence

Client

Client Request

Match
Request URL

Render Server Component

Render Server Component and any Child component that are also server component, converting them in a special format known as RSC payload

RSC Loading Sequence

Client

Client Request

Match
Request URL

Render Server Component

RSC Payload

Render Server Component and any Child component that are also server component, converting them in a special format known as RSC payload

RSC Loading Sequence

Client

Client Request

Match
Request URL

Render Server Component

RSC Payload

Generate HTML on the Server

Render Server Component and any Child component that are also server component, converting them in a special format known as RSC payload

RSC Loading Sequence

Client

Client Request

Match
Request URL

Render Server Component

RSC Payload

Generate HTML on the Server

Stream HTML

Render Server Component and any Child component that are also server component, converting them in a special format known as RSC payload

RSC Loading Sequence

Client

Client Request

Match
Request URL

Render Server Component

RSC Payload

Generate HTML on the Server

Stream HTML

Non-Interactive UI

Render Server Component and any Child component that are also server component, converting them in a special format known as RSC payload

RSC Loading Sequence

Client

Client Request

Match
Request URL

Render Server Component

RSC Payload

Generate HTML on the Server

Stream HTML

Non-Interactive UI

Same time it also Send RSC Payload

Render Server Component and any Child component that are also server component, converting them in a special format known as RSC payload

RSC Loading Sequence

Client

Client Request

Match
Request URL

Render Server Component

RSC Payload

Generate HTML on the Server

Stream HTML

Non-Interactive UI

Same time it also Send RSC Payload

Progrssively Render UI

Final UI

Render Server Component and any Child component that are also server component, converting them in a special format known as RSC payload

RSC Loading Sequence

Client

Client Request

Match
Request URL

Render Server Component

RSC Payload

Generate HTML on the Server

Stream HTML

Non-Interactive UI

Same time it also Send RSC Payload

Progrssively Render UI

Hydration

Final UI

Interactive UI

Render Server Component and any Child component that are also server component, converting them in a special format known as RSC payload

RSC Update Sequence

Client

RSC Update Sequence

Client

Client Request

RSC Update Sequence

Client

Client Request

Match
Request URL

RSC Update Sequence

Client

Client Request

Match
Request URL

Render Server Component

RSC Update Sequence

Client

Client Request

Match
Request URL

Render Server Component

Render Server Component and any Child component that are also server component, converting them in a special format known as RSC payload

RSC Update Sequence

Client

Client Request

Match
Request URL

Render Server Component

Render Server Component and any Child component that are also server component, converting them in a special format known as RSC payload

RSC Payload

RSC Update Sequence

Client

Client Request

Match
Request URL

Render Server Component

Render Server Component and any Child component that are also server component, converting them in a special format known as RSC payload

RSC Payload

RSC Payload

RSC Update Sequence

Client

Client Request

Match
Request URL

Render Server Component

Render Server Component and any Child component that are also server component, converting them in a special format known as RSC payload

RSC Payload

Route Render

RSC Payload

RSC Update Sequence

Client

Client Request

Match
Request URL

Render Server Component

Render Server Component and any Child component that are also server component, converting them in a special format known as RSC payload

RSC Payload

Route Render

RSC Payload

Reconciliation

RSC Update Sequence

Client

Client Request

Match
Request URL

Render Server Component

Render Server Component and any Child component that are also server component, converting them in a special format known as RSC payload

RSC Payload

Route Render

RSC Payload

Reconciliation

Update Ui

Server Render Strategies

Static Rendering

Dynamic Rendering

Streaming

Static Rendering

Static rendering is a server rendering strategy in which an HTML page is generated when we build our application.

Static Rendering

Static rendering is a server rendering strategy in which an HTML page is generated when we build our application.

You can think your page will generated in advanced before user requests.

Static Rendering

Static rendering is a server rendering strategy in which an HTML page is generated when we build our application.

You can think your page will generated in advanced before user requests.

Once we build, those pages can be cached by CDNs and served to the users instantly.

Static Rendering

Static rendering is a server rendering strategy in which an HTML page is generated when we build our application.

You can think your page will generated in advanced before user requests.

Once we build, those pages can be cached by CDNs and served to the users instantly.

With this approach, whenever any user request the page, same page will be shared

to the different users.

Where we should use it ?

Static rendering we can use for blog posts, product list pages, documentation etc...

How can we render any route statically?

We do not have to do anything for this, Static Rendering is default strategy in the app route.

How can we render any route statically?

We do not have to do anything for this, Static Rendering is default strategy in the app route.

During the build process, all routes are prepared automatically and we do not have

to do any additional steps.

How can we render any route statically?

We do not have to do anything for this, Static Rendering is default strategy in the app route.

During the build process, all routes are prepared automatically and we do not have

to do any additional steps.

Wait a second—you keep mentioning generating HTML during the build process, but we haven’t actually built the application yet, right? We’re still in development mode.

Production server vs dev server ?

In production, we create an optimized build, deploy it, and cannot make changes once development is complete.

Production server vs dev server ?

In production, we create an optimized build, deploy it, and cannot make changes once development is complete.

A development server, however, is designed with the developer's experience in mind.

Production server vs dev server ?

In production, we create an optimized build, deploy it, and cannot make changes once development is complete.

A development server, however, is designed with the developer's experience in mind.

In production, pages are pre-rendered once during the build phase.

Production server vs dev server ?

In production, we create an optimized build, deploy it, and cannot make changes once development is complete.

A development server, however, is designed with the developer's experience in mind.

In production, pages are pre-rendered once during the build phase.

In development environment, pages pre-rendering for each request.

Dynamic Rendering

Dynamic Rendering

Dynamic rendering is a server rendering strategy where routes are rendered when

user requests the route.

Dynamic Rendering

Dynamic rendering is a server rendering strategy where routes are rendered when

user requests the route.

This is helpful when you need to display personalized data or information that is only accessible at the time of the request. think like cookies or URL parameters.

Dynamic Rendering

Dynamic rendering is a server rendering strategy where routes are rendered when

user requests the route.

This is helpful when you need to display personalized data or information that is only accessible at the time of the request. think like cookies or URL parameters.

Examples of where dynamic rendering is useful include news websites, customized shopping pages, and social media feeds.

How to Dynamically Render?

If a "dynamic function" or "dynamic API" is detected, Next.js automatically shifts to dynamic rendering for the full route.

How to Dynamically Render?

If a "dynamic function" or "dynamic API" is detected, Next.js automatically shifts to dynamic rendering for the full route.

Next.js dynamic functions are:

cookie()

header()

connection()

draftMode()

searchParams props

after()

If you use any of them full route automatically sifts to dynamic rendering at request time.

generateStaticParams()

generateStaticParams()

generateStaticParams is a function that operates

generateStaticParams()

Alongside dynamic route segments

Create static routes at the time of the build.

Insted of on demand at the request time

This provides us with a significant performance improvement.

generateStaticParams is a function that operates

Multiple dynamic route params

Think we have a product catalogue with categories and products

/products/[category]/[product]/page.tsx

dynamicParams

dynamicParams

Manage the behaviour when a dynamic segment is accessed that wasn’t pre-generated using generateStaticParams()

dynamicParams

Manage the behaviour when a dynamic segment is accessed that wasn’t pre-generated using generateStaticParams()

True - Next.js will statically render the page on demand for any dynamic segments not included in generateStaticParams()

dynamicParams

Manage the behaviour when a dynamic segment is accessed that wasn’t pre-generated using generateStaticParams()

True - Next.js will statically render the page on demand for any dynamic segments not included in generateStaticParams()

False - Next.js will return a 404 error for any dynamic segments not included in our

pre-rendered list

Streaming

Streaming

Streaming is a technique that enables the server to render the UI progressively.

Streaming

Streaming is a technique that enables the server to render the UI progressively.

Tasks are divided into smaller chunks and streamed to the client as soon as they are ready.

Streaming

Streaming is a technique that enables the server to render the UI progressively.

Tasks are divided into smaller chunks and streamed to the client as soon as they are ready.

As a result, users can start seeing parts of the page instantly, without waiting for the full page to finish loading

Streaming

Streaming is a technique that enables the server to render the UI progressively.

Tasks are divided into smaller chunks and streamed to the client as soon as they are ready.

As a result, users can start seeing parts of the page instantly, without waiting for the full page to finish loading

The App Router in Next.js comes with built-in support for streaming.

Server and Client Composition

Server and Client Composition

Server Components

Server and Client Composition

Server Components

Data fetching

Server and Client Composition

Server Components

Data fetching

Directly access backend resources

Server and Client Composition

Server Components

Data fetching

Directly access backend resources

Keeping sensitive information (like access tokens and API keys) secure on the server

Server and Client Composition

Server Components

Data fetching

Directly access backend resources

Keeping sensitive information (like access tokens and API keys) secure on the server

handling large dependencies server side - which means less JavaScript will

download by the users.

Server and Client Composition

Client Components

Server and Client Composition

Client Components

For handling interactivity

Server and Client Composition

Client Components

For handling interactivity

Add event listeners (like onClick(), onChange(), etc..)

Server and Client Composition

Client Components

For handling interactivity

Add event listeners (like onClick(), onChange(), etc..)

Managing state (using hooks like useState or useEffect)

Server and Client Composition

Client Components

For handling interactivity

Add event listeners (like onClick(), onChange(), etc..)

Managing state (using hooks like useState or useEffect)

Working with browser APIs

Server and Client Composition

Client Components

For handling interactivity

Add event listeners (like onClick(), onChange(), etc..)

Managing state (using hooks like useState or useEffect)

Working with browser APIs

Work with custom hooks

Context Providers

Context Providers

In Next.js, a context provider is used similarly to React, wrapping parts of your application to share global data (e.g., themes, user authentication) across components. It is typically placed in root layout.tsx to ensure the context is available throughout the entire app.

Context Providers

In Next.js, a context provider is used similarly to React, wrapping parts of your application to share global data (e.g., themes, user authentication) across components. It is typically placed in root layout.tsx to ensure the context is available throughout the entire app.

In Server Components React Context isn't supported.

Context Providers

In Next.js, a context provider is used similarly to React, wrapping parts of your application to share global data (e.g., themes, user authentication) across components. It is typically placed in root layout.tsx to ensure the context is available throughout the entire app.

In Server Components React Context isn't supported.

If you try to set up a context at the top level of your app, you’ll encounter an error.

Context Providers

In Next.js, a context provider is used similarly to React, wrapping parts of your application to share global data (e.g., themes, user authentication) across components. It is typically placed in root layout.tsx to ensure the context is available throughout the entire app.

In Server Components React Context isn't supported.

If you try to set up a context at the top level of your app, you’ll encounter an error.

To resolve this, create your context and render its provider within a separate

client component.

Request Memoization

Request Memoization

As a result, you can fetch data wherever you need it in your components without worrying about duplicate network requests.

Request Memoization

As a result, you can fetch data wherever you need it in your components without worrying about duplicate network requests.

React will execute the fetch operation just once and utilize the same result for any additional calls within the same render cycle

Request Memoization

As a result, you can fetch data wherever you need it in your components without worrying about duplicate network requests.

React will execute the fetch operation just once and utilize the same result for any additional calls within the same render cycle

It’s a feature of React, and as a result, it’s also available in Next.js

Data Fetching Patterns

Data Fetching Patterns

There are two main data fetching patterns you should consider when fetching data

inside components.

Data Fetching Patterns

There are two main data fetching patterns you should consider when fetching data

inside components.

Sequential

Parallel

Data Fetching Patterns

There are two main data fetching patterns you should consider when fetching data

inside components.

Sequential

Parallel

Requests within a component tree rely on one another, which can result in

increased loading times.

Data Fetching Patterns

There are two main data fetching patterns you should consider when fetching data

inside components.

Parallel

Requests in a route are started simultaneously, allowing data to load in parallel and reducing the overall loading time.

Data Fetching from Database

Data Fetching from Database

We'll be using two handy tools—SQLite and Prisma.

Data Fetching from Database

We'll be using two handy tools—SQLite and Prisma.

SQLite

Data Fetching from Database

We'll be using two handy tools—SQLite and Prisma.

SQLite

A simple database that operates on a file-based system to store project-related information

Data Fetching from Database

We'll be using two handy tools—SQLite and Prisma.

SQLite

A simple database that operates on a file-based system to store project-related information

It operates without a server or complex configuration, making it ideal for

learning and prototyping.

Data Fetching from Database

We'll be using two handy tools—SQLite and Prisma.

SQLite

A simple database that operates on a file-based system to store project-related information

It operates without a server or complex configuration, making it ideal for

learning and prototyping.

Prisma

Data Fetching from Database

We'll be using two handy tools—SQLite and Prisma.

SQLite

A simple database that operates on a file-based system to store project-related information

It operates without a server or complex configuration, making it ideal for

learning and prototyping.

Prisma

A tool that simplifies communication with your database.

Data Fetching from Database

We'll be using two handy tools—SQLite and Prisma.

SQLite

A simple database that operates on a file-based system to store project-related information

It operates without a server or complex configuration, making it ideal for

learning and prototyping.

Prisma

A tool that simplifies communication with your database.

It's like a mediator, helping your code communicate effectively with SQLite.

Server Actions

Server Actions

Server actions are async functions that run exclusively on the server.

Server Actions

Server actions are async functions that run exclusively on the server.

They can be invoked in both Server and Client Components to process form submissions and perform data mutations in Next.js applications.

Server Actions

Server actions are async functions that run exclusively on the server.

They can be invoked in both Server and Client Components to process form submissions and perform data mutations in Next.js applications.

You should use Server Actions when you

Server Actions

Server actions are async functions that run exclusively on the server.

They can be invoked in both Server and Client Components to process form submissions and perform data mutations in Next.js applications.

need to execute database operations securely on the server

You should use Server Actions when you

Server Actions

Server actions are async functions that run exclusively on the server.

They can be invoked in both Server and Client Components to process form submissions and perform data mutations in Next.js applications.

need to execute database operations securely on the server

You should use Server Actions when you

want to reduce API boilerplate code

Server Actions

Server actions are async functions that run exclusively on the server.

They can be invoked in both Server and Client Components to process form submissions and perform data mutations in Next.js applications.

need to execute database operations securely on the server

You should use Server Actions when you

want to reduce API boilerplate code

need progressive enhancement for forms

Server Actions

Server actions are async functions that run exclusively on the server.

They can be invoked in both Server and Client Components to process form submissions and perform data mutations in Next.js applications.

need to execute database operations securely on the server

You should use Server Actions when you

want to reduce API boilerplate code

need progressive enhancement for forms

want to optimize for performance

Server Actions Convention

Server Actions Convention

A Server Action can be declared using the React "use server" directive.

Server Actions Convention

A Server Action can be declared using the React "use server" directive.

You can place the directive

Server Actions Convention

A Server Action can be declared using the React "use server" directive.

You can place the directive

At the top of an async function marks the function as a Server Action.

Server Actions Convention

A Server Action can be declared using the React "use server" directive.

You can place the directive

At the top of an async function marks the function as a Server Action.

At the top of a file makes all exported functions in that file Server Actions.

Pending State with useFormStatus hook

Pending State with useFormStatus hook

useFormStatus is a React hook that provides details about the last form submission.

Pending State with useFormStatus hook

useFormStatus is a React hook that provides details about the last form submission.

const status = useFormStatus()

Pending State with useFormStatus hook

useFormStatus is a React hook that provides details about the last form submission.

const status = useFormStatus()

pending: A true or false value that tells if the parent <form> is submitting

Pending State with useFormStatus hook

useFormStatus is a React hook that provides details about the last form submission.

const status = useFormStatus()

pending: A true or false value that tells if the parent <form> is submitting

data: It contains the form's submission details in an object format.

Pending State with useFormStatus hook

useFormStatus is a React hook that provides details about the last form submission.

const status = useFormStatus()

pending: A true or false value that tells if the parent <form> is submitting

data: It contains the form's submission details in an object format.

method: A string value ("get" or "post") that indicates the HTTP method used for the

form submission.

Pending State with useFormStatus hook

useFormStatus is a React hook that provides details about the last form submission.

const status = useFormStatus()

pending: A true or false value that tells if the parent <form> is submitting

data: It contains the form's submission details in an object format.

method: A string value ("get" or "post") that indicates the HTTP method used for the

form submission.

action: A reference to the function that was provided to the parent <form> as its action prop.

Pending State with useFormStatus hook

useFormStatus is a React hook that provides details about the last form submission.

const status = useFormStatus()

pending: A true or false value that tells if the parent <form> is submitting

data: It contains the form's submission details in an object format.

method: A string value ("get" or "post") that indicates the HTTP method used for the

form submission.

action: A reference to the function that was provided to the parent <form> as its action prop.

We'll use "pending" to disable the submit button while the form is submitting

Pending (useFormStatus) vs isPending (useActionState)

Pending (useFormStatus) vs isPending (useActionState)

Both can check if a form is submitted and disable the submit button, but they have an important difference.

Pending (useFormStatus) vs isPending (useActionState)

Both can check if a form is submitted and disable the submit button, but they have an important difference.

The pending state from useFormStatus is only meant for tracking form submissions.

Pending (useFormStatus) vs isPending (useActionState)

Both can check if a form is submitted and disable the submit button, but they have an important difference.

The pending state from useFormStatus is only meant for tracking form submissions.

The isPending state from useActionState can be used with any action, not just form submissions

Pending (useFormStatus) vs isPending (useActionState)

Both can check if a form is submitted and disable the submit button, but they have an important difference.

The pending state from useFormStatus is only meant for tracking form submissions.

The isPending state from useActionState can be used with any action, not just form submissions

Use the pending state from useFormStatus when creating reusable components that will be inside forms, like submit buttons or loading spinners for different forms in your app.

Pending (useFormStatus) vs isPending (useActionState)

Both can check if a form is submitted and disable the submit button, but they have an important difference.

The pending state from useFormStatus is only meant for tracking form submissions.

The isPending state from useActionState can be used with any action, not just form submissions

Use the pending state from useFormStatus when creating reusable components that will be inside forms, like submit buttons or loading spinners for different forms in your app.

Use isPending from useActionState when tracking server actions that don’t have to be tied to form submissions, giving you more flexibility.

Next.js 15

By AZ Bytes

Next.js 15

  • 897