KEMBAR78
NoteGPT - Next - Js 15 Full Tutorial - Beginner To Advanced | PDF | Computer Programming | Software Development
0% found this document useful (0 votes)
25 views112 pages

NoteGPT - Next - Js 15 Full Tutorial - Beginner To Advanced

This document is an introductory tutorial for Next.js, a React framework for building full-stack web applications. It covers the key features of Next.js, including file-based routing, API routes, rendering flexibility, and data fetching, while also outlining prerequisites such as knowledge of HTML, CSS, and JavaScript. The tutorial guides users through setting up a development environment, creating a basic Next.js application, and understanding the project's folder structure and routing conventions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views112 pages

NoteGPT - Next - Js 15 Full Tutorial - Beginner To Advanced

This document is an introductory tutorial for Next.js, a React framework for building full-stack web applications. It covers the key features of Next.js, including file-based routing, API routes, rendering flexibility, and data fetching, while also outlining prerequisites such as knowledge of HTML, CSS, and JavaScript. The tutorial guides users through setting up a development environment, creating a basic Next.js application, and understanding the project's folder structure and routing conventions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 112

00:00:00

hey everyone my name is vishwas and welcome to the most comprehensive next year's
tutorial course throughout this course we will build from the ground up exploring
all key Concepts in Ni shares we will be focusing on version 15 and above depending
on when you're watching in this introduction I'll cover what nexs is why it's worth
learning and what you need to know before getting started so what exactly is nexs
nexs is a react framework for building full stack web applications when building
applications

00:00:31
with react alone it's not feasible to create a fully featured application ready for
production react is a library for building user interfaces responsible only for the
view layer of an application as a developer you need to make decisions about other
features such as routing data fetching and more next shs on the other hand is a
react framework it uses react for building user interfaces but also provides
additional features that enable you to build production ready applications these
features include routing optimized

00:01:02
rendering data fetching bundling compiling and more you don't have to install
additional packages as nexs provides everything you need however keep in mind that
nexs being a framework has opinions and conventions that should be followed to
implement these features there's no need to worry though as the conventions have
emerged from a team with years of experience in writing react apps for production
so to reiterate nexs is a react framework for building production ready full stack
web applications now that we understand what

00:01:34
nextjs is let's see why it's worth learning the reason to learn next sh stems from
the fact that it simplifies the process of building production ready web
applications let me list some of the key features that Nies provides out of the box
first is routing traditional react applications require installing and configuring
thirdparty routing packages every time you need to create a route nexts simplifies
this with file based rout in you just create files and the routes are automatically
generated second is API routes which

00:02:07
sets nexs apart as a full stack framework you can build both front-end react
components and backend epis within the same nexs application allowing seamless
integration between your front end and backend code third is rendering flexibility
next supports both server side and client side rendering approaches when
implemented properly this leads to improved performance and better search engine
optimization fourth is streamlined data fetching xgs provides buil-in esync a
support in react components making data

00:02:39
fetching straightforward and efficient xgs is also flexible with styling approaches
supporting CSS modules tailin CSS and CSS injs solutions to match your preferences
additionally nextjs includes outof the boox optimizations for images fonts and
scripts enhancing your application cor web vitals and overall user experience ience
finally nexts comes with an optimized development and production build system this
means you can focus on writing code instead of dealing with complex configurations
these features combined to make nexts a
00:03:13
powerful framework for web development throughout this course we will explore each
feature in detail also please note that I may refer to nexts simply as next in the
course so please don't get confused now what about the prerequisites HTML CSS and
model and JavaScript knowledge are required since nextjs is a react framework it's
also essential to have a good understanding of react fundamentals while you don't
need to be an expert you should be familiar with Concepts like function components
props State jsx and hooks if

00:03:46
you're new to react I have an extensive tutorial series that covers react from
beginner to advanced level so make sure to check that out my goal is to guide you
from a complete beginner to becoming an expert in next year you can find all Source
codes for this course in the GitHub repository Linked In the description with this
introduction let's move on to building our first hello world application in nexs
let's create our first nexs application together first things first we need to set
up our development

00:04:17
environment we need two things nodejs and a text editor of your choice head over to
nodejs.org to download and install the latest stable release of node.js if you
already have it installed just make sure it's up to date nextjs requires nodejs
version 18.18 or later for the text editor I personally recommend vs code you can
grab that from code dovisual studio.com all right with our environment ready let's
dive in I've created a folder called nexs tutorials and opened vs code in it this
folder

00:04:53
will be our workspace throughout the course creating a new next year project is
super simple it just takes one command open up your terminal control pactic being
the shortcut and run the command npx create hyphen next hyphen app at latest when
you do this you will see several prompts first up it will ask for the project name
we will call it hello hyphen world then you will see seven configuration prompts
let me guide you through these choices we want typescript we want eslint we want t
in CSS we want our code in a source

00:05:33
directory we will use the new app router turbo pack is stable in version 15 but we
will opt out for now and we will stick with the default import Alias give it a few
seconds to do its thing and you'll see a new folder called hello world with your
nexs application inside to get the application running navigate into the project
folder with the command CD hello hyphen world then run the command npm run Dev this
starts a development server on Local Host P 3000 Control Plus click or command plus
click

00:06:10
the link it gives to open the application right in your browser and there you have
it your hell World application is up and running you'll see the next sh's welcome
page with an instruction that says get started by editing Source slapp p. TSX save
and see your changes instantly the let's do exactly that go back to vs code
minimize the terminal with control backtick open the source folder then the app
folder and find page. TSX here if you scroll down you can see the two instructions
get started by editing

00:06:47
Source slapp page. TSX and save and see your changes instantly let's replace the
text in the second list item with Hello World save it and the browser will
automatically refresh and you will see your text change on the screen just like
that you've got your first NS application running now that we know how to generate
an nexs app using Create next app let's take a look at the Project's folder
structure previously we learned how to create and run a basic nxs application now
we're going to dig into the

00:07:22
Project's structure to understand what makes everything take when we run our
application I've got the hello world project open in vs code and at the root level
we can see four folders and 10 files let's break this down one by one starting with
the files first we have package.json this is where all our project dependencies and
scripts live for dependencies we've got the essentials next year version 15 react
and react Dom version 19 depending on what you choose during setup you might

00:07:56
also have typescript with its types Tailwind with post CSS and eslin packages the
script section is pretty straightforward Dev for development mode build for
production builds start for running the production server and Link for setting up
next jss built-in es link configuration a straightforward package.json file with
dependencies and scripts next up are our configuration files we've got next. config
dots for next year settings Ts config.js for for typescript eslint config.js for
eslint and both twin.

00:08:38
config.cfg MGS for tailn CSS there are also a few files we won't focus on much in
this course package lock. Json which ensures consistent installation of our
dependencies get ignore for Version Control the readme file which contains a few
instructions related to running building and deploying the application and next
env. D.S which contains the typescript Declarations for n shs now let's proceed to
the different folders first is the next folder this gets created when you run
either Dev or Bild

00:09:13
scripts it's where your NEX application actually gets served from you will notice
that this folder is G ignored so don't worry about this one too much during
development then we have node modules the home of all our installed dependencies
this gets created when you run npm install or in our case when we run the dev
script which handles the installation automatically if needed like the next folder
this wants get ignored too and we don't need to worry about it during development
the third

00:09:43
folder is the public folder it's pretty important it's where all your static assets
like images and svgs go finally we've got the start of the show The Source folder
inside source there is the app folder which is the app router this is where we will
spend most of our time in this course currently it contains four files F icon for
the browser tab icon global. CSS for application wide Styles layout. TSX for shared
UI elements across pages and page. TSX which creates what you see at localhost for
3000 this page. TSX is

00:10:23
what we tweaked earlier the home component defined here slots into layout. TSX as
children Pro top to create the complete UI in layout. TSX depending on the minor
version of nexs you might see Guist font imported as a Google font or might also be
referenced as a local font that does not affect our learnings so don't worry too
much about it but let me explain how it all comes together when we run the command
npm run Dev in the terminal the execution starts from package.json moves to layout.
TSX

00:10:57
rendering the root layout component for the URL localhost 3000 it looks for the
component in page. TSX within the app folder that is our home component it renders
this component inside the root layout you might now be wondering how this app
folder handles routing in our application but before we get there we need to cover
some new react Concepts that are fundamental to how we write next year's code let's
explore those next before we dive into routing let's cover a fundamental concept
that will

00:11:32
help us better understand how routing Works in X shares that concept is react
server components or RSC for short react server components is a new architecture
that was introduced by the react team and quickly adopted by next Shar this
architecture introduces a new approach to creating react components by dividing
them into two distinct types server components and client components we will
explore these component types in more detail as we move move forward but for now
let's focus on a few key points by

00:12:03
default NEX treets all components as server components these components can perform
server side tasks like reading files or fetching data directly from a database the
trade-off is that they can't use react hooks or handle user interactions if you
want to create a client component you will need to add the use client directive at
the top of your component file while client components can't perform server side
tasks like reading files they can use Hooks and handle interactions think of client
components as the traditional

00:12:34
react components you're already familiar with from previous versions of react as we
get into routing you will see practical examples of both component types we will
work with several components that weit for certain operations to complete before
rendering content and we will use client components to take advantage of hooks from
the routing module having this basic understanding of server and client components
will really help you grasp the routing concept ceps better if none of this makes
sense right now don't

00:13:02
worry we will cover everything about react server component in much more detail
later in the course all right with this Foundation let's jump into routing in nexts
let's dive into one of NEX js's core features routing nextjs uses a file system
based routing system meaning the URLs you can access in your browser are determined
by how you organize your files and folders in your code let me show you how this
works with some practical examples I have created a new NEX project using the
command npx create

00:13:36
next app at latest routing hyphen demo routing demo is the name of our project when
the command completes successfully you should have a project similar to mine
navigate to The Source folder now we will start fresh by deleting the app folder
since we are going to build our routes from scratch I mentioned earlier that next s
has a file based routing mechanism you might naturally Wonder does every file in
our app folder become a route not quite next she is built around conventions and
routing is one area

00:14:12
where these conventions are particularly important there are three main conventions
to remember first all routes must live inside the app folder second route files
must be named either page.js or page. TSX depending on whether you're using
typescript third each folder represents a segment of the URL path when these
conventions are followed the file automatically becomes available as a route let's
put this into practice for scenario one we want to create a homepage that shows up
when someone visits our site at Local

00:14:46
Host Port 3000 let's head back to vs code and implement this scenario the first key
convention in EXs routing is that all routes must be placed in an app folder within
the source directory let's create this folder the second convention is that any
file meant to be a route must be named page. TSX or page.js if you're not using
typescript let's create a page. TSX file in the app folder from this file we will
default export a simple react component export default function home and this
returns

00:15:24
an each one tag that says welcome home and just like that we have created our first
next year's route in the terminal run the command npm run Dev to start the dev
server in the browser visit localhost 3000 and you will see welcome home displayed
this is our first key routing concept to remember page. TSX file inside the app
folder automatically maps to your site's root URL with that we have successfully
implemented scenario one before we continue let's talk about the layout. TSX file
even

00:16:00
though we deleted this file when removing the app folder nexts will automatically
create and set it up when you first access the root route we will explore layouts
in depth later but for now just remember that this file gets automatically created
behind the scenes now let's tackle scenario number two for this scenario we need to
create two additional routes one for the about page and one for the profile page
the URL will read localhost 3000 slab and localhost 3000 SL profile back in vs code
let's create these routes there are

00:16:35
three simple steps first create a new folder called about inside the app folder
second inside this about folder create a page. TSX file third from this file
default export a react component export default function about which returns an
each one about me similarly create another folder in the app folder called profile
inside the folder create page. TSX file from this file default export a react
component export default function profile return an H1 tag that says my profile
after saving the files and

00:17:18
heading back to the browser the homepage will still be displayed at the root route
Local Host Port 3000 when you navigate to localhost 3000 slab you will see the
about me page and similarly going to SL profile will show the my profile page
scenario 2 is now complete the second key routing concept to remember is that
routes are directly tied to their folder names within the app directory a page. TSX
file inside the about folder maps to the slab route and a page. TSX file inside the
profile folder maps to the/ profile route let me

00:17:57
show you a quick visualization of everything we have covered so far it is pretty
straightforward page. TSX in the app folder directly maps to the root route and
each folder in the app folder directly maps to a segment in your url now you might
be wondering what happens if someone tries to access a URL that doesn't match any
file in your app folder let's say someone tries to visit SL dashboard in this case
NEX has got you covered it will automatically serve up a 404 not found response you
don't

00:18:28
need to write any special code to handle these non-existing routes by now you
should have a solid understanding of how file based routing works in xjs the beauty
of this system is that you don't need to mess around with installing and
configuring a router in your code your file and folder structure does all the heavy
lifting this is a perfect example of nex's philosophy of favoring conventions over
configuration when it comes to routing all right let's continue exploring more
routing Concepts

00:18:59
previously we got a glimpse of nex's file based routing system we saw how the page.
TSX file in the app folder maps to a root domain and how page. TSX files in
subfolders create routes matching their folder names like about and profile now
let's tackle nested routes in scenario 3 we need to set up a page that shows up
when users visit Local Host 3000 SL blog we will also need to handle two additional
routes localhost 3000 /blog slir and Loos 3000 blog2 let me show you how easy this
is with the app router first up let's

00:19:38
create a block folder inside our app directory inside this block folder we will add
page. TSX file with a simple react component exported as default so page. TSX and
the react component export default function blog that returns an H1 tag my blog if
we save this and check localhost 3000 /blog we will see our blog page right away
that takes care of the first part of scenario 3 but what about these nested routes
SL blog slfirst and SL blog SLC this is where nexs really shines we can simply
create two new folders inside

00:20:22
the block folder named first and second so new folder first new folder second in
each folder we will create a page. TSX file with its own component exported as
default page. TSX and another page. TSX we export a default function called first
blog that returns an each1 tag first blog post and in the other we export a default
function second blog that returns an H1 tag second blog post so save the files
navigate to localhost 3000 /blog slfirst and you will see the first block page
render exactly where it should and

00:21:09
similarly when you navigate to /blog SLC you will see the second block page just
like that we have implemented scenario number three here's a visualization of how
these nested routes work page. TSX in the app folder corresponds to the root route
page. TSX in the block folder corresponds to /blog page. TSX in the first folder
corresponds to/ blog slir and similarly /blog SL2 the key takeaway here is that
nexs mirrors your folder structure in your URLs automatically it is that simple up
next we will check out something even

00:21:47
more powerful Dynamic routes previously we learned about nested routes by creating
a block folder in the app directory with first and second subfolders each subfolder
has its own page. TSX file corresponding to /blog slir and /blog SLC while this
works for simple cases using predefined Parts isn't always practical for complex
applications let's dive into scenario 4 to understand why in this scenario we're
building a product listing and Details page when the user visits SL products they
should

00:22:24
see a list of three products however when they navigate to/ product products
followed by the products idid they should see details for that specific product for
example navigating to/ products SL1 should display details about the first product
SL products SL2 should display details about the second product and so on let me
show you how we can implement this in nexs first let's create a products folder in
our app directory new folder products inside it we'll create a page. TSX file this
file will contain a react component

00:23:01
that displays a list of three products so export default function product list and
we return an H1 that says product list and three H2 for product one 2 and three if
you head over to localhost 3000 SL products you will see our product list that is
part one done now based on what we have learned about nested routes you might think
we could just create separate folders for each product right a folder for product
ID 1 a folder for product ID 2 and so on similarity first and second in our block
folder let's try

00:23:42
that approach first we'll create a folder named one in our products directory and
add a page. TSX file here we will default export a react component that displays
the text details about the product using an H1 tag export default function product
details returns and each one details about product sure enough if we visit Local
Host 3000 SL products SL1 it works but here's the thing imagine having hundreds of
products creating a folder for each one would be a maintenance nightmare this is
where Dynamic rout segments come in

00:24:22
handy first delete this one folder and instead we will create a special folder with
square brackets so Within products new folder square brackets we'll call it product
ID I'm using product ID instead of just ID because it is more descriptive inside
this folder we will create our page. TSX file we will default export the same
component export default function product details returns an each one tag details
about product but now something cool happens when you refresh the browser and visit
SL

00:25:00
products SL1 we will see the product Details page visit SL products SL2 SL product
sl3 even SL product sl100 they all work that is because Nexus treats a folder name
in square brackets as a dynamic segment making our routes Dynamic and flexible
product ID here refers to product ID 1 to 100 and so on but showing this same text
for every product isn't very useful in a real app you would probably fetch product
details from an API based on this product ID for now let's at least show which
product we are looking at now

00:25:44
every page in the app router receives route parameters through the params prop
let's destructure it as params the type of params is a promise that results to an
object containing the dynamic segments as key value pairs in our case that is
product ID the name of our folder the nice thing about server components is that we
can use async AIT to resolve the promise and access the dynamic segment so export
default async function product details and within the component const product ID is
equal to

00:26:23
AWA params and access product ID display the product ID in the UI now when you
visit SL product1 you will see details about product one and/ products sl100 shows
details about product 100 and remember the ID doesn't have to be a number it could
be a string for example products SL iPhone and we see details about product iPhone
scenario 4 has been successfully implemented let me summarize what we have built
we've created a folder with square brackets containing product ID anded . TSX
inside it and nexts now Maps

00:27:02
any SL products slid URL to this file inside the component we grab the product ID
from the parms prop to show Dynamic content here is a visualization of dynamic
routes page. TSX within the app folder corresponds to the root route page. TSX
within the products folder corresponds to/ products and page. TSX within the
product ID within square brackets folder corresponds to a dynamic segment SL1 SL2
sl00 and so on this pattern is super useful for building list detail views in your
application whether you're building an e-commerce

00:27:40
site with millions of products a Blog with a few hundred block post or any app that
needs Dynamic routing this approach will serve you well let's build on our
knowledge of dynamic routes and dive into nested Dynamic routes in real world
applications you will often come across scenarios where you need to handle multiple
Dynamic segments in your routes consider scenario 5 you want to show product
details at/ products1 but you also need to display the first review for that
product at/ products1 SL reviews SL1 let me show you

00:28:17
how to set this up with the app router previously we set up the dynamic product ID
route that is why/ product1 already shows product details now let's tackle SL
products SL1 SL reviews SL1 if you're comfortable with file based routing by now
this next part should click right away when we are dealing with multiple path
segments we need to think in terms of nested folders here's what we will do first
inside the product ID folder create a reviews folder this gives us slash products
SL product id/ reviews but we are not done

00:28:57
yet we also need a dynamic review ID so inside this reviews folder create another
folder named review ID within square brackets within this folder create a page. TSX
file here let's define a react component that shows both the product ID and review
ID so export default async function product review and we restructure route params
params is of type promise that results to product ID which is of type string and
review ID of type string product ID and review ID correspond to product ID are
Dynamic

00:29:37
route and review ID are Dynamic route as well within the component we destructure
product ID and review ID by awaiting params we then return in each one review
review ID followed by for product product ID now for the fun part in the browser
navigate to localhost 3000 SL products1 SL reviews SL1 and you will see exactly
what we wanted review one for product one try changing the URL maybe go to product
100 and review ID five watch those IDs update in real time review five for product
100 we have successfully implemented scenario 5 here

00:30:26
is a visualization to help you picture these nested Dynamic routes page. TSX within
the app folder corresponds to the root page. TSX Within products corresponds to/
products p. TSX within product ID corresponds to/ one we don't have a list review
route and we skip to review ID where page. TSX corresponds to the review ID one SL
products1 SL reviews SL1 the key takeaway here is that you can create nested
Dynamic routes simply by using d DC segments with nested folder names but here is
something interesting nexs actually has

00:31:04
another way to handle multiple Dynamic part segments before we dive into that I
have an exercise for you implement a review listing page for each product so create
a page. TSX file in the reviews folder and list a couple of reviews let me know how
that goes in the comment section let's dive into another powerful routing concept
called catchall segment to understand this better consider scenario 6 imagine we're
building a documentation site for our project this site has multiple features and
each

00:31:38
feature contains several Concepts that need documentation picture a side navigation
with five features where the first feature expands to show five different concepts
the goal is to create unique routes for each concept under its respective feature
think about URLs like localhost 3000 do/ feature 1 SL concept 1/ do/ feature 1/c
concept 2/ do/ feature 2/ concept 1 and so on now if we have 20 features and each
feature has 20 Concepts we looking at 400 different routes since nexs uses file
system based

00:32:17
routing that would mean 400 separate files in a project but here's where Dynamic
routing comes to the Rescue by using Dynamic route folders with a concept ID we can
cut that down to just 20 files take it a step further by making the feature folder
Dynamic with a feature ID and we are down to just two folders one for feature ID
and one for concept ID much better right but there is still a catch every time we
add A New Path segment to our URL like SL docs SL feature one SLC concept one SL
example

00:32:52
one we need another level of nesting in our routes folder since every page in our
documentation shares the same layout wouldn't it be great if we could handle all
these route segments with just one file that is exactly what catch all segments
feature lets us do let me show you how to set it up in your app folder create a
docs folder inside that create another folder with a special nexs naming convention
use square brackets with three dots like the spread operator followed by a name we
will use use slug

00:33:29
since that is a common term for URLs then create a page. TSX file within the slug
folder default export a react component so export default function talks that
returns an H1 tag talks homepage the magic of this file is that it matches any URL
with DOs in the path try it out whether you visit SL dos SL feature 1/c concept one
or even SL do/ feature oneconcept one SL example one you will see the same docs
page that is the catch all segments route in action it captures all URL segments
and handles them in the

00:34:16
single file this is perfect for documentation sites where you want different URL
segments for organization and SEO but keep the same basic layout of course you'll
want to access the different URL segments in your code let me show you how to do
that using the params object we destructure params from prop and params is of type
promise we have slug which is an array of strings within the component D structure
slug from params by awaiting it make sure your component is an async function for
the jsx we will use any Els block to

00:34:54
handle the different possibilities so if SL exists and the length is equal to two
return an H1 tag viewing dogs for feature slug of zero and concept slug of one else
if slug exists and the length is equal to one we return an H1 tag weing dogs for
feature slug of zero pretty simple in the browser navigate to SL docs SL routing
and you will see viewing docs for feature routing navigate to/ docs sl/ routing SL
catch all segments and you will see viewing docs for feature routing and concept
catch all segments you can customize

00:35:46
this UI logic however you need but typically you would use the slug array to fetch
the right documentation for each feature or concept scenario 6 has been
successfully implemented now next also offers optional catchall segments right now
if you navigate to just SL Docs in the URL you will see a 404 error but if you want
to show the same docs page here too just wrap your folder name in an extra pair of
square brackets so rename the slug folder and wrap it with an extra pair of square
brackets this
00:36:21
makes the slug segments optional and now slash docs will work as well triggering
this last return statement now you might be wondering when should you use a simple
page. TSX in the docs folder versus the optional catchall page. TSX since both of
them render UI for/ docs in the URL well it is straightforward if your page UI is
always the same the simple page. TSX in the docs folder if your page UI is
different based on the URL for example as it is the case in our current scenario
then use the optional catch all

00:37:00
route page. TSX within slug folder as opposed to page. TSX directly within docs
folder here is a visualization of catchall segments lical host 3000 will render
page. TSX in the app folder for any URL that contains docs we render page. TSX in
the slug folder which is our catchall segment all right that is a comprehensive
look at cashall segments we have covered a lot about next year's routing but
there's still more to explore let's continue with the next topic let's explore how
to create a

00:37:36
custom 404 page using the app router by default when you visit a route that doesn't
exist in your app folder you will see a basic 44 page try visiting localhost 3000b
building to see what I mean while this default page works fine for development you
would probably want to customize it for your production site the good news is is
super simple all you need to do is create a file called notfound DJs or notf found.
TSX if you're using typescript in your app folder let me show you how first in vs

00:38:11
code create a new file in the app folder called not found. TSX not hyphen found.
TSX remember the file name must be exactly not hyphen found this is a next year's
convention here Define and export a react component so export default function not
found and we return a div tag with an H2 heading that says page not found and a
paragraph tag could not find requested resource feel free to style this component
however you want I'm keeping it simple here since we are focusing on the concept
rather than

00:38:49
styling if you refresh your browser now you will see the custom not found page
instead of the default one page not found could not find requested resource this
file is particularly useful for production sites where you want your 404 page to
match your sites branding and design but here is something cool while this noton
page works automatically with next year's file based routing you can also trigger
it programmatically using the not found function let me show you an example let's
say we are building a

00:39:22
product review system where we will never have more than 1,000 reviews and and we
want to show a 404 page for any review ID above 1,000 so in the review ID folder
page. TSX file import the not found function from next SL navigation then within
the component if parse int review ID is greater than 1,000 call the not found
function and while we are at it here is another neat feature you can actually
create specific noton Pages for different sections of your app for example in the
review ID folder you
00:40:05
can create another notf found. TSX file with more specific messaging so I'm going
to copy our notfound file from the app directory paste it inside the review ID
directory and change the messaging review not found in the browser when you visit
slash products slash1 slre reviews sl1000 And1 you will see this more specific
review notfound page instead of your Global 404 page this is because next we use
the most specific not Fon page it can find in this case the one in the review ID
folder rather than the one

00:40:45
in the app folder one thing to keep in mind though is that the not found component
does not accept props you might be wondering what if I need to show different
messages based on the route parameter for that we will rely on the use path name
Hook from nexs let's import it and invoke it within our not found component import
use path name from next SL navigation and then within the component const path name
is equal to use path name however when we save this file we encounter an error
you're

00:41:24
importing a component that needs use path name the this react hook only works in a
client component to fix Mark the file or its parent with the used client directive
if you remember from earlier I mentioned that in the new react server component
architecture all react components are server components by default and hooks can
only be used inside client components so let's follow the instruction to fix the
eror add use client at the top of the file within quotes use client our not font
component

00:41:56
is now a client component component you can access the path name constant within
the component and extract the route parameters from it so const product ID is equal
to path name. spit on forward slash we access at index 2 similarly review ID is
going to be path name. split at for Slash and access index 4 now we can display the
extracted values within the components jsx review ID not found for product product
ID in the browser you will see the message review 1,00 and one not found for
product one all right that is

00:42:39
everything you need to know about the not found file and function in nexs app
router while nexs gives us some routing conventions to follow it's actually pretty
flexible about how you structure your project files and folders let's take a look
at file collocation in nexs you already know that nexs uses a file system based
router each folder represents a route segment that maps to a URL path but here is
the important part a route only becomes publicly accessible when you add a page.js
or page. TSX file to it let me show you

00:43:17
what I mean let's create a new folder called dashboard in our app directory inside
it we'll create a file called linechart do TSX here we will Define a simple react
component default function line chart which returns an each one tag line chart now
if you try going to slash dashboard in your browser you will get a 404 page not
found error why because we haven't added a page. TSX file yet that is what makes a
route accessible let's create page. TSX now here is another interesting thing
00:44:00
even when a route is public with a page. TSX file the browser only gets what is
returned by page. DSX and it has to be a default exported react component let's see
what happens if you create a component without making it a default export a
function bar chart that returns an each one bar chart in the browser you can see
the 404 page go away but you will see an error saying the default export is not a
react component in/ dashboard SL page let's fix this by adding a proper default
export to our

00:44:37
component so export default function dashboard that returns in each One dashboard
now when you visit the browser and refresh you will see dashboard appear notice
that the bar chart component still isn't showing up so what is the key takeaway
here you can see safely collocate project files inside route segments in the app
directory without worrying about them accidentally becoming routes themselves by
the way while you can keep your files in the app directory you don't have to some
developers prefer to keep their files

00:45:14
outside the app directory maybe in the source folder with a separate components
folder for all their UI components shatan Library does this for example and that is
totally fine too nextjs also gives us two more cool features to help organize our
project let me show you those next we just learned about safe collocation of files
which NEX handles right out of the box now let's dive into another cool NEX feature
private folders this will help you keep your project super organized so what is a
private

00:45:49
folder think of it as a way to tell nexts hey this folder is just for internal
stuff don't include it in the routing system the folder and all its subfolders are
excluded from routing to create a private folder just add an underscore at the
start of the folder name let me show you how this works in your app folder create a
folder called underscore lib this is where you might put utility functions like
format date.js or. TS if you're using typescript we will skip the implementation
details for now but here

00:46:26
is what I really want to show you let's create a page. TSX file inside this undor
liip folder with a simple react component so new file page. TSX export default
function private route and return an H1 tag you cannot view this in the browser now
you might think this would show up at localhost 3000 slore lib but it won't the
underscore incore lib makes it a private folder so next year won't create a route
for it try navigating to slore lib in the browser and you will get a 404 error page
not found could not find requested

00:47:07
resource this is the custom 404 page we defined earlier private folders are super
useful for a bunch of things keeping your UI logic separate from routing logic
having a consistent way to organize internal files in your project making it easier
to group related files in your code editor and finally avoiding potential naming
conflicts with future next year's file naming conventions and here is a quick Pro
tip if you actually want an underscore in your url use percentage 5f instead that
is just the URL encoded version of an
00:47:44
underscore try switching underscore with percentage 5f and see what happens in your
browser let me know in the comment section if you can view ph. TSX in the browser
private folders is just one of the ways to organize your next year's project if
this is not your cup of tea you can always choose to not use the feature and simply
rely on file collocation or even Place files outside of the app folder up next we
will check out another awesome feature nexts gives for project organization let's
dive into another

00:48:19
powerful feature nexs offers for organizing our projects route groups this feature
lets us logically organize our routes and project files without impacting the URL
structure it is also worth noting that route groups are actually the only way to
share a layout between routes without affecting the URL let's see rout groups in
action by implementing some authentication routes we will build routes for register
login and forgot password first head over to your app folder and create three
folders

00:48:53
register login and forgot password in each folder we will Define a page. TSX file
with a simple react component with a heading so register page. TSX export default
function register which returns an H1 tag register copy page. TSX from register
folder paste it in the login folder and change register to login similarly paste
page. DSX in forgot password and change component name to forgot password password
in the browser visiting localhost 3000 SL register shows register slash login shows
login and slash forgot password

00:49:40
shows forgot password now this works but there is a problem our authentication
routes are scattered throughout the app folder while this might be fine when you're
working solo and know all the authentication routes it does become challenging in
the team environment let's improve the developer experience by grouping related
routes together we can do this by creating an au folder to house all our
authentication related routes let's try it create an au folder inside the app
directory and move the

00:50:12
register login and forgot password folders inside it so register move it inside o
update Imports move login inside Au update import and move forgot password inside o
update Imports and save the changes the project structure looks much cleaner now
right but if you check your browser you will notice the routes are broken SL
register login and forgot password all return 404 this happens because nxs
automatically Maps nested folders to URL pods so now we have au/ register a/ login
and au/ forgot password while

00:51:02
this URL structure might work for Au routes it might not be ideal for other groups
like marketing or analytics this is where route groups come in handy to create a
rout group we simply wrap the folder name in parenthesis so rename o folder add
parenthesis and O inside it this tells next to treat this folder as an organization
tool only excluding it from the URL path if you have trouble renaming the folder
stop the dev server with contrl C rename the folder and restart the server with npm
runev check
00:51:39
your browser again localhost 3000 register we see register page SL login login page
and forgot password we see the forgot password page but now our code is neatly
organized and if you need more organization you can even Nest route groups within
each other that wraps up our exploration of routing with pages in the app router up
next we will explore layouts in detail we've explored pages so far which are route
specific UI components now let's dive into layouts a layout is UI that is shared
between multiple pages in

00:52:20
your application think of it like having a consistent structure such as a header
and footer that appears on on every page next makes it super easy to implement
creating a layout is straightforward you just need to default export a react
component from a layout. JS or layout. TSX file that component takes a children
prop which next will populate with your page content let's look at this in action I
should mention that we don't need to create a layout from scratch because nexts
provides one by default in

00:52:53
your app folder you will find layout. TSX like page. TSX this follows next year's
special file naming conventions this layout. TSX file in the app folder is called
the root layout and it is not optional every Nexus app must have one in fact Nexus
is so insistent about this that if you delete it it will automatically regenerate
the file let me show you delete move to trash refresh Local Host 3000 in the
browser and look at that the has already recreated it let's understand the code
here we'll

00:53:32
talk about the metadata object later but for now let's focus on the react component
every layout component needs a children prop this is where your page content will
go in our case the page. TSX in the app folder becomes the children when layout.
TSX renders if you inspect the elements in Chrome Dev tools you'll see and an HTML
tag with language is equal to English matching our layout and a body tag containing
an H1 tag welcome home that is coming from our page. TSX component through the
children

00:54:12
prop right now our layout isn't doing much let's make it more useful by adding a
header and a footer I will piece the code since this is basic HTML and CSS so we
have the header tag with style background color light blue padding one REM with a
paragraph tag that says header we then have the footer element with style
background color Coast white panning one REM with a paragraph that says footer
sandwiched in between header and footer is our children props really simple HTML
and CSS although we could

00:54:50
make separate components for the header and footer we are keeping it simple with
placeholder text and basic styling for now take a look at the browser and you will
see the header and footer the cool part is that these stay in place no matter which
route you visit try going to slash about or slash products the header and foter
remain constant that is the power of the root layout. TSX file it creates a
consistent structure across your entire application you can add whatever markup
Styles or behavior you

00:55:25
want to just remember to include the children prop so your pages can render their
unique content here is a visualization of how layouts work in the app router when
you visit localhost 3000 the rude layout component in layout. TSX in the app folder
gets rendered this contains a header at the top a footer at the bottom and the
children prop in between the children prop gets replaced by the component defined
in page. TSX within the app folder when you visit Local Host 3000 slout the
component defined in page. TSX

00:56:01
within the about folder replaces the children content in the layout file and when
you visit localhost 3000 SL profile the component defined in page. TSX within the
profile folder replaces the children prop in the layout file I hope this helps you
understand layouts better now here is a quick challenge before we proceed try
creating your own header and footer components and add them to the root layer out
drop a comment to let me know how it goes up next we will explore nested layouts
previously we explored layouts

00:56:37
these handy UI components that are shared between multiple pages in your
application every app needs a root layout which in our case lives in the layout.
TSX file in the app folder now here is something cool about layouts you can Nest
them let's say you want a special layout just for your product details pages we can
do that by adding a layout. TSX file inside the product details folder let me show
you how in the product ID folder create layout. TSX file here Define and default
export a react component so export default

00:57:15
function let's call this product details layout the component accepts children prop
of type react. react node and we return the children prop along with and H2 that
says featured products so just like the root layout we're exporting a react
component with a children prop but this time the children prop represents the
product ID page content details about product followed by product ID I've also
added a simple H2 heading that says featured products think of this as a spot where
you might want to show a

00:57:51
carousel of featured products let's see how this works back in the browser when you
visit the rout route so Local Host 3000 you will only see the root layout header
footer and the children content from page. TSX in the app folder same thing happens
when you visit SL products header footer and the product list component as children
but here is where it gets interesting when you navigate to a specific product so/
products SL1 you will see that featured products section appear for slash1 slash2
and even

00:58:30
sl00 this happens because first nexs renders the root layout with the children prop
representing the product ID folder content then the product IDs layout kicks in
replacing the children prop in the root layout we will see featured products
finally the actual page content from page. TSX in the product ID folder fills in
the children prop in the product ID layout this pattern gives you the power to
create specialized layouts for different parts of your application here's a
visualization of nested layouts in the app router for

00:59:08
lost 3000 layout. TSX file in the app folder gets rendered for/ products the
component in page. TSX in the products folder replaces the children prop in the
root layout when you visit SL product/ one TSX the component in layout. TSX becomes
the children prop in the root layout the product details layout contains the
featured products and then the component from page. TSX gets rendered as the
children prop in the product ID's layout. TSX file so we see the header and footer
and sandwiched in

00:59:44
between we see the layout and Page components from product ID when you navigate to/
product SL2 only the page. TSX content gets replaced with the updated JSI the key
takeaway here is that nexs app router supports nested layouts letting you customize
different parts of your app exactly how you want to now you might be wondering what
if I want to exclude the header and footer from certain pages for Pages like login
register or forgot password you may want a cleaner more focused layout well don't

01:00:19
worry there is a straightforward solution for this which we will explore next
before we start I just want to mention that I have switched to a fresh next year's
project just for this topic to make this super easy to follow now imagine we're
building an app with routes for Revenue customers login and register all of which
have already created behind the scenes we want our revenue and customers pages to
have a nice header and footer but we want to keep our login and register Pages
clean and minimal here's the challenge though

01:00:55
if we add a header and footer in the root layout. TSX file they will be applied to
every single page in our application there's just no way around it but what if you
want different layouts for different parts of the app this is where multiple root
layouts come into play now you might be thinking how can we have multiple root
layouts isn't there supposed to be only one in the app folder this is where route
groups really shine remember how route groups help us organize our project
structure without

01:01:27
affecting URLs well they also let us apply layouts selectively to specific parts of
our application let me show you how first create two route groups in the app folder
first marketing for revenue and customers let's move those folders and then another
route group Au for login and register let's move them as well next we will take our
root layout. TSX file and move it from the app folder into the marketing route
group move it update Imports and change the name to marketing layout it is very
important

01:02:14
that the root layout does not exist in the app folder anymore we will create
another layout in the a folder so copy paste the layout file and rename this to Au
layout and here let's get rid of the header and only have the footer when you save
the files and check this out in your browser you will see an error page. TSX
doesn't have a root layout and this is the page. TSX file in the app folder all you
have to do is move this into the marketing route group now page. TSX corresponds to
localhost 3000 and it

01:02:52
does have a root layout file to work with but in the browser you you will see
something cool the URLs haven't changed at all but now the register and login Pages
have only the footer in the layout whereas customers and revenue has both header
and footer we able to Define multiple root layouts that affect specific parts of
our application this is what makes route groups so powerful in next sh they give us
the flexibility to create different user interfaces for different parts of our app
all while keeping our code

01:03:28
organized and maintainable all right now that you're comfortable with how
components work in a layout let's dive into something else that is interesting this
metad dat object that is sitting right above it we will switch back to the route
demo project to understand this better let's talk about search engine optimization
and how ni shares can help us get it right the metadata API in XS is a powerful
feature that lets us Define metadata for each page making sure our content looks
great when it is

01:04:00
shared or indexed by search engines the app router gives us two ways to handle
metadata in layout. TSX or page. TSX files you can either export a static metadata
object or export a dynamic generate metadata function before we dive in here are
the key points you need to know about configuring routing metadata both layout. TSX
and page. TSX can export metadata layout metadata applies to all its Pages while
page metadata is specific to that page metadata follows a top- down order starting
from the root level when

01:04:35
metadata exists in multiple places along a route they merge together with page
metadata overriding layout metadata for matching properties let's jump into vs code
and start with the static metadata object approach we will keep the existing metad
data in root layout TSX file title nexs description generated by nexs in our about
routes page. TSX export a metadata object so export const metadata with the title
property set to about code Evolution while both layout and Page can have metadata
the pages metadata takes

01:05:18
priority when they overlap let's check this out in the browser looking at the home
pages elements panel you will see that title next sh and description generated by
NEX sh this comes from our layout. TSX metadata now when we go to localhost 3000
slab notice how the title changes to about code Evolution while keeping the same
description generated by next shares this happens because when routes have multiple
metadata objects they merge together with deeper segments taking priority since
about pach is

01:05:57
deeper than the root layout its title overwrites the layout's title about code
Evolution overwrites nextjs the description stays the same because it wasn't
overwritten it was never defined in page. TSX this pattern works the same way no
matter how deeply nested your layouts and pages are and this is how static metadata
object configuration Works in nextjs next let's take a look at Dynamic metadata
this comes in handy when your metadata depends on Dynamic information like current
route parameters external data

01:06:33
or metadata defined in parent segments you can Define it by exporting a generate
metadata function from a layout. TSX or page. TSX file perfect example is a dynamic
route like product ID instead of having the same title for every product which
would happen with a static metadata object we can make un for each product here's
how we set up the generate metadata function in page. TSX first we'll create our
component props type so type props is equal to params which is a promise that
resolves

01:07:11
to product ID of type string and then we will use this type with our component so
params of type props finally we will Define the generate metadata function at the
top import the metadata type from next then export a function called generate
metadata exactly this name and this is an async function the function receives
params of type props and returns a promise of type metadata within the function
body we await params and access product ID we assign it to a constant called ID and
we return a metadata object with the title

01:07:59
set to product followed by the product ID now if we head back to the browser and
visit SL products SL1 inspect the title we can see it is product one navigate to
sl00 and we can see the title product 100 for this simple example we're using the
product ID directly in our title however in a real e-commerce application where you
might have a product catalog you could fetch the product details within this
function and set the title accordingly we don't have an API to work with so we will
keep it simple and

01:08:35
return a promise that results in 100 milliseconds so const title is equal to await
new promise which will resolve after 100 milliseconds so set time out resolve let's
assume the title fetched is the word iPhone followed by the ID we return title
product followed by title in the browser if we navigate to/ products sl6 we can see
the title is product iPhone 16 this is how you configure Dynamic routing metadata
in next shares one important point I should mention is that you can't use both a
metadata

01:09:20
object and generate metadata function in the same route segment it is one or the
other and before we move on there is one crucial limitation you need to be aware of
when working with metadata it will not work in pages that are marked with the use
client directive let me show you what I mean I'm going to create a new route in the
app folder called counter I'm going to create a page. TSX file that default exports
a simple counter component count State variable set a function button on click to
increment

01:09:55
the count since the component uses react hooks I will mark it with the use client
directive at the top I will also set the title to counter in the metadata object so
export const metadata it's an object with title set to counter in the browser when
you navigate to the route SLC counter you will encounter an error you're attempting
to export metadata from a component marked with use client which which is
disallowed either remove the export or the use client directive you will encounter
the same error even if

01:10:32
you export the generate metadata function the solution is to keep your metadata in
server components and extract any client side functionality into separate
components so let me show you the correct pattern in the counter folder create a
new counter. TSX file and move the client side logic from page. TSX into counter.
TSX I'm going to copy the code paste it here remove the metadata object and rename
the component to counter as a named export it doesn't have to be a named export but
I prefer

01:11:07
my components to be named exports in the counter routes page. TSX file we can now
import the counter component and return it so return counter and make sure to
import the counter component at the top remove the use client directive the use
State hook but leave the metod data object as it is now when you refresh SLC
counter route you will see the counter title and the page renders without any
errors you also see the same title in the browser tab counter this is the
recommended way to handle metadata in

01:11:44
client components let's dive deeper into the title field in metadata which plays a
crucial role in routing the title Field's main job is to Define your document title
and you can set it using either a string or an object let me show you both
approaches the simplest way to set the title is with a string value this is what
we've been doing in our layout. TSX and page. TSX files when we set the title to
about code Evolution it renders exactly that string in the browser's title tag but
what if you need more

01:12:19
control that is where defining the title as an object comes in handy it might seem
complex at first first but you will get the hang of it all right in your root
layout you will first want to import and use the metadata type for better
typescript support import metadata from next metadata is of type metadata Now when
using the object approach you get three powerful options template default and
absolute let's start with default the title. default property acts as a fallback
for any child routes they don't specify their

01:12:56
own title for instance if we set the value to next year's tutorial hyphone Cod
Evolution and you have a page like appblog SL page. TSX without a defined title it
will automatically use this default title in the browser navigate to/ blog and we
see the title next tutorial code Evolution the default value is the fallback value
next up is the template option this is really useful when you want to add
consistent prefixes or suffixes to your titles this property applies to child
routes we will set it to percentage s the pipe

01:13:37
character and code Evolution now in the blog page if you set the title to blog so
export const metadata title set to blog the output is blog pipe code Evolution the
child page title which is blog replaces percent s in the layout template this
pattern is particularly useful in multi-page applications where you want consistent
title formatting across your site lastly we have the absolute title option
sometimes you might want to break free from the template pattern set by parent
segments that is exactly what title.

01:14:16
absolute property does remove this property from the layout file and add it to the
block page title is an object and we set absolute the value is the string blog and
here is what we get just blog nice and clean and we are breaking away from the
pattern set in layout. TSX F title. absolute overrides the parent segments title
all right that covers everything you need to know about routing and SEO metadata in
next year up next we will explore linking and navigation with the app router
previously we go into the file

01:14:56
based routing system in XS we covered defining routes for our applications route
nested routes Dynamic routes and catch all routes while we've been typing URLs
directly in the browser to test these routes that is not how real users navigate
websites instead they click on links or get redirected after certain actions let's
see how to implement this in next sh first up let's look at navigating from the
homepage to the blog page when clicking a link for client side navigation next
shares gives us the

01:15:28
link component the link component is a react component that extends the HTML anchor
element and it is the primary way to navigate between routes in nexs to use it we
will need to import it from next /link in our root page. TSX file in the app folder
let's start by importing the link component import link from next SL link now we
can add the link component to navigate anywhere in our application here's the
syntax I'll wrap the H1 tag with react fragment and add a link right below the

01:16:02
heading the text is blog href is equal to/ blog by using the link component with an
href prop we create clickable navigation elements in this case we are showing blog
as the text and when clicked it will take us to SL blog save this head to the
browser and you will see a clickable blog link that takes you right right to the
block page let's add another example to make sure we've got this down we will
create a link to the products page right after our blog link so link component the
text is products

01:16:38
and the HF is SL products simple right back in the homepage refresh and we see the
products link clicking it takes you to SL products where we see the product list
component both our links are working smoothly now it's always good to help users
get back to the homepage let's add a home link in our products list Page open page.
TSX file in your products folder and import the link component import link from
next slash link then add a link to the homepage in the jsx the text is home and hre
is

01:17:15
forward slash this points to our applications route now when you're on the products
page you will see a link to take you back home next let's tackle some something
more interesting Dynamic routes in our products page we have three products listed
we can turn each products heading into a link to its Details page remember how our
Dynamic routs are SL products SL product ID for example SL products SL1 well here
is how we Implement that as a link within h two link component product one becomes
the

01:17:51
text and each ref is equal to SL SL product SL1 similarly Product 2 and product 3
in the browser you should see the products linked to their respective details Pages
product one details about product one two and three while hardcoding these links
works sometimes we need to generate them dynamically let's say we have a product ID
coming from somewhere else so const product ID is equal to 100 the value could be
from a prop for example we can use template literals to create link using this
product ID I'm going to duplicate the H2

01:18:33
heading and bind this product ID the hre we're going to use backx which is the key
below Escape key make sure to wrap it within curly braces and then dollar curly
braces product ID this creates a dynamic link showing product 100 that leads to the
corresponding product page now here is something I want to highlight about the link
component it has a replace prop that changes how navigation history Works let's add
it to product 3's link component now try this back in the browser from the homepage
click on

01:19:11
products click product one and then hit back Works normally same with product two
Details page and we go back but with product three we navigate to The Details page
but when I hit the back button it takes you straight to the homepage skipping the
product list that is because replace overrides the current history entry instead of
adding a new one this is something to keep in mind the link component makes client
side navigation a breeze in xjs just import it from next SL link add your href and
you're good to

01:19:50
go previously we learned about the link component for navigating between routes now
let's tackle something we haven't covered yet styling active links you know how
most websites highlight the current page you're on in the navigation menu well
we'll build exactly that it is not just about Aesthetics it helps user understand
where they are in your application and is very important to save time and get us
started I have already prepared some code in our o route group I've created a
layout. TSX

01:20:22
file with a nav links array containing three items register login and forgot
password each has a name and a corresponding href property the layout component
Maps over these links and renders them using NEX jss link component if you head
over to/ register in the browser you will see all three links in the a layout you
can click between them and they will stay visible throughout register login and
forgot password now let's make them show which one is active next next shs gives us
the use path name hook to help us figure out

01:20:58
which link is active let's bring that in at the top import use path name from next
snation and use it in the a layout component the const path name is equal to use
path name when we save the file we encounter an error we've seen before remember
how server components are default in XS well hooks only work in client components
so we need to add to use client directive at the top of our file perfect now that
is fixed let's use the path name constant it gives us the current URL path so slash
register for

01:21:39
the register route SL login for the login route SL forgot password for the forgot
password route and so on these match up with the each values in our nav links array
so inside the map method we can add const is active is equal to path name being
equal to the links H ref or path name do starts with link hre and link. hre is not
equal to the root route next it's time to add some styles on the link component
let's add a class name with a conditional so if is active is true we specify font
bold and margin right four

01:22:23
if it is not active we specify F text blue 500 and margin right four these are
Tailwind CSS classes font bold makes the text bold and text blue 500 gives us a
nice blue color mr4 adds some breathing room on the right if you check the browsers
elements panel you will see the active link has the font bold class while the other
links have text blue 500 we are currently viewing SL forgot password so forgot
password is our active rout out but wait the Styles don't seem to be visible in the
browser

01:22:59
this is because we removed the global CSS file earlier no worries let's create a
styles. CSS file in the odd folder and add tailn CSS base components and Utilities
in the layout. TSX file import the styles.css file or if you prefer you can also
bring back the global CSS file from earlier either way works now head back to the
browser and you can see the current route forgot password is Bold and the other
links are blue click login and The Styling changes that is all it takes to style
active links in next

01:23:41
shs let's dive into params and search params in nexts if you're working with
navigation you will definitely need to understand these two concepts in simple
terms for a given URL params is a promise that re resols to an object containing
Dynamic route parameters like ID for example search patterms is a promise that
resols to an object containing the query parameters like filters and sting to
understand this better let's build a simple news article page that supports
multiple languages

01:24:12
first let's look at how to create links with both parms and search parms in the
home component add two links the first one says read in English and href is SL
articles SL breaking news1 23 question mark language is equal to English I'm going
to duplicate this link change the text to read in French and change language to FR
FR here breaking news 1 to3 is the dynamic route parameter and language is the
query parameter next let's define a route for the Articles we've done this before
so

01:24:51
in the app folder create a folder called articles and inside it create another
folder called article ID this time within square brackets inside the folder create
a page. TSX file and Define the newest article component export default function
news article and for the jsx render an H1 tag with the text news article followed
by ID and a paragraph with the text reading in language I will then add a language
switcher with links to switch the language so import the link component from next
SL link and

01:25:33
invoke it language is going to be English and hre is going to be/ articles / ID
question mark language is equal to n similarly we will create Spanish and French
with language is equal to es and fr FR in the browser when you click the link L
read in English the news article component gets rendered we have breaking news 123
which is the route parameter and L is equal to I which is the query parameter go
back click on read in French and we see the same component with language is equal
to F FR our next

01:26:13
step is to access the value of patterms and search patterms in the news article
component and display them in the UI replacing ID and language begin by
destructuring the parms and search parms from the props parms is a promise that
resolves to an object containing the dynamic route parameters in our case article
ID is the dynamic route parameter this is of type string search params is a promise
that resols to an object containing the query parameters Lang is the query
parameter and the value can be English Engish

01:26:55
Spanish or French also make it optional since parms and search PMS are promises you
will need to aade them in the component add the ASN keyword to the function and
aade the parms and search patterns get hold of the article ID from params and
language from search params with the default value of English now replace the
placeholder text in the jsx with the values of article ID and language for the
links use PEX instead of double quotes and interpolate dollar ID so article ID
across all three links head to the

01:27:46
browser and we see the values rendered in the UI news article breaking news 123
reading in French click on the Lang language links and you will see the language
changes I should point out that you're able to await and access parms and search
parms in the news article component because it is a server component if this was a
client component you would get an error as client components do not support async a
and use client at the top and you will see the issue now to access the values of
patterms and search patterms in a client

01:28:23
component you will need to use a hook from react which is the use hook so remove
async and await and instead import use from react invoke this hook passing in
params and search params head to the browser and you can see the component
continues to work as expected so async await for sever components but use hook for
client components that is how you access patterms and search patterms in nures Now
One very important point to note is that while page. TSX has access to both
patterms and search patterms layout. TSX only has access to
01:29:03
patterms search patterms are not available in layout components as an exercise
Define a layout component and try to access search patterms in it and let me know
in the comments below what happens while links work great for most cases sometimes
we need to navigate programmatically think about when you're shop on Amazon after
you submit your order you're automatically redirected to an order confirmation page
this kind of programmatic navigation is essential for form submissions and many
other real

01:29:37
world scenarios let's dive into how we can achieve this using nexs App router for
our example we'll keep things simple even though we don't have a full e-commerce
site we will create a basic scenario where clicking a place order button in the
order product page P navigates us to the homepage let's start by creating the order
product route in your app folder create a new order product folder and add a page.
TSX file with the basic react component export default function order product we
return

01:30:13
an H1 tag order product let's add a button to make things interactive rub the
heading with react fragment and add a button place order now we'll add a click
Handler to the button using onclick we will Define the handle click function which
logs a simple message to the console placing your order after our simulated order
placement you want to redirect the user to the homepage this is where the use
router hook comes in first import it at the top of your file import use router from
next SL

01:30:53
navigation and inside your component set up the router const Router is equal to use
router then use the push method to handle navigation so after console log router.
push and the path is the homepage in the browser if you navigate to/ order product
you will get an error because used router only works in client components add use
Cent directive at the top of your file to fix this you will now see your heading
and the place order button clicking the button will take you straight to the
homepage that is programmatic navigation in

01:31:34
action although we are using forward slash as our destination you can use any valid
route whether it is nested dynamic or even a catchall route sometimes you might
also want to replace the current page in the history stack instead of adding a new
entry for that use router. replace instead of router. push it is similar to using
the replace prop on a link component you can also use router doback to go back to
the previous page or router. forward to move forward in the history now there is
one more way to

01:32:09
handle programmatic navigation and that is the redirect function let's look at an
example using our existing product review component remember how we check if the
review ID is greater than 100 and show a not found page well let's redirect them to
the product list Instead at the top import redirect from next snation and instead
of calling not found we will call redirect with the destination route SL products
now when you visit localhost 3000 SL products SL1 SL reviews SL1 in fact instead of
seeing the not
01:32:53
found page you will be automatically redirected to the products list page a very
contrived example but it shows how we can use redirects in our application all
right now that we have covered linking and navigation in xjs let's dive deeper into
some of the related Concepts next let's look at another special file that nexs
provides in the app router the template file to understand template files better we
need to First Look at a specific behavior of layouts in our app router we have an
au route

01:33:27
group with a layout file that handles navigation between Three Links register login
and forgot password in this layout let's add an input element to collect some user
data first we will import UST state from react at the top and within the layout
component we will include a state variable input with a Setter function set input
and the initial value is an empty string for the jsx we will render an input
element whose value is equal to the state variable input and on change we call the
setter function e. target. value the

01:34:11
data we are collecting from this input element is not important we just need some
state in our component now let's check this in the browser navigate to/ register
and we should see our or layout the input element might not be visible due to
styling but I can confirm it is there I will type Cod Evolution as test input now
pay attention to what happens to this input value as we navigate from register
route to the login route notice how the state is preserved this happens because
layouts only Mount

01:34:48
the new page content while keeping common elements intact they don't remount shared
component which leads to better performance register login and forgot password are
the new pages that are remounted when navigating between them whereas the input in
the layout which is a shared component is not remounted this Behavior works great
for most cases however sometimes you might need the layout to create a fresh
instance for each child component during navigation this could be useful for
scenarios like

01:35:22
implementing enter or exit animations or running use effect hooks when routes
change this is where template Files come in handy as an alternative to layout files
templates are similar to layouts in that they are also UI shared between multiple
pages in your application the key difference is that whenever a user navigates
between routes sharing a template you get a completely fresh start a new template
component instance is mounted Dom elements are recreated state is cleared and
effects are resynchronized you can create a template

01:35:58
by exporting a default react component from a template. JS or template. TSX file
like layouts templates need to accept a children prop to render the nested do
segments to demo this we simply need to rename our layout. TSX file to template.
TSX back in the browser if we type code Evolution again and navigate to forgot
password you will see the state is reset this is the significance of the template
file in the app router it is worth mentioning that you can actually use both
layout. TSX and template. TSX files
01:36:38
together in this case the layout renders first and then its children are replaced
by template components output templates are not a common requirement and layouts
should be your go-to for shared UI however if a need does arise for you to use
templates You Now understand how to use them we have already explored several
special files like page. TSX layout. TSX template. TSX and not found. TSX now let's
look at another important one called loading. TSX this file helps us create loading
states that users see

01:37:14
while waiting for content to load in a specific route segment the loading State
appears instantly when navigating letting users know that the application is
responsive I and actively loading content let's head back to vs code to see how it
works creating a loading state is pretty straightforward you just need to add a
loading. TSX file in the right folder let's try this out for our blog route segment
within the block folder create loading. TSX default export a react component export
default function loading which

01:37:49
returns an H1 loading behind the scenes this loading . TSX file automatically wraps
the page. TSX file and its nested children within a react suspense boundary if
you're new to the concept of suspense don't worry about it in the browser if we
navigate directly to Local Host 3000 SL blog you might notice we don't actually see
the loading text that is because our Blog Page loads super quickly the blog page
content replaces the loading text in the blinker an ey but trust me it is working
to prove it

01:38:25
I'm going to introduce a delay with a promise that takes 2 seconds to resolve so
export default async function blog and we await a new promise which results after 2
seconds with then set timeout we call the resolve function I'm going to pass
intentional delay as the value that is returned from the promise now when we go
back to the browser and reload the blog page you can see the loading text for 2
seconds and after our promise resols it gets replaced with the blog page content
right now we are just showing basic

01:39:04
loading text but in real applications you can get creative with this you might want
to use skeleton loaders Spinners or even show a preview of what is coming like a
photo or title it is completely up to you how polished you want to make this just
remember to put the loading. TSX file in the correct folder there are two really
cool benefits of using loading UI first it gives users immediate feedback when they
navigate somewhere new this makes your app feel Snappy and responsive and users
know their click actually did something

01:39:39
second nexts keeps shared layouts interactive while new content loads this means
users can still use things like navigation menus or sidebars even if the main
content isn't ready yet the loading UI pattern makes sure these loading states
don't get in the way of the parts that are already working giving users a smoother
experience all right that is about loading. TSX for instant loading states in the
app router it is time to explore another crucial aspect of our application namely
error handling this is implemented

01:40:14
through a special file called error. TSX let me show you how it works right now
when we visit localhost 3000 SL product/ SL1 SL reviews SL1 everything works
smoothly we can see the first review of our first product this URL corresponds to
the page. TSX file in our review ID folder but let's be realistic things don't
always go perfectly Network requests might fail and data might be unavailable let's
simulate an error scenario in our review ID page to see how we can handle such
situations outside of our component I'll

01:40:54
create a function that generates a random integer between zero and whatever count
we pass in inside the component we will call this function with two as the argument
so the function will now return either zero or one if it returns one we throw an
error with the message error loading review if we refresh the browser a few times
we will eventually see an unhandled runtime error with our error message error
loading review this is in development mode let's see how this behaves in production
by running npm run build once

01:41:42
the build completes run the command npm Run start now when the error occurs after
refreshing a few times we get a generic application error a server side exception
has occurred and we will see our error message in the terminal error loading review
this isn't great for our users right the error message isn't helpful and worse an
error in our deeply nested review ID component breaks the entire application we can
do better by handling errors gracefully containing them to just the affected part
while

01:42:20
keeping the rest of our application running this is where error. TSX comes in handy
let's create one in our review ID folder so adjacent to page. TSX error. TSX here
we will Define a client component so use client directive at the top export default
function error boundary that returns a div tag error in review ID this component
acts as an error boundary around our page. TSX file it is very important to note
that error boundaries must be client components you will need to add use client at
the

01:42:56
top of the file contrl C and restart the dev server with npm run Dev refresh the
page until we hit the error now we see error in review ID which is the text from
error. TSX of course in a real application you would want to style this properly to
match your application's design but what is great as you might have observed is
that the rest of the application still continues to work we have the header the
featured products from our products layout and the footer only the review ID
component has been

01:43:30
replaced by the jsx defined in error. TSX now this component receives the error
object as a prop so error of type error we can use it to make our error message
more informative so replace error in review ID with error. message by replacing our
hardcoded text with error. message we will now see error loading review when things
go wrong the error we threw in our ph. TSX file this same message is passed to our
error. TSX component now here is what makes error. TSX so powerful in the app
router it automatically wraps route segments and

01:44:14
their nested children in a react error boundary you can create custom error uis for
specific segments using the file system hierarchy it isolates errors to affected
segments while keeping the rest of your application functional finally it enables
you to attempt to recover from an error without requiring a full page reload now
that we have identified all the special files in the app let's look at the bigger
picture the slide shows us the component hierarchy in a folder layout component at
the top

01:44:46
followed by template then the error boundary from error. TSX for runtime errors a
suspense boundary from loading. TSX another error boundary from not found. TSX for
missing resources and finally the page component with this error handling setup in
place let's explore more advanced error handling techniques as we continue
previously we learned how to handle errors gracefully using error. TSX while some
errors are serious others might be temporary and can be fixed with a simple retry
let's take a look at how

01:45:22
to recover from such error apart from the error prop the error boundary in error.
TSX provides us with another useful prop a reset function the type is a function
that returns void we can make use of this reset function by adding a button in our
jsx that triggers it on click inter WRA the message in a paragraph tag and add a
button the text is try again and on click we're going to call the reset function
this button gives users a way to retry rendering the component in page. TSX if we
head to the browser and

01:46:00
reload until we hit the error you will notice a try again button when clicked it
attempts to reender the review ID component however if we keep clicking we will
keep hitting the error again and again this is because the retry function will
attempt to reender client side but converting the review ID component to a client
component just to handle errors is a bit Overkill to attempt server side recovery
we will need to rely on start transition from react and use router from nextjs here
is how we can do it

01:46:36
start by importing use router from next navigation and start transition from react
then within the component we Define a router constant by calling use router const
Router is equal to use router next we Define a Reload function that grabs router.
refresh and reset call inside start transition so start transition this accepts a
function where we call router. refresh and reset make sure these lines are outside
the return statement the reload function ensures that the refresh is deferred until
the

01:47:16
next render phase allowing react to handle any pending State updates before
proceeding finally we update the on click Handler to call the reload function now
if we head to the browser and reload until we hit the error you will notice a try
again button when clicked it attempts to reender the review ID component if our
random number isn't one we will recover from the error and see the actual page
content of course this could just be the reload function but I hope you found this
useful all right we've got more

01:47:51
interesting aspects of error handling to cover so let's keep going let's focus on
how to handle errors in nested routs right now we have our error. TSX file sitting
in the review ID folder looking at our route hierarchy we've got products at the
top level followed by product ID and review ID is nested inside this structure
actually affects how our error. TSX file Works here's the key thing to understand
errors always bubble up to find the closest parent error boundary what this means
is that an error. TSX

01:48:26
file handles errors not just for its own folder but for all the nested child
segments below it too by strategically placing error. TSX files at different levels
in your route folders you can control exactly how detailed your error handling gets
let me show you what I mean let's hop into vs code and move our error. TSX file
from the review ID folder up to the products route when we refresh the browser and
trigger an error we will see the same error message error loading review but there
is a crucial difference this time the

01:49:04
entire products route gets replaced by what is in error. TSX file that is because
the error from page. TSX in the review ID folder bubbles up until it finds the
nearest error boundary which is now in the products folder but watch what happens
when we move the file file back to the review ID folder and refresh now the
featured product section from our product ID layout stays in place and only the
review ID component gets replaced by our error. TSX UI see how much more precise
this is this really demonstrates how error handling

01:49:44
Works in nested routs where you put your error. TSX file makes a huge difference it
determines exactly which parts of your UI get affected when things go wrong up next
we will dive into handling errors within layouts after handling errors in nested
routes let's tackle something equally important handling errors within layouts we
know that error. TSX handles errors for all nested child segments but there is an
interesting catch with layout. TSX components in the same segment the error
boundary won't catch errors thrown in

01:50:19
layout. TSX within the same segment because of how the component hierarchy works
the layout actually sits above the error boundary in the component tree let's head
back to V code and see this in action with a practical example I'll start by
copying the error. TSX file from the review ID route into the product ID route then
in the product ID layout. TSX I will add the same random error throw we had in the
review ID page copy over both the random number generator and the error throwing
logic change the message to error

01:51:02
loading product I'll comment out the error code in review ID to avoid confusion
back in the browser when we reload the page and Trigger the error you will notice
something is off there is no error boundary catching it and our app breaks with
unhandled runtime error we also see our error message error loading product this
highlights a crucial Point error. TSX won't handle errors from a layout. TSX file
in the same segment the solution well we need to move the error. TSX file up to the
layout parent segment in this case the

01:51:42
products route reload the page and you will see everything works as expected the
error boundary run ERS properly replacing just the products route content while
keeping the header and footer and other higher level UI elements in tag at this
point I am pretty sure you have a question lingering in your mind you might be
wondering if an error boundary can't catch errors in the layout. TSX file from the
same segment what about errors in the root layout it doesn't have apparent segment
how do we

01:52:19
handle those errors nexts has thought of this it Prov provides a special file
called Global error. TSX that goes in your root app directory this is your last
line of defense when something goes catastrophically wrong at the highest level of
your application it is a little verbose to simulate and catch errors in the root
layout so let me show you how to set this up to introduce an error in our root
layout in the app folder I'm going to add a special wrapper component that throws
an error so adjacent to the

01:52:50
root layout. TSX file create error rapper. TSX I'm going to paste the code and walk
you through the code you can find this code on my GitHub repo but let me quickly go
over what we have here error rapper is a client component so use client directive
is present at the top we are importing some Styles the use State Hook from react
and then we have this error simulator component it accepts a message and throws
that error message if the error flag is set to true true error is false by default
but when you click on a

01:53:26
button simulate error set error is set to true and the error is triggered the error
simulator component is present in an error wrapper component which accepts children
props and renders the same this component is necessary to throw an error from our
root layout so in layout. TSX file import the component and add it to the jsx
wrapped around ch children so error wrapper opening and closing next add a global
error. TSX file in the app folder so adjacent to layout. TSX new file Global error.
TSX this file should export a react

01:54:12
component that will be rendered when an error occurs in the root layout or any of
its nested routes in the absence of an eror boundary once again to save time I'm
going to paste the code you can find this code in my GitHub repository we start
with the use client directive since error boundaries must be client components we
then import some CSS we then Define a react component called Global error which
displays an each two heading something went wrong on click of a button we call
window. location.

01:54:45
reload and the text is refresh very simple now in both files Tailwind classes are
used for styling and you will notice the global. CSS import the file does not exist
yet so let's create it in the app folder create a new file called global. CSS
include Tailwind base components and utilities all right our setup is now complete
in the browser when you navigate to Local Host 3000 you should see our newly
included wrapper component wrapping p. TSX in the app folder using this wrapper
component we can trigger an

01:55:23
error in the root layout click the button now we don't see the global error
boundary kick in we only see the error overlay this is because the global error
boundary only works in production mode in development you will see the default nexs
overlay instead so we have an unhandled runtime error and the error message
simulated error in root layout in the terminal press contrl C to stop the
development server and run the build command npm run build then start the
production server with npm Run start back in the browser simulate the

01:56:05
error in the root layout again now we still don't see the global error UI and we
don't see the error overlay either the reason is that Global error. TSX needs to
include its own HTML and body tags because when this error boundary kicks in it
completely replaces your root layout we have HTML and body tags in layout. TSX
which also need to be included in the global error boundary so HTML and body let's
rebuild with npm run build and rerun with npm Run start in the browser simulate the
error

01:56:47
again and we can see the global error UI something went wrong and a button to
refresh that corresponds to the jsx present in our Global error boundary Works only
in production mode and requires HTML and body tags to be rendered these are two
crucial things you need to know about global error. TSX that makes it different
from our regular error. TSX files since we can't catch any more errors it is
recommended to have global. TSX as simple as possible HTML and CSS would be the
ideal scenario you wouldn't want errors from your

01:57:24
Global error boundary all right that covers the key Concepts about error handling
in the nexts app router it is time to dive into some Advanced routing Concepts in
next sh we're going to start with parallel routes what they are how to set them up
and why they're super useful when building complex user interfaces parallel routes
is an advanced routing mechanism that lets us render multiple Pages simultaneously
within the same lay out let's look at scenario 7 building a complex dashboard

01:57:56
for a web application imagine needing to display user analytics Revenue metrics and
notifications all at once in the same route the traditional way would be to create
three separate components for each part and organize them in a layout. TSX file
inside a dashboard folder within the app folder so let's do that now we already
have a dashboard folder so let's create a new folder called complex dashboard
complex hyphen dashboard and add a layout. TSX file using regular components the
code might look something like this the three

01:58:37
components will be imported from separate files and rendered within complex
dashboard layout component user analytics Revenue metrics and notifications the
layout will also render the component from adjacent page. TSX as the the children
prop this file doesn't exist yet so let's create it new file page. TSX export
default function complex dashboard and return an H1 tag that says complex dashboard
each of the other three components which we won't Define by the way represents a
specific

01:59:13
dashboard section in the UI think of them as cards that will render the necessary
data while this traditional component based approach works well par routes can
achieve the same result with some extra benefits so how exactly do we Implement
parallel routes in next sh parallel routes and xjs are defined using a feature
known as slots slots help organize content in a modular way to create a slot we use
the at folder naming convention each defined slot automatically becomes a prop in
its corresponding layout. TSX file for our

01:59:49
complex dashboard we will create three slots within the comp complex dashboard
folder at users for user analytics at revenue for Revenue metrics and at
notifications for notifications let's Implement these now let's start with
notifications within the complex dashboard folder create a new folder called at
notifications with a page. TSX file default export a react component called
notifications which returns a DI tag t with the text notifications similarly within
complex dashboard again create another folder at

02:00:31
Revenue create a page. TSX file and default export a react component called Revenue
metrics that returns a div tag that says Revenue metrics finally create another
folder with a page. TSX file so at users page. TSX export default function user
Analytics which returns a div tag with the text user analytics three simple
components with the at folder naming convention now we can use these three slots in
our layout. TSX file the nice thing is that they are automatically passed in as
props to our layout component and no Imports are

02:01:12
needed let's delete the import statements and specify three more props users
revenue and notifications and and for the types the same three components users
revenue and notifications I will update the jsx with inline styles to match the
layout from our slide you can find this code on my GitHub repo we have an enclosing
div tag with an sad div tag that renders children prop we have the users slot
Revenue slot and finally notifications slot let's also create a nice card component
to wrap each one of those

02:01:51
slots in the source folder we'll make a new folder called components with a card.
TSX file I'll paste the code for a card component to save us the time now in each
slot replace the diff tag with the card component make sure to import the component
at the top so notifications wrapped with card Revenue metric wrapped with card and
user analytics wrapped with card we now ready to go when you visit locost 3000
complex dashboard you will see our complex dashboard with the main title right here
and all the three

02:02:33
slots nicely laid out user analytics Revenue metrics and notifications if it
doesn't work try restarting the development server our parallel routes work as
expected but here's something important to note slots are not route segments and
don't affect your url structure so so if you try navigate to complex dashboard SL
users or at users you won't see user analytics you get back a 404 page not found
and what is even more interesting is that the children prop is actually an implicit
slot that doesn't need its own

02:03:13
folder complex dashboard SL page. TSX is the same as complex dashboard SL children
SL page. TSX so technically we are working with four slots in our layout file now
let me walk you through some of the use cases for parallel routes dashboards with
multiple sections split view interfaces multi- pane layouts complex admin
interfaces and really any UI where sections need to operate independently you might
be wondering what is the benefit of building user interfaces with parallel routes
what makes them so special while parallel

02:03:52
routes are great for splitting a layout into manageable slots especially when
different teams work on different parts that is not their main superpower you could
do that with regular components as well the real magic of parallel routes comes
from two key features independent route handling and subnavigation let's break this
down one of the most compelling features of parallel routes is the ability to
handle each route independently this is huge because each slot in your layout such
as users

02:04:24
revenue and notifications can handle its own loading and error States this granular
control is particularly useful in scenarios where different sections of the page
load at varying speeds or encounter unique errors think about it if your user
analytics data is taking its speed time to load you can show a loading spinner just
for that part while everything else stays interactive or if something goes wrong
with fetching Revenue metrics you can display an error message in that specific
slot without breaking the rest

02:04:56
of your dashboard the other significant advantage of using parallel routes is their
capability to offer a seamless subnavigation experience within each parallel route
each slot can essentially function as a mini application complete with its own
navigation and State Management users can interact with each section separately
applying filters sorting data or navigating through pages without affecting other
parts for example in the notifications section users might want to switch between
default and archived views to see older

02:05:31
notifications these interactions stay contained within the notification section and
the URL updates to match the current view this makes the URL sharable and helps
users track their location in the application users can also navigate through
different parts of the application without unnecessary page reloads or layout
shifts now when discussing in subnavigation in parallel routes there is a very
important concept we need to understand let's see what that is next let's dive into
a crucial aspect of

02:06:03
parallel routing which is handling unmatched routes we've already learned that sub
navigation within routes is one of the benefits of using paralleled routes for
example in our complex dashboard we could navigate between a default list of
notifications and an archived list of notifications let's jump into vs code and
implement the scenario first we will update page. TSX in the notifications slot to
add navigation to the archive view import the link component and include it in the
jsx let's wrap notifications in a div

02:06:37
tag and add another div with link text is archived and hre is/ complex dasboard
slash archived link by the way is a default export now let's create the archived
notifications view inside the notifications slot create an archived folder remember
this is a regular route folder and add a page. TSX file with similar code but
modified for the archive view so copy page. TSX paste it update the component name
to archived notifications The Heading and the link we point to default
notifications s the

02:07:22
HF is/ complex Dashboard please note archived is a regular route folder and not a
slot if you now check the browser you will see the link for archived notifications
clicking it changes the URL to/ complex dashboard SL archived and the UI shows the
archived view clicking the default link takes you back to/ complex dashboard and we
see the notific ation view our subnavigation is working perfectly with this
implementation in place let's discuss the main topic for this video which is
unmatched routes by default the content

02:08:05
rendered within a slot matches the current URL our complex dashboard has four slots
children users revenue and notifications when you visit localhost 3000 complex
dashboard all slots show their respective content but when you navigate to
localhost 3000 complex dashboard SL archived only the notifications slot has
matching content the other three slots children users and revenue become unmatched
next Shar handles these unmatched slots differently depending on how you navigate
when navigating through the UI

02:08:45
like clicking links next keeps showing whatever was in the unmatched slots before
so when you move between default and archived notifications the other three slots
children users and revenue stay exactly as they were and are not influenced by the
shift in the URL path from SL complex dashboard to SL complex dashboard SL archived
when you reload the page however next sh looks for a default. TSX file in each
unmatched slot this file is critical as it serves as a fallback to Rend content
when the framework cannot retrieve a slot's

02:09:24
active state from the current URL without the file you will get a 404 error that is
exactly what happens if you reload SL complex dashboard SL archived it's not found
could not find requested resource we don't have a default. TSX file in the children
users or Revenue slots let's go back to vs code and fix this by adding the missing
file now the files can either mirror your page. TSX content or show something
completely different it is up to you in our case we will keep it simple and copy

02:10:00
the content from page. TSX for our complex dashboard we need to add three default.
TSX files to prevent 404 errors when reloading the page first is for the children's
slot Define default. TSX within the complex dashboard folder this will serve as a
fallback View for the children's slot copy the contents from page. TSX and paste it
you can rename the component as well as change the heading completely up to you
next Define default. TSX inside the user slot So within add users folder default.

02:10:41
TSX and this will serve as the fallback View for the users slot so copy page. TSX
content and paste it I'll just change the card text to use analytics default
content finally Define default. TSX in the revenue folder I'll copy page. TSX
content and leave it as it is no change this will serve as the fallback View for
the revenue slot once these are in place reloading localhost 3000 complex dashboard
SL archived works perfectly the notifications slot shows the archived content as it
is the only slot with a

02:11:22
component defined for the slash archived route this folder right here the other
slots show the respective default. TSX content as fall bags say complex dashboard
default user analytics default content Revenue metrics which we didn't change so
reload complex dashboard navigate to archived children user and revenue Remains the
Same we load and we render the default content this setup ensures you don't
accidentally render a route that shouldn't be parallel rendered if you're having
trouble with

02:11:59
this please try restarting the development server all right we have now covered how
parallel routes allows you to simultaneously render multiple pages in the same
layout next we will explore how parallel routes allows for conditional rendering of
pages within the same layout in our previous exploration of parallel routing we
learned how to display multiple Pages simultaneously in the same layout without
changing the URL now let's explore conditional routes another powerful feature that
parallel

02:12:30
routes enable imagine you want to show different content based on whether a user is
logged in or not you might want to display a dashboard for authenticated users but
show a login page for those who are not conditional routes allow us to achieve this
while maintaining completely separate code on the same URL let me show you how to
implement this scenario let's start by creating our login slot first in the complex
dashboard folder create a new sub folder called at login inside this folder create
a page. TSX

02:13:03
file we'll keep the component simple you can copy a component from another slot for
example users paste it here and rename it to login slot change the text to please
login to continue in a real application this would be where you would Implement
your login form but this placeholder text works fine for our demo now head back to
the layout. TSX file and add the login slot to the props so login and then login of
type react. react node for the jsx we will create a simple Au check add a constant
called e logged

02:13:47
in and set it to fults in a real application you would typically use something like
get user or use Au to check the authentication status but we'll keep things simple
here based on the value of e logged in let's conditionally render the UI so return
is logged in then what we already have else the login slot when you check the
browser you should see the login slot since we set is logged in to false if you're
not seeing the change try restarting your Dev server npm runev refresh and we see
the card please log

02:14:27
in to continue switch the value of East logged in to true and you will see all the
other slots appear this shows how parallel routes conditionally render different
pages while maintaining clean separated code under the same URL the login slot also
benefits from independent error and loading States as well as subnavigation to a
possible signup or forgot password route the app router in ex introduced two
Advanced routing patterns we've already learned about paralleled routes now let's
dive into intercepting routes

02:15:03
let's tackle this in two parts first we will understand the Core Concepts and
conventions then we will see how to put them to practical use intercepting routes
is an advanced routing mechanism that allows you to load a route from another part
of your application within the current layout it is particularly useful when you
want to display new content while keeping your user in the same context to help
understand better let me give you a couple of real world examples consider a login
flow typically

02:15:32
clicking a login link would take you to a new page but with intercepting routes you
can display a model instead while still updating the URL to/ login this means
sharing that URL or refreshing the page still works as expected showing the full
login page or consider a photo gallery instead of jumping to a dedicated photo page
when someone clicks an image you can show a model with the enlarged photo in
details like the photographers name and location the URL updates to match the
specific photo making it sharable accessing that URL

02:16:09
directly will show the photo's full page of course defining intercepting routes in
an xjs application involves certain conventions let's dive into vs code and
understand them through examples we will start by setting up our folder structure
in your app folder create a new folder named F1 short for folder one with a page.
TSX file containing a simple react component page. TSX export default function F1
that returns an H1 tag F1 page inside F1 folder let's create another folder F2 with
its own page. TS X so F2 page. TSX

02:16:55
here export default function F2 return and H1 tag that says F2 page next let's
update our F1 component to include a link to F2 so import link from next SL link
and for the jsx add a div tag with the link component pointing to F2 H is equal to
slf1 slf2 remember F2 folder is nested inside F1 folder in the browser when you
visit Local Host 3000 slf1 you will see the F1 component with a link to F2 clicking
this link will take you straight to/ F1 slf2 we see the jsx F2 page let's change
this Behavior
02:17:43
with an intercepting route to understand intercepting routes conventions better
let's think about two key elements The Source folder and the target folder we want
to intercept the F2 route when navigating from F1 route so F1 is our source folder
and F2 is our Target folder let's start by creating a new folder in our source
folder this will be our intercepting route the folder name needs to match our
Target folder F2 but we need a special prefix to make it work for now I'll just add
intercepted hyphen

02:18:23
as a placeholder while I explain the actual prefix we need the prefix VI use is
super important because it tells nexs where the Target Route is located notice how
both F2 and intercepted F2 are at the same level in our folder structure when we
want to intercept a route at the same level like this we use a dot inside
parenthesis notation so let's replace intercepted hyphen with parenthesis with a
dot inside inside this folder we'll create a page. TSX file with a react component
that shows our intercepted

02:19:00
content so export default function intercepted F2 we return an H1 tag with the
prefix and text that says intercepted F2 page restart the dev server with npm run
Dev and navigate to/ F1 in the browser click the F2 link the URL updates to slf1
slf2 but shows the intercepted content refreshing this page loads the original F2
page instead this is the idea behind intercepting routes it lets you show alternate
UI by preserving context but defaults to the standard UI on Direct page loads the
first convention you need to know about

02:19:43
intercepting routes is pretty straightforward we use a DOT within parenthesis to
match segments that are at the same level in your folder structure this is similar
to relative path convention where we use a DOT to refer to the current folder now
what if you want to intercept something that is one level up no problem we just use
two dots within parentheses as the prefix similar to how we use two dots to refer
to the parent folder in relative path convention let me show you what I mean with
an example let's create a new

02:20:16
folder called F3 in our app directory So within app new folder F3 create a page.
TSX file with a simple react component export default function F3 that returns an
H1 tag F3 page now head over to page. TSX in the F1 folder and add a link to F3 the
text is F3 and the H slf3 when you try this in the browser clicking this F3 link
takes you straight to slf3 this renders F3 page but let's make it more interesting
by intercepting this route for this example our source folder is F1 where we are
navigating from and

02:21:01
our Target folder is F3 where we want to go so inside the source folder F1 we'll
create a new folder that matches our Target folder name F3 so new folder F3 we need
a special prefix to make it work but I will just add intercepted hyphen as a
placeholder while I explain the actual prefix we need since F3 is one level above
where we are in the folder structure we'll use dot dot within parenthesis as our
prefix kind of like when you use do do slash to go up one folder in file pods
inside this folder
02:21:43
let's create a page. TSX file with a component that shows we have successfully
intercepted the route so page. TSX and default export a function called intercepted
F3 that shows the prefix as well as the content intercepted F3 page give your Dev
server a quick restart npm run Dev and now in the/ F1 route when you click that F3
link the URL still shows slf3 but you will see our intercepted content instead if
you refresh the page you'll get back to the original F3 content just as you you
would expect hopefully the

02:22:22
convention is starting to make sense now let's see how to match segments that are
two levels above in our folder structure let's start by creating a new folder
called F4 in our app directory inside it we'll add a simple page. TSX file export
default function F4 and return an H1 tag that says F4 page for this example we're
going to intercept the F4 route when navigating from F2 so let's add a link to F4
in our F2 page import link and invoke it to navigate to F4 a TR is going to be

02:23:05
slf4 if you try this in the browser by navigating to slf1 slf2 and clicking on F4
it takes you directly to/ F4 and you see the F4 page content but we are going to
change that behavior for this scenario our source folder is F2 where we are
navigating from and our Target folder is F4 where we want to go inside the source
folder F2 we'll create a new folder that matches our Target folder name F4 we need
a special prefix to make it work but I will just add intercepted hyphen as a
placeholder while I explain

02:23:46
the actual prefix we need since F4 sets two levels above where we are in the folder
structure we will use parenthesis with two dots and another set of parentheses with
two dots this is our prefix to go up two folders inside the folder let's create a
page. TSX file with a component that shows we have successfully intercepted the
route so export default function intercepted F4 the prefix and the content now give
your server a quick restart npm run Dev and try it out when you load slf1 slf2 you
should see the link to F4 click

02:24:32
the link and you will see our intercepted content instead of the original F4 page
if you refresh the page you'll get the regular F4 route UI back this is exactly
what we want with intercepting routes this double parenthesis with two dots inside
convention is super useful when you need to intercept routes that are multiple
levels up in your folder structure think of it like using do/ do do slash in
regular file Parts it is the same concept just adapted for next year's routing so
that is our third

02:25:06
intercepting routes convention next let's look at the final convention for
intercepting routes using three dots within parenthesis to match segments from the
root app directory first let's create a new folder called F5 in our app directory
F5 and add a page. TSX file with a simple react component export default function
F5 and we return an H1 tag F5 page next inside our F2 folder we will create an
inner F2 folder with a page. TSX that includes a link to F5 so the folder name is
inner F2 with a
02:25:48
page. TSX file that default exports a react component with a link to/ F5 in the
browser navigate to slf1 slf2 slash inner F2 and you'll see the link to F5 clicking
it currently takes you directly to the F5 route SL F5 but what if you want to
intercept this route in this case our source folder is inner F2 where we are
navigating from and our Target folder is where we want to go inside source folder
in our F2 we will create a new folder that matches our Target folder name F5 we
need a special

02:26:34
prefix to make it work but I will just add intercepted hyphen as a placeholder
while I explain the actual prefix we need since F5 lives multiple segments above
our current position we can use a special convention parenthesis with three dots
inside this tells next CH to match segments starting from the root app directory so
from the root app directory there's a folder F5 let's create our intercepting route
with a page. TSX file export default function intercepted F5 and we return an H1
tag

02:27:12
with the prefix and the content now when you restart the dev server npm run Dev and
navigate to SL F1 slf2 SL inner F2 and click the F5 link you will see our
intercepted route instead of the original F5 page but if you refresh you'll get the
regular F5 route back exactly as we want this is the fourth convention using three
dots within parentheses to match segments from the root app directory so to wrap
things up intercepting routes give you this powerful ability to show content from
another part of your app while keeping

02:27:52
your user in their current context and this slide here is a quick cheat sheet of
the conventions we have covered I know intercepting routes can feel a bit complex
at first and that is totally normal up next we'll look at a practical example that
should make all of this click we have recently explored parallel routes and
intercepting routes to powerful routing patterns in the app router now let me show
you how these patterns work together together through a practical example remember
this photo

02:28:24
feed example I mentioned earlier I'll demo this and break down the code to help you
understand how it all works let's start with the demo at localhost 3000/- feed you
will see an image feed showing the seven New Wonders of the World click any image
and a model appears with an enlarged version of that image along with details like
the name photographer and location at the bottom what's happening here is really
interesting we're looking at a parallel route that has been intercepted while

02:28:57
the URL changes to/ photo Feed plus the image ID what you are seeing is a parallel
intercepted route rendering within the same layout with the photo feed visible in
the background this is crucial because without the modal parallel route clicking a
photo would completely replace the page content instead of showing an overlay and
here's something even cooler normally with models hitting the browser's back button
would take you to the previous page instead of closing the model but parallel
intercepting routes solve this
02:29:31
elegantly notice how the back and forward browser buttons smoothly open and close
the model and here is another neat feature if you share the URL with someone or
just refresh the page it loads the photo details on a fresh page this makes
parallel intercepting routes perfect for models you can apply the same principle
elsewhere too like having a login button that opens a model but accessing SL login
directly shows you a full login page now that you've seen it in action let me walk
you through the steps to

02:30:06
create this you'll find all the code in the photo feed folder in my GitHub repo and
the modal component is defined in components folder step one gather your images and
put them in a photos folder inside the photo feed folder we have seven images step
two create a typescript file to import these images and organize them into an array
with metadata each Wonder in our array needs an ID name Source photographer and
location step three set up a page. TSX file in the photo feed folder to display
your image list using the Wonders array

02:30:47
I went with tablein CSS for styling produce whatever styling you prefer wrap each
image in a link component pointing to/ photo feed followed by the image ID 1
through 7 this page creates your main photo feed at localhost 3000 photo Feed step
four create your photo details Dynamic route inside the photo feed folder add an ID
Dynamic route this route grabs the ID parameter finds the matching photo from the
Wonders array and display its details photo name image source photographer name and
location

02:31:27
when someone visits SL photo feed SL ID like two for Petra they'll see the Wonder
details now for the crucial part step five is intercepting navigation between the
feed and details since we want a model overlaying the feed we'll start with a
parallel route create a model as a parallel route in the photo feed folder and
include it in layout. TSX props do model this at model route is special because it
enables simultaneous rendering both the feed content and the model can exist on the
screen at the same time for

02:32:08
interception modal parallel route is the source and the ID route is the destination
so inside the modal Source folder add a new folder that matches the destination for
folder name in this case it is ID Dynamic route since model is a parallel route a
prefix needs to be dot within parenthesis to match the same level within this
folder create a page showing photo details similar to the main Dynamic ID route I
moved photo name from the top to the bottom to demonstrate how you can have
different uis for each route step six add a

02:32:47
default. TSX file to the model parallel route folder this file is used to render
the model content when the route is first loaded we simply return null now here is
what happens behind the scenes when you first load SL photo feed nexs renders both
the modal route which starts empty thanks to default. TSX and the main content
present in page. TSX then when you click an image the modal route intercepts the
navigation to/ photo feed slid this displays the mod overlay while keeping your
main photo feed visible underneath when you reload
02:33:24
the page there is no interception and the ID Dynamic route is rendered instead I
hope this example helps you understand how parallel intercepting routes work
together all right this wraps up page based routing in XS we will dive into route
handlers previously we've learned how to route to pages with the file based routing
system while that is already a powerful feature the app router can do even more it
lets you create custom request handlers for your routes using a feature called
route handlers unlike

02:34:01
page routes which give us HTML content route handlers let us build restful
endpoints with complete control over the response think of it like building a node
plus Express app you can perform all your crud operations with a database but here
is the cool part there is no need to set up and configure a separate server next
just gives you everything right out of the box route handlers are great when making
external apepi requests as well for example if you're building an application that
needs to talk to third

02:34:31
party Services route handlers are perfect for that since they run server s side
your sensitive information like private Keys stays secure and never reaches the
browser if you're coming from Pages router you can think of Route handlers as API
routes next here supports get post put patch delete head and options if an
unsupported method is called Next sh will return a 405 method not allowed response
let me show you how to build your first route Handler I've got vs code open here
and I've started

02:35:06
by creating a fresh next year's project using the command npx create next app at
latest route handlers demo once the command completes you should have a project
that looks like mine let's head into the Source folder first up we will create a
new folder called hello inside the app folder just like page routes route handlers
must live in the app folder inside this hello folder we'll create a file called
route. TS that's another next year's convention we need to follow here we will
export a

02:35:42
function that matches the get HTTP wereb and yes that's another convention export
asnc function get we'll keep this simple and return a plain text response return
new response hello world we're using the standard JavaScript response object here
to handle our incoming request we return a new response with hello world as text in
the browser navigate to localhost 3000 /hello and you will see our text response
hello world and just like that we've got our first route Handler up and running
that is really the core idea of

02:36:23
Route handlers in the app folder create a route. TS file and Export functions named
after HTTP verbs in this case when someone makes a get request to/ hello or get
Handler jumps into action now there are two important things to keep in mind first
route handlers are super flexible with organization so just like page routes you
can Nest them in folders and subfolders to keep everything tidy for instance you
could add a dashboard folder in your app directory with its own route Handler so
create a new folder dashboard

02:37:02
and copy over route. TS from Hello folder but change the text to dashboard data if
you want user specific stuff create a users subfolder inside dashboard with another
route Handler returning user us data so copy paste it and change the text to user
data now in the browser you can hit SL dashboard for dashboard data and SL dasboard
SL users for user data very straightforward second watch out for conflicts between
page routes and Route handlers here's what I mean so you have a page route profile
SL page. TSX in the app folder

02:37:50
so profile / page. TSX with a simple export default function profile page and we
return a div tag profile page in the same folder let's say you've got a route
Handler route. TS you have a get Handler function that returns a new response
profile API data in this case the route. TS will take over by default so when you
visit localhost 3000 SL profile you will see profile API data instead of your page
component the fix is to move your route Handler to an apepi subdirectory So within
profile folder create an Epi

02:38:34
folder and move route. TS within that folder so profile SL route. TS becomes
profile /i/ route. now you can have both your page at/ profile and your Epi at/
profile slpi to summarize route handlers allow you to create custom request
handlers for a given route they are defined in a route. JS or route. TS file inside
the app directory a route. TS file at the same route segment level as page. TSX
will result in a conflict and the page will not be served the route Handler will
handle the request now that you've

02:39:18
got the basics down let me walk you through some Hands-On examples of handling get
post hatch and delete requests with nexs route handlers previously we learned how
to create a basic route Handler now let's dive deeper into working with route
handlers starting with how to handle get requests before we begin I should mention
that we won't be focusing on the UI for this section instead we will use Thunder
client arrest API client for vs code to test our route handlers if you haven't
already go ahead and install the

02:39:52
Thunder client extension in vs code once you have it ready we can proceed to keep
things focused on Route handlers we will skip setting up a database instead we will
store our data in memory which means it will be cleared when we restart the app or
refresh the page that is perfectly fine since our main goal is to understand how
route handlers work let's start by creating some data to work with first create a
new folder called comments in inside your Source folder inside this folder create a
file

02:40:24
called data. TS and here I'll paste an array of three comments we will use think of
these as comments on a YouTube video each with a unique ID and some text now that
we have our data ready let's create our route Handler in the same Commons folder
create a new file called route. TS remember this is a nexs convention for creating
route handlers in this file we will Define and Export our get Handler function we
start by importing our comments array from the data file so import comments from /
data

02:41:05
then we export a function called get export async function get this get Handler
simply returns our comments array as adjacent response return response. Json and we
pass in comments now let's test this Handler open tender client extension and click
on new request set the HTTP method to get and enter the URL localhost 3000
commments leave all the other settings as they are when you click send you should
see a status 200 okay response with our array of three commments ID one first
comment ID 2 second comment and

02:41:51
ID3 third comment perfect the get Handler is working exactly as expected now we are
using Thunder client for testing but in a real application your user interface
would make this request either when the page loads or when the user interacts with
it the important thing is that we have successfully created a get route Handler in
N shars up next we will explore how to handle post requests previously we learned
about handling get requests now let's explore how to handle post requests let's
start

02:42:25
with thunder client we'll keep our previous get request and create a new request
first select post as the HTTP word next copy over the URL HTTP localhost 3000
commments next we need to specify a new comment object to add to our comments array
head to the body Tab and under Json and an object the key in quotes is text and the
value is new comment notice how we are not specifying an ID that will be generated
by our Handler function when we click Send we get a status 405 error method not
allowed let's fix that by adding a

02:43:14
Handler for this post request going back to our route. TS file in the comment coms
folder we will Define and Export a new function export Asing function post remember
it is crucial that our function name matches the HTTP verb we want to handle each
route Handler function gets a standard web request object as a parameter request of
type request we extract the Json body from this request by calling and awaiting
request. Jason this gives us the object we have specified in Thunder client let's
store

02:43:53
it in a constant called common then we create a new comment object so const new
comment is equal to an object we set the ID to the current length of our comments
array plus one so comments do length + one and use the text from our request body
so text is comment. text we add this new comment to our comments array using push
comments. push new comment now for the response we could use response. Json but
that would give us a 200 status code since we are creating a new resource with our
post request a

02:44:36
2011 status is more appropriate so return new response passing in our new comment
as Json so json. stringify new common setting the content type to application sljs
in headers and using status code 2011 to indicate successful resource creation back
in Thunder client when we hit send now we get a 2011 created status and a new
comment as the response id4 text new comment if we switch to our get request Tab
and hit send again we will see all four comments including a new one and that is
the essence of handling post

02:45:22
requests Define your post Handler process the request body and send back an
appropriate response please note that any changes to comments will only exist in
memory and won't be saved to file system our comments array will still contain only
three comments all right now that we have got this down let's move on to exploring
Dynamic route handlers we have covered creating route handlers forget and post
requests now let's tackle patch and delete requests which work a bit differently
since they

02:45:56
require specifying which comment to update or delete while our SL comments route
Handler handles get and post requests patch and delete requests need an endpoint
like slash comments slid where the ID is a dynamic segment it could be 1 2 3 or any
valid ID from our comments array so first let's learn how to to create a dynamic
route Handler that returns a single comment based on its ID this will set us up
nicely for handling patch and delete requests later you will be pleased to know
that Dynamic

02:46:30
route handlers follow the same pattern as Dynamic page routes so to create a route
Handler for/ comons slid first we will create a new folder called ID wrapped in
square brackets within the comments folder so new folder within square brackets ID
then we'll add a route. TS file inside it route. TS and Define our get Handler
function export Asing function get inside this function we need to fetch a specific
comment that matches the route's ID parameter first we will import the comments
array that

02:47:09
contains our data so import comments from data next we need to access the ID route
parameter and as a turn out the Handler function takes two parameters first is a
request object which we are already familiar with second is a context object
containing the route parameters so params of type promise which contains our ID
route parameter of type string now we are only interested in the context so prefix
the request object with an underscore within the function body await the pro
promise and destructure the ID property from the

02:47:51
params object so const ID is equal to await harams using this ID we search through
our commment array to find the matching common so const common is equal to
comments. find and for each comment we check if its ID matches the parameter ID so
parse in ID once found we send it back to the client as adjacent response return
response. Json comment Let's test this in Thunder client in the tab where we are
making a get request let's append slash1 to the URL and hit send we get a 200 okay
status and the comment with ID

02:48:39
is equal to one try slash2 send and we get the second comment same with slash3 for
the third comment the URL parameter Det determines which comment we retrieve while
we are only working with three comments here in the real application you might have
thousands of database records but the logic Remains the Same extract the ID from
the parameters find the data corresponding to that ID and return as Json but now
that we understand Dynamic route handlers let's move on to handling patch requests
for

02:49:12
updating individual comments let's learn how to handle patch requests a patch patch
request lets us make partial modifications to a resource since we only working with
a single property called text updating a comment will be pretty straightforward
first let me show you what a patch request looks like in Thunder client we'll start
by changing the HTTP word from get to patch we will keep the same URL since we are
updating the comment with ID3 in the body tab under the Json section we will

02:49:45
add an object with the text property set to a different string updated common when
we hit send we get a status 405 method not allowed let's fix that by adding a
Handler for patch requests in our route. TS file inside the ID folder we will
create a new route Handler function export async function patch this function
receives two parameters request and context I will copy the parameters from our get
Handler function inside the function we first destructure the ID by awaiting params
next we get the Json body from

02:50:29
the request using await request. Json we assign it to a constant called body now we
are using request so let's remove the underscore from our parameter next from body
we destructure the comment text to find the comment we want to update we can use
either th array. find or find index I'm going with find index since we will need it
for delete operations later so con index is equal to comments. find index comment
such that comment. ID is equal to horse int the ID parameter once we find the
comment we

02:51:13
simply update its text property so comments of index text is equal to the text from
the request finally return the updated comment as adjacent response return
response. Json comments of index now heading back to thunder client and hitting
send we get a 200 status code with our updated comment in the response ID3 text
updated comment if you make a get request from the same tab to/ comments we can see
our updated comment in the array ID3 text updated comment this is how we handle
patch requests in

02:52:02
route handlers please note that any changes to comments will only exist in memory
and won't be saved to the file system in data. TS you will continue to see the
original text for comment ID 3 up next we will look at handling delete requests
let's learn how to handle delete requests a delete request as the name suggests
removes a specified resource in our case we will be deleting a comment using its ID
first let's see what a delete request looks like in Thunder client we will start by
changing the

02:52:37
HTTP word from patch to delete the URL structure stays the same since we will still
need the comment ID in the URL /3 for this example we will delete the comment with
ID 3 we can remove the body Json since it's not needed for delete requests when we
hit send we get a status 405 error method not allowed let's fix this by adding a
Handler for the delete request in our API route in our route. TS file within the ID
folder let's add a new route Handler function we will create an async function
called

02:53:16
delete that takes two parameters request and context these are the same parameters
we've seen before for both patch and get requests we get hold of the ID route
parameter by awaiting params next we will use array. find index to locate the
comment we want to delete let's copy the line from our patch function so const
index is equal to comments. find index find the comment such that its ID is equal
to the ID route parameter before deleting the comment at the given ID we store it
in a variable so we can

02:53:54
return it later so const deleted comment is equal to comments of index then we use
array. splice to remove the item so comments. splice at index one item and we
finally return response. Json passing in the deleted comment Let's test this in
Thunder client hitting send now gives us a 200 status code and shows us the deleted
comment in the response ID3 text this is the third comment and if we make a get
request from the same tab to just slash comments you will notice the comment with
ID3 is no longer present in the

02:54:39
array we just have two comments so that is how we handle delete requests in route
handlers please note that any changes to comment will only exist in memory and
won't be saved to the file system in data. TS you will continue to see the third
commment now that we have covered get post patch and delete requests let's proceed
to understand some additional related topics let's learn how to work with URL query
parameters in route handlers in our data. TS file we have an array of three
comments now imagine we want to

02:55:16
filter these comments based on a search St term for instance when you visit
localhost 3000 Commons you will see all three comments but what if you want to see
only comments containing the word first by going to slash comments question mark
query is equal to first let's jump into vs code and see how to make this happen in
route. TS present in the comments folder we have defined our get Handler function
which Returns the array of three commments this is the route Handler we need to
modify first up

02:55:49
we need to work with the request parameter while we've been using the standard
request API until now in the context of next shares the type we are actually
dealing with is next request import it at the top from next SLS server and specify
the type in the get Handler this next request object provides convenient methods
for managing query parameters with ease let's update our code within the function
body we grab all query parameters using request. nextext url. search params and
store them in a constant called search

02:56:28
params then we use the get method to fetch our specific query parameter so const
query is equal to search params doget query if there is a query parameter we filter
the comments to only include those containing the search term so const filtered con
commment is equal to query if it exists commons. filter and filter Commons such
that they include the query parameter if there is no query present respond with the
original comments array finally send back the filtered comments as Json Let's test
it out in the browser

02:57:10
navigate to localhost 3000 SL comments and we continue to see the three commments
now specify question mark query is equal to first and you will see just the first
commment try changing the query parameter value to ir and you'll get both the first
and third comments since both contain IR in case you're wondering how to work with
multiple query parameters you can access them individually using search params
doget passing in the parameter name very straightforward but this is how you work

02:57:47
with query parameters in route handlers they're optional but they're absolute gold
for adding powerful features like search sorting and pagination to your
applications let's dive into handling headers in route handlers we will start with
the basics of what headers actually are HTTP headers represent the metadata
associated with an API request and response this metadata can be classified into
two main categories first we have request headers these are sent by the client such
as a web browser to the

02:58:20
server request headers contain essential information about the request which helps
a server understand and process it correctly for example we have user agent which
identifies the browser and operating system to the server it is often used for
browser specific content rendering and analytics we have accept which indicates the
content types like text video or image formats that the client can process it
enables the server to deliver the resource in a format suitable for the client
another common

02:58:51
request header is the authorization header used by the client to authenticate
itself to the server it carries credentials allowing controlled access to resources
second we have 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
an example is the 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 for HTML documents application

02:59:25
sljs for Json data Etc when you're working with route handlers in xgs you will need
to know how to both read request headers and send back response headers let's head
over to us code and understand with an example now we will use the profile route
Handler we built earlier open route. TS present in the API folder we have a get
Handler that returns a new response through file API data I'm going to open Thunder
client extension make a new request to http localhost 3000 profile API by default

03:00:02
the request has two headers accept and user agent let's add a third one
authorization and we can set the value to a bearer token beer 1 2 3 4 5 now the
question is how do we read these headers in our route Handler well we've got two
options the first one is using the request parameter at the top import type next
request from next SL server and specify the parameter with its type request of type
next request within the Handler function we use the headers web API to extract the
request headers so new

03:00:44
headers and we pass in request. headers we store it in a constant called request
headers in the next line we will use the get method on request headers and log the
authorization header to the console so console.log request headers doget the
authorization header which we have just specified if we send a request from Thunder
client open the terminal we should see our Bearer token authorization header the
value is beer followed by 1 to 3 4 5 while this first option works completely fine
you can also choose to

03:01:23
use the headers function that next sh has provides at the top import headers from
next SL headers and within the function body we invoke the headers function and
store the result in a request headers constant so const header list is equal to
await headers headers is an Asing function so we will need to await it we then
access the authorization header using the get method and log it to the console
console.log headers list.get authorization resend the request with a different
token value 1 2 3 4 5

03:02:05
67 and check the terminal we can see the latest beer token is logged so this is how
you read headers from an incoming request now let's talk about setting outgoing
headers here's something important to know the headers returned from the headers
functions are read only to set new headers you will need to return a new response
with your custom headers let me show you an example if you access this route in
your browser SL profile SL API you will see profile API data in plain text check
the network Tab

03:02:40
and you will notice the content type is text/plain so if we wrap our text in an H1
tag and refresh it will still show up as plain text but watch what happens when we
set the content type to text/html so return new response as a second argument you
specify headers and content type is text/html refresh your browser and now you've
got properly styled H1 text profile API data the browser renders it differently
because we told it to expect HTML through the response header content type
text/html the takeaway is that to set headers you

03:03:25
need to return a new response with custom headers using the request and response
headers you can Implement whatever logic you need to in your route Handler
previously we learned how to work with headers in route handlers now let's dive
into handling cookies in route handlers cookies are small pieces of data that a
server sends to a user's web browser the browser can store the cookies and send
them back to the same server with future requests cookies serve three main purposes
managing sessions like user logins and shopping

03:03:59
carts handling personalization such as user preferences and themes and tracking
like recording and analyzing user Behavior if you would like to dive deeper into
cookies you can check out the detailed documentation on mdn but for now let's head
back to vs code and see how we can work with cookies in the next year's route
Handler similar to what we saw with headers we will primarily look at how to set
and get cookies inside a route Handler there are two ways to accomplish this the
first approach is to set a cookie by returning

03:04:32
a new response with the set cookie header so after content type text/html specify
set cookie theme is equal to dark if we check Thunder client and look at the
cookies tab in the response section we have no cookies available it starts empty
with our set cookie logic in place if we make a new request we will see our tee
cookie appear named tee value dark now to read this cookie in our route Handler we
can use the request parameter so const theme is equal to request. cookies. getet
and we specify the name of the cookie team let's log it

03:05:19
to the console back in Thunder client if we send the request and open the terminal
we will see the cookie name value pair being logged name theme value dark so this
covers our first approach using the set cookie header to set a cookie and the
request object to read it for the second approach next sh provides a built-in
cookies function let's import it at the top import headers comma cookies from next
SL headers cookies is an eing function so we will need to await it within the
Handler function

03:05:57
const cookie store is equal to await cookies now to set a cookie using this method
we can call Cookie store. set we specify the name results per page for example and
the value is 20 after sending a new request a cookie results per page now appears
with a value of 20 reading this cookie is just as straightforward with cookie
store.get so console.log cookie store.get results per page send the request again
and in the terminal you will see name results per page value 20 apart from set and
get the cookies function

03:06:48
supports additional methods like has and delete please refer to the docs for more
information all right that wraps up working with cookies in route handlers let's
quickly talk about handling redirects in route handlers imagine you've built a
user's API that's been running for a while your V1 endpoint has basic user
information like ID email full name and create at after a few months you've built a
more comprehensive V2 endpoint that includes structured names user preferences and
profile data to move

03:07:24
clients to this new endpoint we can set up a redirect in V1 so in V1 rod. TS import
redirect from next SL navigation and within the get Handler function call redirect
passing in the New Path /i slv2 SL users in the browser when clients headit /i slv1
they'll receive a 307 temporary redirect to /i/ V2 users this works smoothly
because all V1 fields are preserved in V2 new fields are purely additive existing
clients can keep using the same Fields they've always used and new clients can take
advantage of the

03:08:13
enhanced data structure it also gives us a chance to clean up any loot in V1 before
fully switching over all right up next we will look at caching in route handlers
for the final detail about route handlers let's talk about caching while route
handlers in nexts are in cached by default you can opt into caching when using the
get method let me show you how this works let's create a new folder called time in
our app directory and add a route. TS file so time/ route. TS here is a simple get
Handler this

03:08:54
endpoint Returns the current time in Json format if you navigate to localhost
3000 /time in the browser you will see the current time in hours 11:45 43 a.m. each
reload will show you the latest time since there is no caching by default and this
is exactly what we want in this case now let's look at a scenario where in makes
perfect sense within the app folder create a new folder called categories with a
route. TS file Define and Export a get Handler function so export eing function get
and we have an

03:09:32
array of four categories each with an ID and a name we return the array in Json
format we've hardcoded the categories data for Simplicity but in a real world
scenario this data would typically come from a database since this data rarely
changes every request to this endpoint will trigger a database query which is
inefficient to avoid this we can use caching We'll add a configuration option at
the top of the file export const Dynamic is equal to force static this ensures that
the response is cached and

03:10:09
served instantly to all users however we can't test this route Handler because
there is no Dynamic data in this response let's add the seam configuration to the
time route Handler and test that instead export const Dynamic Force static Now
navigate to/ time in your browser you will see the current time 11:49 31 a.m. if
you reload the page you will still see the time change this is because there's no
caching during development let's build the app using npm run build and start it
using npm Run start

03:10:50
now navigate to/ time the time is 11:49 58 a.m. the time Remains the Same on
reloads refresh and you can see the time does not change this time refresh to the
time when the app was built if you come back to the browser and navigate to/ time
after 10 minutes you will still see the same time it changes only when the
application is rebuilt but what if we want to update our data without rebuilding
the entire application well you can revalidate cached data using incremental static
regeneration at the

03:11:27
top of the file we will add export const revalidate is equal to 10 this will
revalidate the data every 10 seconds when you run npm run build the rout Handler
code is generated with the time of the build when you run npm run start all
requests made to slash time are cached and instantaneous after 10 seconds has
passed the next request will still show the cached stale page while a new version
of the code is generated in the background with the latest timestamp now when you
reload again the updated time

03:12:07
stamp is shown for the next 10 seconds and this process repeats this is how you
revalidate cached route handlers in the app router it is worth noting that caching
only works with get methods other HTTP methods like post put or delete are never
cached additionally if you're using Dynamic functions like headers and cookies or
working with the request object in your get method caching won't be applied I hope
this gives you a good understanding of how caching Works in route handlers we have
one final topic

03:12:41
to cover in this section so let's keep going for our final topic on routing inexs
let's learn about middleware middleware inexs is a powerful feature that lets you
intercept and control the flow of requests and responses throughout your
application it does this at a global level significantly enhancing features like
redirects URL rewrites authentication headers cookies and more let's jump into vs
code and see how to implement middleware in our application creating middleware in
xjs is straightforward just add a middleware

03:13:17
doj s or TS file in your Source folder middleware dots now middleware let's you
specify Parts where it should be active with two approaches custom matcher config
or conditional statements let's explore both approaches using redirection as an
example imagine a scenario where navigating to/ profile should redirect the user to
the homepage here's how we can achieve this we start by importing next next
response from next SLS server which extends the standard response API we also
import next request type from next /s server

03:13:59
next we Define a middleware function that accepts a next request type request so
export function middleware accepts request of type next request this function
redirects to the homepage when slash profile is accessed so return next response.
redirect new URL and the path is the homepage we also pass in request. url with
then use a config object to tell ni shares to only apply this middleware to the/
profile rout so export const config is equal to an object where we specify a
matcher SL profile let's restart the dev

03:14:46
server with npm run Dev now when you navigate to/ profile in the browser it
automatically redirects to the homage showcasing the matcher config approach now
let's look at the second approach using conditional statements we'll keep the
Imports but comment out the function body and the config object instead we will
type f request. next url. paath name is equal to/ profile return next response.
redirect new URL and let's specify the path as /hello and we pass in request. next
URL now when you

03:15:29
visit SL profile in the browser it will redirect to our /hello route which we
created a while ago this shows how we can use conditional statements to control
middleware responses based on the request path Beyond redirects middleware also
supports URL rewrites a feature perfect for handling Legacy URLs or improving SEO
instead of redirect you can use rewrite to keep the URL in the browser unchanged
while serving different content Now navigate to/ profile and you will see it is
redirected to/ hello so
03:16:07
we see hello world but the URL in the browser is still SL profile finally let's
explore the use of cookies and headers in middleware let's modif mod ify our
middleware to handle user preferences for themes and add a custom header for all
responses we start by getting our response object that we will eventually return
from the function so const response is equal to next response. next then using the
request object we check if the user has a theme preference stored in their cookies
so const theme

03:16:43
preference is equal to request. cookies get and the cookie name is theme so if
there is no theme preference response. cookies. set the cookie name is theme and
the value is dark finally we return our modified response object from our
middleware function so return response if we go back to the browser and take a look
at cookies in Dev tools in the application tab you can see they are empty if you
now refresh you can see the Dark theme cookie being set name theme value dark if we
manually overwrite the value to light and then

03:17:27
refresh you can see the value is not overwritten to dark very simple to work with
cookies now headers work just as smoothly let's add a custom header to the response
using response headers set name it custom header and set the value to custom value
go to the network Tab and refresh the page for/ profile under response headers you
will see our custom header with its value custom headers are super useful for
passing extra information which can be used by client side scripts or for debugging
as you can see middleware can

03:18:07
be effectively used to manipulate both cookies and headers in summary middleware
index shes allows you to effectively control and intercept the request response
cycle enabling redirects URL rewrites and the manipulation of headers and cookies
with that we conclude this first section on routing in XS we've covered a wide
array of topics from basic route definition using pages and layouts Dynamic routes
route groups linking and navigation loading and error States and advanced concepts
like parallel routes

03:18:42
intercepting routes route handlers and now middleware I hope you now feel confident
working with routing in X for our next section we will dive deep into rendering in
XS after exploring the ins and outs of next sh's routing in our first section we
are now ready to tackle something equally important in the second section rendering
in XS rendering might sound complex but it is actually pretty straightforward it is
a process of transforming the component code you write into user interfaces that
users

03:19:16
can see and interact with the tricky part to building a performant application is
figuring out when and where this transformation should happen you have probably
heard terms like CSR SSR and RSS being thrown around and maybe they've left you
scratching your head don't worry we're going to break all of this down in a way
that makes sense but before we jump into rendering in next shares let's take a step
back and look at how rendering Works in react itself since nexs is built on top of
03:19:45
react understanding reacts rendering model will make everything else click into
place I should mention we are about to cover quite a few Concepts in this section
if something doesn't make complete sense right away that is totally normal feel
free to pause and rewatch any part that feels unclear trust me sometimes it takes a
couple of passes for these Concepts to really sync in all right with this
introduction in mind let's dive into how react handles rendering to really grasp
how rendering

03:20:18
Works in nexts we need to look at how reacts rendering has evolved over the past
decade let's dive into reacts different rendering strategies and see how they have
changed over time if you've been around web development for a while you probably
remember when react was primarily used for building single page applications when a
client visited your website the server would send back a single HTML page this page
was pretty barebones just a simple div tag and a link to a Javascript file let me
show

03:20:49
you what I mean with an example from create react app which was the go-to tool for
starting react projects you get this minimal HTML file with an empty root div tag
and a reference bundle.js Javascript file this bundle.js is the real powerhouse
which contains everything the react Library your applications code everything
needed to run your application the browser would download this file as soon as the
HTML was processed once your browser downloaded all the JavaScript it would get to
work generating the HTML right

03:21:23
there on your computer injecting it into the Dom under that root div element and
that is when you would finally see your user interface here's a very simple way to
verify this if you check the Dom inspector elements we can see a header with image
and H1 and a paragraph tag but if you view the PID source you'll only see the
original barebones HTML the server sent over this whole approach where your browser
which is the client transforms react components into what you see on screen that is
what we

03:21:59
call client side rendering CSR for short CSR became super popular for single page
applications and everyone was using it however it wasn't long before developers
began noticing some inherent drawbacks to this approach the first big issue was 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 tag which is not great for
search engines trying to figure out what your page is about plus when you have a
lot of nested components

03:22:33
making API calls the meaningful content might load too slowly for search engines to
even catch it the second issue was performance and user experience think about it
your browser which is the client has to do everything fetch data build the UI make
everything interactive and that is a lot of work users often end up staring at a
blank screen or a loading spinner while all this happens and here's the kicker
every time you add a new feature to your application that JavaScript bundle gets
bigger making
03:23:07
users wait even longer this is especially frustrating for people with slower
internet connections while CSR was indeed gamechanging and gave us the interactive
web app We Love Today developers knew they needed better solutions for SEO and
performance up next we will look at another rendering approach that tackles these
CSR limitations headon we just covered client side rendering in react and its two
main drawbacks the first is SEO since content relies on JavaScript to render on the
client side search engines often

03:23:40
struggle to index it properly the second is user experience users have to wait
while their browsers download par and execute JavaScript before seeing any
meaningful content to overcome these drawbacks of client side rendering modern
react Frameworks like Gatsby and Nas move towards serers side Solutions let's look
at how this changes content delivery when a request comes in instead of sending a
bare HTML file that needs client side JavaScript to build the page the server now
handles rendering the

03:24:11
complete HTML this fully formed HTML document goes straight to the browser since
the HTML is already generated on the server the browser can quickly parse and
display it giving us faster initial page load times this server side approach
tackles both CSR issues headon first search engines can now easily index the server
rendered content solving our SEO problem second users see actual HTML content right
away instead of staring at a blank screen or loading spinner but here's the catch
while SSR

03:24:44
makes content visible faster it produces its own complexity around interactivity
the page can't become fully interactive until the JavaScript bundle comprising both
react itself and your applications code has finished downloading and executing in
the browser this important phase known as hydration is where the static HTML page
initially served by the server is brought to live during hydration react takes
control in the browser and reconstructs the component Tre in memory us using the
server rendered HTML as a blueprint it

03:25:19
carefully Maps out where all the interactive elements should go then hooks up the
JavaScript logic things like initializing application State adding click and
mouseover handlers and setting up all the dynamic features needed for a full
interactive user experience understanding hydration is key for what's coming up
next so please make sure you're comfortable with what we have just learned diving
deeper serers side Solutions can be categorized into two main strategies static
site generation

03:25:47
or SSG and server s side rendering or SSR static site generation happens during
build time when you deploy your application to the server this results in pages
that are already rendered and ready to serve it is perfect for Content that stays
relatively stable like blog posts server side rendering on the other hand renders
pages on demand when users request them it is ideal for personalized content like
social media feeds where the each HL changes based on who's logged in you will
often hear both
03:26:20
approaches collectively referred to as serers side rendering or SSR while service
side rendering was a big step up from client side rendering giving us faster
initial loads and better SEO it came with its own challenges the first issue with
SSR is that components cannot start rendering and then pause or wait while data is
still being loaded if a component needs to fetch something from a database or
another source like an API this fetching must be completed before the server can
begin rendering the page this can delay

03:26:53
the server's response time to the browser as a server must finish collecting all
necessary Data before any part of the page can be sent to the client the second
issue with SSR is that for successful hydration where react adds interactivity to
the server rendered HTML the componentry in the browser must exactly match the
server generated component Tre this means that all the JavaScript for the component
must be loaded on the client before you can start hydrating any of them the third
issue with SSR is related to

03:27:24
hydration itself react hydrates the component Tree in a single pass meaning once it
starts hydrating it won't stop until it's finished with the entire tree as a
consequence all components must be hydrated before you can interact with any of
them these three issues having to load the data for the entire page loading the
JavaScript for the entire page and hydrating the entire p page at once create an
All or Nothing waterfall problem that spans from the server to the client where
each issue must be

03:27:54
completely resolved before moving on to the next one this becomes really
inefficient when some parts of your app are slower than others as is often the case
in real world applications these limitations led the react team to develop a new
and improved SSR architecture up next we will explore this architecture and see how
it solves these traditional SSR problems previously we explored the fundamentals of
server side rendering in react and discovered its main drawbacks let's quickly
recap the challenges first we

03:28:28
can't start rendering HTML until all data is fetched on the server second we need
to wait for all JavaScript to load on the client before hydration can begin and
third every component needs to be hydrated before any of them become interactive
these issues create an All or Nothing waterfall effect that is pretty inefficient
especially when some parts of your application are slower than others to address
these performance drawbacks of SSR react 18 introduced the suspense SSR
architecture this new

03:28:58
architecture allows you to use the suspense component to unlock two gamechanging
SSR features HTML streaming on the server and selective hydration on the client
let's explore these two features in detail as we discussed a minute ago
traditionally SSR has been an All or Nothing fa the server renders the complete
HTML which is then sent to the client the client displays this HTML and only after
the complete JavaScript bundle is loaded does react proceed to hydrate the entire
application to add

03:29:30
interactivity but react 18 gives us a better way here is a similar visualization
from a user interface perspective first you render all HTML the client eventually
receives it then you load all the code and hydrate the entire application but react
18 gives us a better way when you wrap something like your main content area in a
suspense component you're telling react hey don't wait for this part start
streaming the rest of the page react will show a loading spinner for that wrapped
section while it works on the

03:30:03
rest of the page when the server finally has the data ready for that main section
react streams the additional HTML through the ongoing stream along with a tiny bit
of JavaScript that knows exactly where to position that h HTML the cool part users
can see the main section's content even before react itself finishes loading on
their browser this solves our first problem you don't have to fetch everything
before you can show anything if a particular section is slow and could potentially
delay the

03:30:33
initial HTML no problem it can be seamlessly integrated into the stream later when
it is ready this is the essence of how suspense facilitates serers side HTML
streaming but we still have another hurdle to jum even with faster HTML delivery we
can't start hydrating until we've loaded all the JavaScript for the main section if
that is a big chunk of code we are still keeping users waiting from being able to
interact with the page to mitigate this code splitting can be used it lets you tell
your bundler these parts of the

03:31:06
code aren't urgent split them into separate scripts using react lazy for code
splitting is particularly powerful here it separates your main sections code from
the core JavaScript B bule this means the browser can download react and most of
your applications code independently without getting stuck waiting for that main
sections code and here's where things get really interesting by wrapping your main
section in a suspense component you're not just enabling streaming but also telling
react it's okay to hydrate other

03:31:35
parts of the page before everything is ready this is what we call Selective
hydration and it is a game changer it allows for the hydration of parts of the page
as they become available even before the rest of the HTML and the JavaScript code
are fully downloaded from a user's perspective here's what happens first they see
non-interactive content streaming in as HTML even though the main sections
JavaScript code hasn't been downloaded yet react starts selectively hydrating and
other parts of

03:32:06
the page can become interactive the main section catches up and becomes interactive
once its code loads this is huge because it means a heavy chunk of JavaScript
script won't hold up the rest of your page from becoming interactive but it gets
even better selective hydration also solves our third problem the necessity to
hydrate everything to interact with anything react starts hydrating as soon as it
can which means users can interact with things like the header and side navigation
without waiting for the main

03:32:36
content and the best part react handles all this automatically also here is
something really clever about how react handles hydration in scenarios where
multiple components are awaiting hydration it prioritizes hydration based on which
components users are trying to interact with let's say react is about to hydrate
the side nav but the user clicks on the main content area react will immediately
switch gears and hydrate the clicked component during the click events capture
phase this means the component

03:33:08
is ready to respond right away the side nav it will get hydrated later so there you
have it reacts new suspense SSR architecture has effectively tackled all three
major drawbacks of traditional SSR but we are not quite done yet despite these
improvements in SSR there are still some challenges we need to think about first
even though we are streaming JavaScript code to the browser bit by bit eventually
users still end up downloading the entire code for a web page as we keep adding
features to our

03:33:40
apps this code keeps growing and this leads to an important question do users
really need to download so much data then there is another issue right now every
react component gets hydrated on the client side whether it needs interactivity or
not this means we're using up resources and slowing down load times and time to
interactivity by hydrating components that might just be static content this leads
to another question should all components be hydrated even those that don't need
interactivity and here's the third

03:34:12
challenge even the servers are way better at handling heavy processing we are still
making users devices to bulk of the JavaScript work this can really slow things
down especially on less powerful devices and this leads to another important
question shouldn't we be leveraging our servers more these challenges point to
something bigger we need smarter ways to build fast applications that go beyond
traditional rendering approaches what is the solution that is exactly what we will
explore next we've seen how reacts rendering has

03:34:47
evolved from client side rendering to serers side rendering and then to suspense
for serers side rendering while each step brought improvements it also introduced
new challenges suspense with SSR brought us closer to a seamless rendering
experience but we still struggled with large bundle sizes causing excessive
downloads for users unnecessary hydration delaying interactivity and heavy client
side processing leading to poorer performance to tackle these challenges we needed
more than just an incremental step we

03:35:19
needed a significant Leap Forward that brings us to react server components RSC for
short react server components represent a new architecture designed by the react
team this approach leverages the strengths of both server and client environments
to optimize efficiency load times and interactivity the architecture introduces a
dual component model differentiating between client components and server
components this distinction is based not on the components and functionality but
rather on their execution environment and the

03:35:51
specific systems they are designed to interact with let's take a closer look at
these two types of components starting with client components client components are
the familiar react components we've been using and talking about in our previous
rendering techniques they are typically rendered on the client side but they can
also be render to HTML once on the server allowing users to immediately see the
pages HTML content rather than blank screen I know it might sound confusing when I
say client components can render

03:36:21
on the server but it is best understood as an optimization strategy these
components primarily operate on the client but can and should also run once on the
server for better performance client components have full access to the client
environment such as the browser allowing them to use State effects and event
listeners for handling interactivity they can also access browser exclusive API
like geolocation or local storage allowing you to build UI for specific use cases
just as we've done all these years before the

03:36:54
introduction of the RSC architecture in fact the term client component doesn't
signify anything new it simply helps differentiate these components from the newly
introduced server components server components on the other hand represent a new
type of react component specifically designed to operate exclusively on the server
and unlike client components their code stays on the server and is never downloaded
to the client this design Choice offers multiple benefits to react applications
let's take a closer look at what these

03:37:27
benefits are first up smaller bundle sizes since server components stay on the
server all their dependencies stay there too this is fantastic for users with
slower connections or less powerful devices since they don't need to download pars
and execute that JavaScript plus there is no hydration step making your app load
and become interactive faster second you get direct access to server resources
server components can talk directly to databases and file systems making data
fetching super efficient without any

03:38:00
client side processing they use the server's power and proximity to data sources to
manage compute intensive rendering tasks third security gets a boost too since
server components run only on the server sensitive data and logic like a keys and
tokens never leave the server fourth data fetching gets way smarter server
components allow you to move data fetching to the server closer to your data source
this can improve performance by reducing time it takes to fetch data needed for
rendering and the

03:38:32
number of requests the client needs to make fifth there is caching when you render
on the server you can cache the results and use them for different users and
requests this means better performance and lower costs since you're not re-
rendering and ref fetching data all the time sixth initial page load and first
contentful paint get a serious upgrade by generating HTML on the server users see
your content immediately and there is no waiting for JavaScript to download and
execute seventh SEO

03:39:04
improves too search engine Bots can easily read the server rendered HTML making
your pages more indexable and finally there is streaming server components can
split the rendering process into chunks that stream to the client as they're ready
this means users start seeing their content faster instead of waiting for the
entire page to render on the server in the react server components architecture
server components handle data fetching and static rendering while client components
take care of rendering the interactive

03:39:34
elements the beauty of this setup is that you get the best of both server and
client rendering while using a single language framework and set of apis it's like
getting all the benefits of traditional r in techniques without their drawbacks we
have covered quite a bit so let me simplify what we have learned with the key
takeaways react server components offer a new approach to building react apps by
separating components into two types server components and client components server
components run exclusively on the server

03:40:05
they fetch data and prepare content without sending code to the browser this makes
your app faster because users download less code however server components can't
handle any inter actions client components on the other hand run in the browser and
manage all the interactive Parts like clicks and typing they can also get an
initial server render for faster page loads together they make websites faster more
secure and more accessible to everyone regardless of their device or location now
you might be thinking okay vas this

03:40:37
is all great information about reacts rendering Evolution but how does this connect
to next shares well here's the thing the app router in nexs is built entirely on
the react server components architecture all these benefits we have just discussed
they're already built into the latest version of next shares understanding the
evolution of reacts rendering provides the foundation needed for you to grasp what
we are about to explore as we dive deeper into next shares well then if you're

03:41:06
comfortable with the react rendering strategies we have covered so far let's
proceed to understanding rendering in next shes previously we explored react server
components and learned about its dual component model that distinguishes between
server and client components now let's put that knowledge into practice by creating
both types of components in an XS application for this second section of the course
on rendering I've created a fresh next year's project using the command npx create
next app at

03:41:38
latest rendering hyphen demo once you run this command you'll have a similar
project structure to work with looking at how the RSC architecture integrates with
nexs there is a key point to remember every component in a nexs application
defaults to being a server component this includes the built-in root layout and
root page that come with every new next year's project but let's create a new
component to verify this we will add an about page to our app by creating a new
folder within the app

03:42:12
folder about with the page TSX file here Define a simple react component export
default function about page that returns an each one about page and just like that
we have created a server component to prove this let's add console.log about server
component in the browser when we navigate to slab notice how it is locked with a
special server tag you can also see the same message in the terminal this confirms
our component is a server component running components on the server brings several
advantages zero

03:42:53
bundle Size Direct access to serers side resources improved security and better SEO
however server components do have limitations they can't interact with the browser
apis or handle user interaction for example if we try to use state in our about
page with the UST State Hook from react so import UST State from from react and
invoke the hook let's call it name and set name we will get an error because US
state requires a client component environment currently our about page is a server
component server

03:43:29
components can't maintain State because they run on the server where browser based
State Management doesn't exist this reinforces the fact that Nexia trats every
component as a server component by default unless explicitly specified otherwise
let's leave the about page as a functioning server component by removing the UST
State hook and learn how to create a new client component we will create a
dashboard SL page. TSX in the app folder that uses state to manage a user's name so
export

03:44:04
default function dashboard page we import and invoke use state name and set name
for the jsx we have a div tag within each One dashboard an input element with value
set to the name State variable and on change we call set name which is our set
function we then have a paragraph hello followed by the name State variable to
convert This Server component into a client component at the top of the file we
must include a directive or to put it simply a special instruction within the code
use client within quotes this directive acts as our

03:44:44
ticket to cross the boundary from server to client side and is what allows us to
Define client components it signals to nexts that this dashboard component along
with any components it Imports is intended for client side execution as a result
the component gains full access to browser apis and the ability to handle
interactivity to navigate to this route let's add a link in our homepage so in the
root page. TSX below the image link the text is Das board each ref is equal to/
dashboard and make sure to

03:45:20
import the link component at the top import link from next slash link if you return
to the browser and navigate to slash dashboard by clicking the link we see the
component with its state functioning as expected hello vishwas let's now look at a
very important point about client components rendering behavior let's add
console.log dashboard client component to our dashboard page component back in the
browser when we click the dashboard link from the homepage the log appears in the
browser

03:45:58
console but without the server tag if you take a look at the terminal we don't see
the message but if we reload the dashboard page the dashboard appears both in the
browser and in the terminal let me explain why this happens when we navigate using
the link component the dashboard component is only rendered client side and we see
the message in the browser console but if we reload the page the dashboard
component is rendered once on the server to allow the user to immediately see the
Page's

03:46:31
HTML content rather than a blank screen and then again on the client side during
hydration this is why we see the message in the browser console and the terminal
the term client component is indeed confusing but you'll get used to this Behavior
as you work with rsc's on a side note the message in the browser is logged twice in
the browser because of the strict mode during development this doesn't happen in
production so don't worry about it to summarize in the RSC architecture and by
extension in the

03:47:04
nexs app router components are server components by default to create client
components at the use client directive at the top of the file server components are
rendered exclusive on the server while client components are rendered once on the
server and then on the client all right up next we will explore the rendering life
cycle of server and client components in nexts we've covered server and client
components in nexts now let's dive into their rendering life cycle in simpler terms
we will explore how they come to

03:47:38
life on your screen understanding this process is not mandatory for building next
year's apps but it's like knowing what happens in the kitchen before your food
arrives at the table not necessary for enjoying your meal but definitely
interesting when we talk about react server components we dealing with three key
players your browser the client and on the server side we have nexs our framework
and react our library let's break down the initial loading sequence step by step
when your browser requests

03:48:07
a page the link shs app router matches the requested URL to a server component next
sh then instructs react to render that server component react renders the server
component and any child components that are also server components converting them
into a special Json format known as the RSC payload if you inspect the network tab
when navigating to a route you will come across this special Json format which is
the RSC payload during this process if any server component suspense react pauses
rendering of that subtree and sends a

03:48:43
placeholder value instead while all this is happening react is also preparing
instructions for the client components we will need later next sh takes both the
RSC payload and the client component instructions to generate HTML on the server
this HTML streams to your browser right away giving you a quick non-interactive
preview of the route at the same time nexs also streams the RSC payload as react
renders each piece of UI once this reaches the browser nexs processes everything
that was streamed

03:49:16
over react uses the RSC payload and client component instructions to progressively
render the UI once all the client components and the server components output has
been loaded the final UI state is presented to the user client components under go
hydration Transforming Our application from a static display into an interactive
experience this is the initial loading sequence for rsc's now let's take a look at
the update sequence for refreshing parts of the application the browser requests a

03:49:48
refetch of a specific UI such as a full route next processes the request and
matches it to the requested server component next instructs react to render the
component tree react renders the components similar to what happened during initial
loading but here's where it's different we don't generate new HTML for updates
instead next year progressively streams the response data straight back to the
client on receiving the stream response nexts triggers a reender of the route using
the new

03:50:18
content react then carefully reconciles or merges the new rendered output with the
existing components on the screen because we're using a special Json format instead
of HTML react can update everything while keeping important UI States intact things
like where youve clicked or what you've typed this is the RSC update sequence all
right now that we understand the react seever components rendering life cycle let's
dip deep into the topic in XS there are three different ways rendering can

03:50:49
happen on the server static Dynamic and streaming let's take a closer look at each
of these next earlier I mentioned the three server rendering strategies in next SH
now let's dip into the first one static rendering static rendering is a server
rendering strategy where we generate HTML pages when building our application think
of it as preparing all your content in advance before any user visits your site
once built these Pages can be cached by CDN and served instantly to users what's
really cool

03:51:24
about this approach is that the same pre-rendered page can be shared among
different users giving your app a significant performance boost this makes static
rendering perfect for things like blog posts e-commerce product listings
documentation and marketing Pages now that we understand what is static rendering
and when to use it you might be wondering how do we actually use it or more
specifically how do we tell NS to statically render a specific route here's the
good news you don't have to

03:51:53
do anything special static rendering is the default strategy in the app router all
routes are automatically prepared at build time without any additional setup now
you might be thinking hold on you keep talking about generating HTML at build time
but we haven't built our application right we're just running it in development
mode now that is a great question let's talk about the difference between
production and development servers in production we create one optimized build and
deploy it now on the

03:52:25
flight changes after deployment a development server on the other hand focuses on
the developer experience and we need something more flexible we need to see our
changes immediately in the browser without rebuilding the app every time that is
why the next team made a clever decision in production pages are pre-rendered once
during the build but in development pages are pre-rendered on every request visit
the homepage it is pre-rendered and served refresh pre-rendered again and served
this ensures you always see your latest code

03:52:57
changes in every request nexts also displays a static route indicator during
development to help you identify which routes are static I will say though don't
worry too much about static generation during development what really matters is
understanding how it works when you build your app for production before we dive
into the build process let's stop the dev server and clean up by deleting the next
folder that was generated during development next let's add a link to our about
page from the root page. TSX file

03:53:32
so duplicate the link to dashboard and change HF as well as the text in the above
page let's also render the current time so about page within curly braces new
date . to loal time string this will help prove a point later now in the terminal
run the command npm run build this creates an optimized production build of our
application the output goes into the next folder again but this time the contents
will be quite different from what we saw during development there is quite a bit to
unpack here so let's start with what we

03:54:10
see in the terminal you'll notice three columns showing information about each
route route size and first load JS route is pretty straightforward it is the route
itself so SL about and/ dashboard for example size shows how much data needs to be
downloaded when navigating to that corresponding page client site in the browser
first load J tells us how much gets downloaded when initially loading a page from
the server let's break down these numbers first there is a shared bundle that all
routes use it includes

03:54:44
your Global CSS runtime code framework code vendor code like react for example and
some route related code this shared bundle comes in at 105 KB looking at individual
routes a root page from page. TSX in the app folder is 8.4 KB however when someone
visits the homepage they will download both this and the shared bundle totaling 114
KB nexts also generates a 404 not found page automatically it is Tiny at 979 bytes
but needs 106 KB with the shared bundle the above page which is a server component
is quite

03:55:25
lightweight at 136 bytes for client side navigation and 105 KB for Server loads the
dashboard page which is a client component is slightly larger at 370 bytes and 106
KB from the server next to each route you will see some symbols and at the bottom
is a next year's Legend showing how each route is rendered our root route page. TSX
has a Hollow Circle indicating static rendering the same goes for not found about
and dashboard as well they all are pre-rendered at Bill time as static HTML these
indicators are super helpful when

03:56:06
you're getting started with next sh and want to understand what's happening under
the hood now let's dive into the build output next puts everything in the nextt
folder which has all the files needed to serve our application to the browser we
will focus on two main folders server and static inside the server folder there is
an app folder that matches our application's route structure let me show you the
important files you'll find here first up we have the HTML files see how our build
info

03:56:38
shows the root page as static you'll find that as index.html within the app folder
same story with our not found page not found. HTML we've also got an about. HTML
with its H1 HTML about page and the timestamp and dashboard. HTML with its heading
input and paragraph you might wonder why we see HTML for client components that is
because even client components are pre-rendered as an optimization step something
we already discussed when learning about client components but HTML files are in
the Whole Story Each

03:57:15
route also gets what is called an RSC payload for example about. RSC for the about
server component and dashboard. RSC for the dashboard client component these files
with a special Json format are generated by react for each route and represent your
virtual Dom in a super compact way using abbreviations and internal references for
Server components this payload includes the actual rendered result like the H1 tag
with about page text in it client components work a bit differently their payload
has

03:57:50
placeholders showing where the client components should go plus references to their
JavaScript files our dashboard routs payload for example points to where its
component code lives static chunks app dashboard page hyphen DD 953b DJs next to
the server folder we've got this static folder dig into static chunks app and you
you'll find all our routes the dashboard folder here has that component code file
we saw referenced in the RSC payload the stuff needed for reconciliation and
hydration

03:58:25
the H1 tag dashboard input and so on now that we understand the build output let's
serve our application from the folder run the command npm Run start visit lcos 3000
and with your Dev tools open do an empty cache and hard reload look at the
different resources that get downloaded first thing to check is this Local Host
request it is coming in as a document type this is the index.html we saw earlier in
the server app folder click on preview and you can see the preview of the HTML page
the response shows you the HTML code apart

03:59:09
from the HTML I want to draw your attention to the two RSC files dashboard _ RSC
and about uncore RSC these are essential for building the UI on the client side
when we navigate to slab or/ dashboard using the links there's also the dashboard
component code page hyphen DD 953b DJs that has been downloaded here's what's cool
clear your network Tab and click around to about and dashboard so about component
and dashboard component notice how they render instantly without hitting the server
that is because the

03:59:50
initial load included everything required for client side navigation so we already
have everything we need right in the browser but wait how did next sh know to send
us the about and dashboard stuff before we even clicked anything that is thanks to
a feature called prefetching a clever technique that preloads routes in the
background as their links become visible for static routes like ours nextjs
automatically prefetches and caches the whole route so when our homepage loads with
the links to about and dashboard nexts is already

04:00:23
prefetching about and dashboard routes for instant navigation but what about the
about. HTML and dashboard. HTML files we saw earlier in the server folder well when
you type the URL directly or hit refresh in the browser that is when you get the
full HTML document straight from the server so when you navigate to local first
3000 slab this time you see the about document which is HTML for/ dashboard with
the HTML you will also receive the code needed for hydration oh and remember the
timestamp we added to

04:01:02
the about page notice how it stays the same no matter how many times you refresh
that is because it was locked in when we built the application we will Explore More
about rendering but here is what we've learned static rendering is a strategy where
the HTML is generated at build time along with the HTML rscp loads for components
and JavaScript chunks for client side hydration are created direct route visits
serve HTML files while client side navigation uses RSC payloads and JavaScript
chunks

04:01:35
without additional server requests this makes static rendering excellent for
performance especially in blogs documentation and marketing pages I know this is a
lot to take in if some parts feel fuzzy I would encourage you to try this out
yourself run the code watch the network Tab and experiment the best way to
understand these Concepts is to see them in action my goal isn't just to show you
how to use next shes but to help you understand why things work the way they do
previously we learned about the first

04:02:08
server rendering strategy namely static rendering now let's dive into our second
strategy Dynamic rendering Dynamic rendering is a server rendering strategy where
routes are rendered uniquely for each user when they make a request it is useful
when you need to show personalized data or information that is only available at
request time things like cookies or URL search parameters news websites
personalized shopping pages and social media feeds are some examples where Dynamic
rendering is beneficial now that we
04:02:40
understand what is dynamic rendering and when to use it you might be wondering how
do we actually implement it how do we tell next sh that we want a particular route
to be dynamically rendered well it is quite straightforward xjs automatically
switches to Dynamic rendering for an entire route when it detects what we call a
dynamic function or dynamic API in XS these Dynamic functions are cookies headers
connection draft mode search patterms prop and after which is a new API using any
of these automat

04:03:14
automatically Ops your entire route into Dynamic rendering at request time let's
write some code to understand better back in vs code let's modify our about
component by importing and using the cookies Dynamic function at the top import
cookies from next SL headers convert the component to an async function so export
default async function about page and within the function body const cookie store
is equal to a weight cookies then const theme is equal to cookie store.get let's
pass in the name of the cookie as

04:03:53
theme we will log theme to the console don't worry too much about what we're doing
with the cookies function right now we're just using it to trigger Dynamic
rendering for this about page with this code in place let's build our application
and inspect the output from Dynamic rendering I'll first clear out the next folder
and then run npm run build in the terminal this will take a moment to generate a
newex build folder first let's look at the build output in the terminal we can see
all our generated

04:04:28
routes listed pay close attention to the about route it has an F symbol next to it
if you check the legend you will see that F indicates Dynamic rendering server
rendered on demand the next important point to remember is that dynamically
rendered pages are in generated during build time if we inspect next server app we
will see HTML files for index dashboard and not found but we won't find an HTML
file for the up page finally let's start our application with npm Run start in the
browser when we go

04:05:05
to slash about and empty cache and hard reload the page renders on demand and you
will see the lock statement in the terminal name theme value light this cookie was
set when we were learning about the cookies function earlier check out the network
Tab and you will see both the preview and the response containing the HTML each
time you refresh you will get the latest time if you inspect the build folder there
is still no HTML file generated in the server folder since we're building a new
page for each

04:05:40
request there is simply no need to store it what what I've just explained might
seem trivial after understanding static generation builds however it is important
to remember that building our application and running the built app is as close as
we can get to production deployment so I wanted to make sure you understand how it
works here is what we've learned Dynamic rendering is a strategy where the HTML is
generated at request time next she automatically enables it when it encounters
Dynamic
04:06:11
functions like cookies headers connection draft mode after or search params prop
Dynamic rendering is great for personalized content like social media feeds one of
the best parts about NEX Shar is that you don't have to stress about choosing
between static and dynamic rendering NEX Shar automatically selects the optimal
rendering strategy for each route based on the features and apis you're using but
if you want to force a route to be dynamically rendered you can use export const
Dynamic is

04:06:42
equal to force Dynamic cont at the top of your page now that we understand static
and dynamic rendering let's dive into generate static params a really interesting
feature in next sh in simple terms generate static params is a function that works
alongside Dynamic route segments to generate static routes during build time
instead of on demand at request time giving us a nice performance boost I know this
might sound a bit complex so let's walk through a practical example together we
will build a product listing and Details

04:07:18
page to see how this works in action first in our app folder we're going to create
a new products folder and add a page. TSX file with a react component for
displaying featured products export default function products page and we return an
H1 tag that says featured products and three links to the three featured products
product one 2 and three next we will create an ID Dynamic route so Within products
ID within square brackets with a page. TSX file to show individual product details
let me paste the code to

04:07:57
save us some time export default async function product page which receives route
params we await params and destructure the product ID we return an H1 tag product
ID details rendered at timam when we build our application using npm run build
something interesting happens if you look at the terminal you will notice that Niar
handles the product list page and product Details page differently the product list
page gets static rendering while the product detailed speech is set up for dynamic
rendering and this makes

04:08:35
sense right nexs doesn't know what id value it will need until someone actually
requests a specific URL take a look at the build folder specifically within server
slapp and you will find the HTML file for products. HTML but you won't see anything
for the product Details page if you run the app with npm Run start and visit SL
products SL1 you will see the timestamp change every time you refresh the page this
is because the product Details page is rendered on demand at request time from our
previous learning we know that

04:09:16
static rendering gives us better performance wouldn't it be great if we could tell
next to prender at least our featured products detail Pages product one 2 and three
well that is exactly what generate static parms helps us do let's look at how to
implement it in the product Details page we will add a generate static params
function which is an async function that returns an array of objects each object
represents a route we want to pre-render with the object key corresponding to a
route's dynamic
04:09:51
segment we want ID with 1 2 and three this function runs during build time while we
are just returning an array here you could also fetch these IDs from an API if we
rebuild our application now with npm run build you will see next sh PR rendering
the product details pages for all three featured products SL1 SL2 and slash3 this
is indicated by the new symbol a filled Circle and if you check the legend it says
SSG pre-rendered as static HTML using the generate static params function you can
also confirm

04:10:34
this by checking the build folder so server app and products you'll Now find HTML
files 1. HTML 2html and 3. HTML corresponding to our IDs start the application with
npm Run start and navigate to/ product SL1 notice how the timestamp stays the same
when you refresh this is because we are now serving a pre-rendered HTML file now
what about routes with multiple Dynamic segments let's say we have a product
catalog with categories and products using a route like/ products SL category SL
product/ page. TSX in this

04:11:18
case each object includes values for both Dynamic segments needed to pre-render the
route category Electronics smartphone Electronics laptop books and science fiction
books and biography generate static patterms is perfect for scenarios like featured
products or popular blog posts generate static PMS is a powerful feature in XS that
lets you pre-render static routes for dynamic segments it runs at build time
handles multiple Dynamic segments and can really boost your application's
performance by ensuring that frequently

04:11:53
accessed pages are pre-rendered and ready to serve instantly now I bet you're
wondering what happens to Pages where the ID isn't included in generate static
params let's explore that next previously we learned about the generate static
params function it lets us pre-render static routes for Dynamic segments by
returning an array of objects where the keys match our Dynamic route parameters in
our example we are returning objects with ID values of 1 2 and three which means
next we'll

04:12:26
pre-render product detail Pages for these three products at build time pretty
straightforward right but here is an interesting question what happens when someone
tries to access a product page with an ID that is not in our generate static params
function list like products with ID 4 5 and so on well nexs has got us covered it
will still render those pages just not in advance instead it statically renders
them at run time let me show you what I mean in the browser if we navigate to/
products sl4 you will notice the page still works

04:13:03
and if we inspect our build folder next server app products we now see 4. HTML this
file was generated at runtime when we visited / products sl4 and since the page is
statically rendered the time stamp will not change each time we refresh the page
let's try this again with SL product sl5 notice there is no five. HTML file in our
build folder visiting SL products sl5 will generate a new HTML file with the
current time and you can now see that file in the build folder 5 HTML this file is
served to the client

04:13:47
now nexas actually gives us some control over this Behavior through a setting
called Dynamic params by default Dynamic params is set to True which means NEX will
statically render pages on demand for any Dynamic segments not included in generate
static parms but here's where it gets interesting we can set it to fals which tells
NEX sh to return a 404 error for any Dynamic segments not included in our pre-
rendered list let's say this an action I will change Dynamic params to false stop
our production

04:14:22
build and rebuild with the command npm run build start the server with npm Run
start now if we try going to SL products sl4 we get a 404 page so Dynamic patterns
true and dynamic params false the value controls what happens when the dynamic
segment is visited the that was not generated with generate static patterms now you
might be wondering when should you use each option well it really depends on your
use case if you're building an e-commerce site you will probably want to keep
Dynamic patterms said to true this way you can

04:14:58
pre-render your most popular product pages for better performance but still allow
access to all your other products they will just be rendered On Demand on the flip
side if you're working with something like a Blog where you have a smaller more
fixed number of pages you can pre-render all of them and set Dynamic params to
Falls this way if someone tries to access a blog post that doesn't exist they will
get a clean 404 error instead of waiting for a page that will never exist so that
is about

04:15:28
dynamic parms in a nutshell it's a simple setting that gives you powerful control
over how Nexus handles those Dynamic segments that are not included in generate
static patterns let's dive into streaming the third and final server rendering
strategy streaming is a strategy that allows for Progressive UI rendering from the
server work is broken down into smaller chunks and stream to the client as soon as
they're ready this means users can see parts of the page right away without waiting
for everything to

04:15:58
load it is particularly powerful for improving initial page load times and handling
UI elements that depend on slower data fetches which would normally hold up the
entire route this might sound familiar if you recall our suspense for SSR
discussion about reacts rendering the key difference here is that we're looking at
it through nexs where streaming comes built right into the app router let me show
you how to set up suspense boundaries in your application to save time I've set up
a route called product reviews that

04:16:30
renders three elements and each one saying product reviews a product component a
reviews component these components live in our source SL components folder for both
components I've added intentional delays 2 seconds for the product component and 4
seconds for the reviews component this delay M makes what it would be like if we
were actually fetching data with our Dev server running if we visit local Hurst
3000 SL product reviews so product hyphen reviews you will notice the page takes a
while to show anything even just

04:17:08
the H1 element check the network Tab and you will see for product reviews the
server response time is 6 seconds that is because it is fetching everything before
sending anything let's improve this using the streaming strategy supported in the
app router it is super simple we just wrap our slower components with suspense and
EXs handles the rest at the top import suspense from react and wrap both product
and reviews components with the suspense component on the suspense component
specify the

04:17:43
fallback prop let's go with a simple paragraph tag that says loading product
details and another loading reviews now watch what happens when we reload The
Heading appears instantly followed by the product details after 2 seconds and
finally the reviews after 4 seconds while the components are loading we will see
the fallback text loading product details and loading reviews this is Progressive
HTML Ren ing in action from the server to the client and that wraps up our look at
server rendering

04:18:19
strategies in xgs we've got one more crucial rendering topic to cover next so let's
dive into that now that we have built a strong Foundation understanding RSC and the
Dual component model it's time to explore server and client composition patterns
I'll give you a quick overview here and then we'll take a deeper look at specific
use cases for server and client components as we continue let's begin with server
components these are your go to choice for several key tasks fetching data
accessing pack and

04:18:51
resources directly keeping sensitive information secure on the server and handling
large dependencies server side which means less JavaScript for your users to
download moving on to client components these are your best friends when it comes
to adding interactivity handling event listeners managing State and life cycle
effects working with browser specific apis implementing custom hooks or using react
class components while these use cases might sound straightforward there's actually
quite a bit more to unpack about using

04:19:23
these components effectively let's dive deeper into these patterns next for our
first server component pattern let's talk about the separation of serveron code
when building NS applications some code is specifically designed to run exclusively
on the server think about modules or function s that handle environment variables
communicate directly with databases or process sensitive information since
JavaScript modules can be shared between server and client components code meant
for the server could accidentally find

04:19:56
its way to the client this is bad news as it can blow to your JavaScript bundle
expose your secret Keys database queries and sensitive business logic it's super
important to keep serveron code separate from client side code luckily there's a
neat solution to this problem we can use a package called server only that throws a
build time error if someone accidentally Imports server code into a client
component let me show you how this works let's jump into vs code and create two
components first we will

04:20:28
create a server route SL page. TSX with a simple react component export default
function server route page that returns an H1 tag server route then we will create
in the folder once again client route SL page. TSX with another react component
adding the use client directive at the top export default function client route
page return an H1 element client route now in the source folder let's make a new
utils folder with a new file called server utils dots server hyphen utils dots
we'll create a function that is

04:21:13
meant to run only on the server the actual implementation isn't important right now
we just want to demonstrate the concept so here is a function with a loog statement
and a return value export const server side function console.log and a return
statement this function could be doing all sorts of server side stuff using npm
packages accessing environment variables for API Keys making database calls or
handling sensitive business logic and calculations before returning a value the
implementation is not important

04:21:48
right now but let's use this function in our server component So within server
route page. TSX import server site function from util SLS server utils and within
the function body const result is equal to server site function find result in the
H1 in the browser when you visit Local Host 3000 SLS server hyphen route you'll see
the log message with the server tag and you'll see them in the terminal as well
that is because our code is running on the server we also see Server result as part

04:22:28
of the H1 tag now what happens if we use this function in our client component copy
the import statement paste it in client route page. TSX const result is equal to
server site function and we bind it result if you navigate to/ client route you'll
notice the log messages but this time without the server tag in the terminal for/
client route we see the log messages but we see them again in the browser as the
client component executes this is exactly what we want to prevent given the nature
of the

04:23:11
operations in server s side function it is crucial to ensure that it executes only
on the server if this codes ends up in the client bundle you're looking at
potential performance issues from larger bundle sizes and heavy computations
security risks from exposed sensitive logic and possible functional errors when
server specific code tries to run in the browser here is where server only package
comes to the rescue let's install it with npm install server hyphen only once it is
installed import it to your

04:23:46
server utils dots file at the very top import server hyphen only now if anyone
tries to import this module into a client component the build will fail immediately
preventing any potential issues related to exposing server side code to the client
it's like having a security guard that stops server code from sneaking into the
client bundle in summary keeping server only codee separate from client side code
isn't just good practice it is essential for security performance and reliability
the server only package

04:24:23
helps enforce this separation making your application more robust and secure all
right let's proceed to the next pattern for our second server component pattern
let's explore working with third party packages server components have introduced
an exciting new paradigm in react and the EOS system is evolving to keep up
thirdparty packages are starting to add the use client directive to components that
need client side features making it clear where they should run here's the thing
though many

04:24:54
npm packages haven't made this transition yet this means while they work fine in
client components they might break or fail completely in server components don't
worry though there is a straightforward solution we can wrap the third party
components that need client side features in our own client components let me show
you how this works with a real example we will use react slick a popular Carousel
component from npm that relies on client side features to get started let's install

04:25:24
the necessary packages in the terminal run the command npm install react hyphen
slick slick Harel and add types SL react slick now we have an error because we are
using react 19 so run the command by adding -- Force next I'll open the playground
example in npm from here we will grab the sample code copy the code in image
slider. jsx to client rout page. TSX this is a client component start with the
Imports followed by the jsx we can remove the CSS import line and instead copy the
CSS from image

04:26:16
slider. CSS to global. CSS change color black to white as we working with dark mode
in the jsx pleas kitten does not work anymore so let's use pix some do photos
instead back in the browser when you check localhost 3000 client route you you
should see a perfectly working Carousel now what happens if we try to use this
Carousel directly in a server component let's paste the same code into server route
page. TSX so the Imports copy and paste into server route page. TSX and then the
jsx copy and paste in the browser when we

04:27:13
visit SLS server route we hit a problem why well the slider component uses client
side features but the library itself doesn't include the use client directive sure
we could add use client to our server route but that would mean giving up valuable
serers s side capabilities like database calls access to secret environment
variables Etc to resolve this you must encapsulate third party components that
depend depend on client only features within your own client component so in the
components folder create a new file

04:27:50
image slider. TSX we will use the same Carousel code but add the use C directive at
the top we'll also rename this to image slider as a named export now our server
component can be cleaned up to Simply use the image slider component import it at
the top and invoke it as part of the jsx our server site function can be reinstated
our image slider component can be imported and it can be included in the jsx we
still have a server component but now with one element behaving as a client
component check the

04:28:36
browser again and we see the component working as expected server route followed by
server result and we have the carousel we see just the one image from pixum but if
you work with local images you will see all of them in summary thirdparty packages
in the react ecosystem are in a transitional phase where numerous components from
npm packages haven't yet adopted the use client directive wrapping such components
in our own client components will allow us to leverage the ecosystem of thirdparty
packages while adhering to

04:29:10
the new server components model all right we have one more Ser component pattern to
cover let's see what that is next for our final server component pattern let's
explore working with context providers if you're familiar with react you know that
context providers typically live near the root of an application to share Global
State and Logic for example your application's theme however there is a catch with
the RSC architecture react context is not supported in server components if you

04:29:44
try to create a context at your application route you will run into an error the
solution is to create your context and render its provider inside a dedicated
client component let me show you how this works in vs code we start with layout.
TSX in the app folder here let's set up and provide a theme context that our entire
application can use import create context from react next we Define the theme type
which has colors as an object primary of type string secondary of type string as
well next we Define the default theme so

04:30:26
default theme of type theme colors object Define a primary color and a secondary
color next we Define const theme context is equal to create context of type theme
and we pass in the default theme finally we wrap the body tag with theme context do
provider value is equal to default theme and we add the closing tag when we save
this and check our browser we will see an error you're importing a component that
needs create context this react hook only works in a client component now we could
add the client

04:31:12
directive to make layout. TSX a client component but that would tell nexs to run
this component and everything it Imports on the client side that is not what we
want instead let's create a context and render its provider in a separate client
component in the components folder let's create a new file called theme hyphen
provider. TSX since we have seen the code already I'll paste it here to save us
some time let's break this down we've got our type default theme and theme context
creation just like before

04:31:48
we're now exporting a theme provider component that renders theme context. provider
with our default theme value and renders any children pass to it I have also added
a convenient used theme hook that any component can use to access the theme but the
most important part is the use Clan directive at the top back in layout. TSX we can
now simplify our code with the theme provider delete create context import and
instead import the theme Provider from our theme provider. TSX file delete the code
for type theme the

04:32:26
default theme the context creation and for the jsx specify the theme provider
component to test this out let's use our theme context in the client route page so
in page. TSX which is a client component import the use theme hook and use it to
access the theme const theme is equal to use theme and for the jsx we will delete
the carousel code and apply the primary color to an H1 element L route page and
we're going to specify inline Styles color theme. colors. primary the component is
now a very

04:33:08
simple component in the browser head to slash client route and you'll see the
client route page in our primary blue color switch it to secondary and it turns
gray our theme provider is working as expected now here is something important to
make note of even though we are wrapping our application in a client component
which is theme provider server components further down the tree stay as server
components we will explore this concept more deeply pretty soon but this is the key
to working with context providers

04:33:46
and server components instead of converting your server component to a client
component create a new client component and use it within your server component
with the children props if you're using react version 19 you can render just
context as a provider instead of context. Provider so theme context. provider can
be rendered as just theme context head to the browser refresh and you will continue
to see the same result all right up next let's dive into client component patterns
for our first client component

04:34:24
pattern let's talk about the separation of client only code earlier we looked at
server only code in nexs applications and now we are going to flip things around
and focus on client only code just like how we need to keep certain operations
server side it's equally crucial to keep some functionality strictly on the client
side now what exactly is client side code well it's code that works with browser
specific features like Dom manipulation window object interactions or local storage

04:34:53
operations these features aren't available on the server so we need to make sure
such code runs only on the client side to avoid server side rendering errors to
prevent unintended server side usage of client side code we can use a package
called client only let's dive into vs code and understand with an example from
earlier we have our server route which is a server component and client route which
is a client component now let's add a client only function in the source folder
inside the utils folder

04:35:26
create a new file called client u. TS we will Define a function that's meant to run
only on the client side the actual implementation isn't important right now we just
want to demonstrate the concept so here is a simple function with a lock statement
and a return value export const client side function console.log use window object
use local storage and return a client result this function could use any browser
specific features like window or local storage things that would not work server
side let's import

04:36:00
and use this function in our client route component at the top import client side
function from ms/ client details and within the component const result is equal to
client side function we will render a paragraph tag for the result when you run
this in the browser you will see the log messages pop up in the console use window
object use local storage we also see the client result being rendered in the UI
there is no special server tag and this confirms that everything is running client
side as planned now let's Safeguard our client

04:36:40
only code start by installing the client only package in your terminal run the
command npm install client hyphen only if you come across an error specify -- Force
once the command complete import it at the top of the client .ts file so import
client only when we import client only in a module it creates a safety net if
someone tries to use this code on the server site it will fail at build time let's
import and use this client site function in server rout page. TSX file so copy the
import statement paste

04:37:25
it copy the invocation paste it call this client result and render it as part of
the H1 tag save the file and in the terminal you should see an error you're
importing a component that Imports client only it only works in a client component
but none of its parents are marked with use client so they server components by
default this error acts as a clean signal to developers about the inappropriate use
of client specific code in a server context you will also notice the same error
when you navigate

04:38:00
to/ server route instead of running into problems when your application is running
you'll catch these issues early during development in summary just as server only
code needs isolation client only code needs to stay on the client side where it can
properly use browser features the client only package acts as our safety net making
sure our client side code stays right where it belongs which makes our apps more
reliable and easier to maintain all right let's proceed to the next client
component

04:38:31
pattern let's dive into our second and final client component pattern the Strategic
placement of client components in your component tree this is super important for
optimizing the performance of your application since server components can't handle
State and interactivity we need client components to fill the Gap the key
recommendation here is to position these client components lower in your component
Tre let me show you why this matters I've prepared some code to demo this concept

04:39:00
in our project I've set up a new route called landing page and also created three
new components in the components folder nav bar nav search and nav links before we
dive into the code let me explain what we are building picture a landing page with
a nav bar at the top and a main content area below we will focus on the Navar today
it consists of an outer wrapper which is the Navar component itself containing two
inner components nav links for navigation links and nav search with a search bar

04:39:33
that lets users search through our site this creates a simple component Tre the
landing page component sits at the top with a nav component as its children I have
already implemented this structure in our nexts application so let me walk you
through it looking at landing page component you will notice we've imported the
Navar component at the top inside this Navar component we have broughten both nav
links and nav search these components simply output text for Now list of nav links
nav search input each

04:40:07
component includes a console log to show when it renders so console log Navar
rendered nav links rendered and nav search rendered don't worry too much about the
specific implementation details as we're focusing on understanding the component
hierarchy let's check this out in the browser by going to slash landing page take a
look at the dev tools console and you will see lock statements with the server tag
because these are all server components you can confirm this by looking at the

04:40:38
terminal where you'll spot the same lock statement Navar rendered nav links
rendered and nav search rendered right now our search bar doesn't have any state
associated with it let's introduce a state variable to track the value of the
search input we'll do this in the navbar component import use state from react and
invoke the use State hook let's call it search set search initial value empty
string when we save this we get an error our navbar component isn't marked as
client component let's fix

04:41:17
that by adding the use client directive at the top after saving and refreshing we
now see client side lock statements in the browser for all three components now bar
rendered now links rendered Now search rendered all of them without the server tag
and don't worry about seeing the locks twice that is just reacts strict mode in
development but here is a thought if you CL client is declared in the Navar
component shouldn't that be the only component running client side well this is a
common misconception when

04:41:50
you mark a component with used client it doesn't just affect that component but
also affects every child component in the component Tre below it in our case nav
links and nav search become client components as well think of use client as
drawing a line in your component tree and everything below that line runs on the
client side it is crucial to understand this concept especially when you're working
with larger component trees if you convert a high level component to a client
component just to

04:42:19
add some interactivity you're accidentally making its entire sub tree of children
run on the client too this means sending more code to the browser and losing the
benefits of server components that is why we want to push client components as far
down the tree as possible ideally making them Leaf components in our case we can
make this better instead of making the Navar a client component we can keep it as a
server component and just convert nav search to a client component it's the only
one that actually needs State back

04:42:52
in vs code let's move use client to nav search along with the state the use State
hook as well in the browser reload the page and you will see only nav search
running on the the client side Navar and nav links have the server tag so that is
about client component placement within the app router let's wrap up this section
on rendering by diving into the supported and unsupported patterns of inter leaving
server and client components in next trust me this is best understood through
examples so let's jump right

04:43:34
into some code first create a new route called inter leing within the app folder
add a page. TSX file inside it we will need a few components to demonstrate this so
in the components folder let's create both server and client components let's start
with our server component create server component 1. TSX let's name it server
component one export const server component one and this is a function that returns
an H1 tag server component one let's also include a server only operation like a
file

04:44:17
system read in this component at the top import FS module and within the component
invoke fs. readfile sync passing in a path and utf8 as second argument we are not
concerned about the result of this read file method so we can skip the assignment
this is our first server component duplicate this file so copy and paste and name
it server component 2 update the component name as well as the read file argument
so server component 2 server component 2. TSX and the H1 server component 2 now for
our client component within the same

04:45:01
components folder create client iph component hyphen 1. TSX and name it client
component one export const client component one and this is equal to a function
that returns an H1 tag client component one here include a client only operation
like a use State call so add the use Cent directive at the top import use state
from react and invoke it within the component const name comma set name is equal to
use State and the initial value is Batman once again we are not not worried about
using the state variable or the seter function

04:45:44
within our component this is our first client component let's duplicate this file
so copy paste it rename this to client component 2. TSX update the component name
and the jsx now let's define a component in inter leaving page. TSX file export
default function ENT leaving page and we return and H1 tag inter leaving page now
that we have all our components ready let's explore the different inter leing
patterns first is server component inside another server component now our
interleaving route is already a server

04:46:27
component but let's make use of the other components we've just created so at the
top import server component one into page. TSX invoke it and then within server
component One Import server component 2 and include it in the jsx so H1 server
component one and then server component two in the browser navigate to slash inter
leaving and you should see the route working without any issues server component 2
nested inside server component one which is nested inside into leing component our
first

04:47:07
pattern of server component inside another server component works as expected the
second pattern is client component inside another client component so in page. TSX
within inter leaving folder import client component one and invoke it then Nest
client component two inside client component one so import client component two
wrap each one with react fragment and invoke client component to check the browser
and you can see this works perfectly fine as well client component 2 nested inside
client component one nested

04:47:48
inside inter leing page our second pattern of client component inside client
component also works perfectly fine the third pattern is client component inside a
server component so import server component one into page. TSX and then next client
component one inside server component One Import client component one and invoke
client component one check the browser and you can see this pattern also works
without any issues client component 2 is currently nested inside client component
one which is nested inside server

04:48:30
component one which is nested inside inter living page component so the third
pattern of client component inside a server component works perfectly finally let's
take a look at server component inside a client component so in inter leing page.
TSX import client component one then Nest server component one inside client
component One Import server component one and invoke it when you save the file and
check the browser you will see an error module not found can't resolve FS why
because any

04:49:15
component nested inside a client component automatically becomes a client component
too since client components render after server components you can't import a
server component directly into a client component even though server component one
is defined as a server component when it is nested inside a client component it
transforms into a client component which is executed client side in the client
environment there is no file system module and hence the error so it is important
to remember

04:49:49
that importing a server component into a client component is a pattern not
supported in xjs but don't worry there is a neat workaround instead of nesting the
server component pass it as a prop to the client component a common approach is
using reacts children prop to create what is called a slot so in inter leaving
page. TSX pass server component one as children props to client component one
opening and closing tag and Nest server component one in client component one
specify children prop of type react. react node and

04:50:30
instead of importing and invoking server component one we specify the children prop
check the browser now and everything works fine C C component nested inside server
component which is nested inside client component this is the recommended pattern
for interleaving server and client components in xjs and remember you're not
limited to just the children prop you can use any prop on the client component that
brings us to the end of our second section which is a deep dive into rendering in
XS we've

04:51:03
covered everything from CSR and SSR to suspense rsc's component types rendering
life cycles static and dynamic rendering streaming and these composition patterns
you should now have a solid grasp of how rendering works in the next year's app
router there is plenty more next year's goodness coming up so please stay tuned for
the next section in our previous two sections we have covered routing and rendering
now let's dive into our third section data fetching and mutations in XS so far
we've been working with

04:51:39
hardcoded content in our routes and components but let's be real in actual
Enterprise applications you're usually pulling data from external sources the app
router is built on react server components architecture which gives us the
flexibility to fetch data using either server components or client components
however it is usually preferable to use server components for data operations
because you can directly communicate with your databases and file systems on the
server side you can get

04:52:09
better performance since your closer to your data sources your client side bundle
stays lean because the heavy lifting happens server side and your sensitive
operations and apepi keys remain secure on the server throughout this third section
I'll show you how to handle data in both client and server components but we will
mainly focus on server components to get us started with the section on data
fetching I've already set up a fresh next year's project in vs code using the
command in X create next

04:52:42
app at latest TAA hyphen fetching hyphen demo go ahead and run this command you
should end up with the same project I have here now that we are all set up let's
dive into Data fetching with next shs let's learn how to fetch data in the next app
router first things first we need some actual data to work with I'm going to
introduce you to Json placeholder a free fake API service that gives us mock data
to play around on with if you head over to Json placeholder type code.com and check
out

04:53:16
their resources section you will find a/ users endpoint this gives us adjacent
array of 10 users with different details we're going to fetch this data and display
each user's name username email and phone number in our nexs application while nexs
really shines with data fetching in server components which we will get to later
let's start with something you might be more familiar with client side data
fetching if you've done any data fetching in react before you will feel right at
home let's begin

04:53:51
in your app folder create a new folder called users client and add a page. TSX file
inside it I chose the name users hyphen client since we're handling user data in a
client component but feel free to name it as you see fit the code we are about to
write should look pretty familiar if you worked with react before so we'll move
through it at a good Pace first let's define our typescript type for the users
we'll keep it simple and just include the fields we care about type user contains
ID name username

04:54:25
email and phone number for our component we will call it users client so export
default function users client we need three pieces of state within this component
users to store the fetched users loading to track if the users are being fetched
and error to store any error messages don't forget to import use state from react
next we will use use effect to fetch our users when the component mounts import use
effect from react and within the component I'm going to paste the code for use
effect inside our use effect hug we've

04:55:04
got an Asing function called Fetch users that grabs our users data from Json
placeholder API this is the same URL we saw earlier Jon placeholder Doty code.com
users if something goes wrong with the response we throw an error saying failed to
fetch users and update our error state with either error. message or an unknown
error occurred if everything goes smoothly we update our users state with the data
we received either way we set loading to false when we are done we call this
function fetch users right

04:55:40
away in side use effect when the component mounts for the UI we will handle each
state appropriately if you are still loading we will show a loading message if we
hit an error we will display that and if everything works perfectly we will map
through our users and display them in a clean style list user.name user. username
their email and phone number the Tailwind classes are primarily for styling so I
wouldn't worry too much about achieving this exact layout and you y as you can see
this is pretty much standard react code

04:56:15
with just one RSC architecture addition use C directive at the top to enable the
use of hooks in the browser if you navigate to Local Host 3000 SL users hyphen
client you should briefly see the loading text and then the list of users rendered
nicely we have the username username email and phone number we have the data for 10
different users here's the thing though you should really only use client
components for data fetching when you absolutely need to like when you need
realtime updates or when your data depends on client side

04:56:52
interactions that you can't predict on the server side for everything else the
recommended way to fetch data is through server components which we will cover next
previously we learned how to fetch data in client components now let's learn how to
fetch data in server components one of the coolest things about the RSC
architecture is that it supports esync and a keywords in server components this
means we can write our data fetching code just like regular JavaScript using Asing
functions coupled

04:57:22
with the await keyword let me show you how this works with an example we will once
again use the slash users in point from Json placeholder for our mock API we're
going to fetch this users data and display each user's name username email and
phone number in our NEX shs server compon component let's jump into vs code and get
started inside your app folder create a new folder called users hyphen server and
add a page. TSX file inside it I chose the name users hyphen server since we're
handling user data in a

04:57:57
server component but feel free to name it as you see fit first let's define our
typescript type for the users we will keep it simple and just include the fields we
care about ID name username email and phone phone similar to data fetching in
client components so I'm going to Copy Type user and paste it in the new page. TSX
file for our component we will call it users server so export default function
users server make this component async since server components support async
operations now here is where it gets

04:58:37
really simple to fetch our users data we just need to make a get request to the
user's endpoint using the fetch API so const response is equal to await Fetch and
the URL is Jon pleas holder. typy code.com users in the next line const users of
type user array is equal to await response. Json and let's console log the value
users when you save this and check out/ users server in the browser users hyphen
server take a look at the console you'll see the user list consisting of 10 users
our data fetching

04:59:20
is working all there is left to do is display the users on the screen simply copy
the return statement from the client component we previously created and paste it
in the server component delete the console lock statement we map over the list of
users where each user is defined by the user type we render the user's name
username email and phone number the classes are primarily for styling so don't
stress too much about achieving this exact layout and UI save the file and you
should see all 10 users being displayed

04:59:57
the route is/ users hyphen server we have successfully fetched data in server
components now here is something really cool you should know about when building
nexs applications you'll often end up fetching the same data in multiple places
like how request B appears across six different components in our tree to load a
single route you might think this would trigger multiple Network requests for the
same data but react cleverly handles this through a feature called request
memorization react Will D duplicate

05:00:27
fetch requests with the same URL and options this means you can fetch data wherever
you need it in your component tree without worrying about duplicate Network
requests react will only make the actual fetch once and reuse the result for
subsequent calls during the same render pass it's a react feature and thereby
included in XS letting you write data fetching code exactly where you need it
rather than having to centralize fetches and pass data down through props notice
how simple data fetching is with server components just

05:00:58
easing await with the fetch API no use State no use effect none of that State
Management complexity we usually deal with speaking of State though you might be
wondering about handling loading and error States in server components well that is
exactly what we will explore next previously we explored fetching and displaying
data with server components now let's tackle loading and error States while client
components require you to manage these states with separate variables and
conditional rendering

05:01:31
server components make this process much cleaner to implement a loading State all
we need to do is Define and Export a react component in loading. TSX for error
handling we do the same in error. TSX we covered these Concepts earlier when
discussing routing but now let's see how they work specifically with data fetching
let me jump into vs code and show you how this works first let's create a new file
called loading. TSX in the user hyphen server folder so loading. TSX this is a xjs
convention

05:02:04
here Define and Export a react component let me paste the code here to save us some
time we have export default function loading page and this component creates a nice
loading spinner using two div tags with tailin CSS classes since data fetching
happens pretty quickly in our example let's add a deliberate delay to better demo
the loading state so await new promise which results after 2 seconds if we head
back to the browser and refresh the page we will see the loading spinner appear for
2 seconds

05:02:39
before our user data shows up implementing a loading state is pretty
straightforward now for the error handling let's create an error. TSX file in the
same folder the file name is once again an XS convention Define and Export react
component with suitable styling I will once again paste the code here to save us
some time error handling components need to be client components so we have the use
C directive at the top we then have export default function error page and the
component receives an error

05:03:11
object which we are logging to the console using use effect in a real application
you would probably want to send this error to an error logging service the UI
simply shows a clear error message in red error fetching users data to test error
handling back in page. TSX within the same folder we can simulate an error by
changing the URL to something incorrect so users 1 2 3 save the file and go back to
the browser you will see our error message appear error fetching users data we have
successfully handled both the loading

05:03:45
and error States when fetching data in server components in summary to manage data
fetching States add a loading. TSX file with the react component for the loading
State and an error. TSX file with a client component to handle error States now
that we have understood the fundamentals of data fetching in server components
let's move on to explore two common patterns for data fetching when fetching data
inside components you need to be aware of two data fetching patterns sequential and
parallel in
05:04:17
sequential data fetching requests and a component tree are dependent on each other
this can lead to longer loading times but there may be cases where this pattern is
inevitable because one fetch depends on the result of the other let's understand
better with an example for the mock data we will once again rely on the Json
placeholder API this time though we will use the/ hosts and SL users endpoints to
create a blog like page the/ posts endpoint returns an array of 100 posts and each
post has a

05:04:49
user ID host ID title and body the/ users inpoint returns an array of users which
we've already used before if we append user ID to/ users for example slash1 we get
the individual user object in our application we will create a posts component that
fetches all posts and then for each post it will fetch its author using the user ID
property this is a perfect example of sequential fetching because we need the user
ID from each post before we can fetch its author let's jump into vs code and get

05:05:24
started inside your app folder create a new folder called posts sequential and add
a page. TSX file inside it first let's define our typescript type for the posts
each post has user ID id id title and body for our component we will call it posts
sequential so export default function post sequential make this component eing to
support data fetching since we have just learned the fundamentals of data fetching
in server components I'm going to paste the entire component code here and then
we'll go

05:06:02
through it step by step we start by fetching all posts from the/ Posts endpoint
Json placeholder typ code.com slost which is the URL you can find in the browser we
convert the response to Json and then we filter the posts to only include the ones
with an ID that is divisible by 10 this is to make sure we have a different author
for each post as Json placeholder has the same author every 10 posts in the jsx for
each post we display the post title body and a placeholder for the author name to
be fetched

05:06:41
if we check the browser by navigating to/ poost sequential we should see 10 post
being displayed now let's see how we can fetch the author for each post back in vs
code create a new file called author. TSX inside the post sequential folder so
author. TSX Define the author type this is the user type but we only need the ID
and name fields so ID of type number and name of type string now let's define our
author component once again I'll paste the entire component code here and then
we'll go through it step by step we have

05:07:22
a function component that takes a user ID prop makes a fch request to Json
placeholder SL users user ID end point and Returns the author's name to use this
component we need to import it into our post sequential page component and replace
the placeholder Auto name with the author component delete the paragraph tag invoke
author component make sure to import it at the top and then pass in user ID is
equal to post. user ID if you check the browser we should see the posts displayed
with the author name lean
05:08:01
Graham Ain H and so on this is sequential data fetching in action first we fetch
all post from the/ poost API then for each post we render we make another fetch
request to fetch its author's details each author request has to wait for the Post
request to complete because we need the user ID from the individual post this works
perfectly fine but we can improve this by not blocking the UI while we are fetching
the author details we want to show the post first and stream the author in the
background we can do this by wrapping

05:08:39
the author component in a suspense boundary so wrap it with suspense from react
which you should make sure to import from react at the top opening and closing
author is the children prop and on suspense we specify the fallback prop a div tag
that renders loading author in gray color in the author component we can add 1
second delay to see the loading text in action await new promise resolve after 1
second now if we check the browser reload we should see the posts displayed with
the loading author

05:09:17
text and after a short delay the author name should be streamed in our component
works as expected if you're clear with sequential data fetching let's move on to
parallel data fetching now let's look at parallel data fetching in parallel data
fetching requests in a route are eagerly initiated and we load data at the same
time this reduces the total time it takes to load data let's understand better with
an example for the mock data we will once again rely on the Json placeholder API
this time though we will

05:09:50
use the slash posts and slash albums in points to create a user profile page the
posts end point returns an array of 100 posts each post has a user id id title and
body the albums endpoint returns an array of 100 albums each album has a user id id
and title to both endpoints we can append user ID as a query parameter to filter
the posts and albums by the user so question mark user ID is equal to one you can
see we have 10 posts all written by the same user similarly SL albums question mark
user

05:10:34
ID is equal to one we have 10 albums written by the same user now if you're
building a user profile page we might want to show both the users posts and their
albums side by side since these requests don't depend on each other we can fetch
them in parallel let's jump to vs code and see this in action inside your app
folder create a new folder called user hyphen parallel we will pass the user ID as
a route parameter so create an ID folder inside user parallel so square bracket ID
and add a page. TSX file inside

05:11:14
it youve created a user Dynamic route first let's define our typescript types type
post which contains user id id title and body and type album which contains user id
id and title user ID is common across the two types but here ID and title refer to
the album ID and title for our component we will call it user profile so export
default async function user profile make this component async to support data
fetching now here's the trick we will Define our data fishing functions outside the
05:11:53
component the function name is get user posts and it is an easing function that
takes user ID as a parameter it fetches the post for the given ID from the Json
placeholder API and returns a response so const res is equal to await fetch passing
in Json placeholder SL posts question mark user ID is equal to the user ID
parameter and return rest. Json the get user albums function is identical but for
albums let me duplicate the code and change the function name as well as the
endpoint get user albums SL albums user

05:12:38
ID is equal to the Past in user ID now let's define our page component the
component will receive the user ID as a route parameter so we destructure params of
type promise which contains ID of type string ID here is our folder name we will
await params and destructure user ID from it now we will initiate both data
fetching requests in parallel using promise.all so const posts data is equal to get
user hosts passing in ID similarly const albums data is equal to get user albums
passing in ID then call

05:13:22
a wait promise.all we specify an array of post data and albums data we assign it to
posts and albums due to the nature of async and await an awaited request inside the
component will block any requests below it this is why we initiated both requests
before awaiting any of them for the jsx I will paste the entire component code to
save time it is a two column layout with posts on the left and albums on the right
take a look at the browser navigate to user parallel SL ID which is one for example
and we see the

05:14:06
10 posts on the left and 10 albums on the the right our data fetching is working as
expected the key to parallel data fetching is initiating the requests before
awaiting any of them let's add a loading. TSX file and a delay to the two functions
to see this in action so one second delay to get user posts and 1 second delay to
get user albums next adjacent to page. TSX create loading. TSX with a simple react
component I've used t CSS classes to create a loading spinner now if we visit SL
user parallel

05:14:45
SL2 for example both columns will load at the same time after a 1second delay this
is much faster than waiting a second for the posts and another second for the
albums parallel data fetching is particularly useful when you have multiple
independent pieces of data that you need to fetch instead of fetching them one
after another you can fetch them all at once and reduce the total loading time all
right you should now have a solid grasp of how and when to use both sequential and
parallel data fetching in your

05:15:21
applications now that we have looked at how to fetch data from API endpoints using
the fetch API let's dive into fetching data from a database in server components
please pay extra attention to this part because what we are about to cover is super
important it's the foundation for data mutations and server actions coming up next
now there are two key reasons why fetching data directly from a database is
powerful first server components have direct access to serers side resources which
makes database interactions
05:15:50
seamless second since everything happens on the server we don't need API routes or
worry about exposing sensitive information to the client to understand how to fetch
data from a database we're going to be working with two super helpful tools sqlite
and Prisma now don't worry if you've never heard of these before I'm going to break
it down super simple sqlite is a simple file-based database to store information in
your project it doesn't require a server or a complex setup and it is

05:16:18
perfect for Learning and prototyping Prisma is a tool that makes it really easy to
talk to your database it's like a translator that helps your code communicate with
SQL light let's head back to vs code and go through the setup step by step I highly
recommend you to follow along with me first in the terminal install Prisma CLI as a
Dev dependency npm install Prisma [Music] DD second initialize Prisma with sqlite
npx Prisma init -- data source- provider sqlite this creates a Prisma directory

05:17:00
with a schema. Prisma file to simplify the setup update the database URL in this
file to file colon .db we will also add the database file to the git ignore file
database Prisma slam. DB third step in schema. Prisma add a product model with ID
title price and optional description models represent the tables in the underlying
database product model corresponds to the products table finally run a migration to
create the database tables from the Prisma schema in the terminal run the command
command

05:17:39
npx Prisma migr Dev D- name in it this command does three things creates a
migration file in Prisma migrations executes the migration against your database
installs the Prisma client package and generates the Prisma client with which we
will interact with the database our database and tables are ready now let's define
our database operations in the source folder create a new file called Prisma db. TS
to save time I'll paste the code as we go but you can find the full file on my
GitHub repo and the link to that is in the

05:18:19
description down below start by importing the Prisma client package import Prisma
client from at Prisma client in the next line create a new Prisma client instance
const Prisma is equal to new Prisma client with parenthesis next we've got this
seed products function it checks if a table is empty and if it is it adds three
sample products product 1 2 3 with prices and description next we will Define our
crud operations first we have get products which uses Prisma do product.in many to
get all products next we have get

05:19:04
product which uses Prisma product. find unique to get a single product by its ID
next we have ADD product which uses Prisma do product. create to add a new product
we have update product which uses Prisma do product. update to update an existing
product finally we have delete product which uses Prisma product. delete to delete
a product I've added a 1.5 second delay to each crud operation to simulate latency
you wouldn't have this in production if you're new to Prisma don't worry too

05:19:39
much about the syntax details all you have to know is that we have a database with
a products table and functions to perform cred operations on that table all right
now for the exciting part let's fetch the products data in an EXs page in the app
folder create a new products DB folder with the page. TSX file first Define the
type of a product each product has ID title price and optional description similar
to our model in schema. Prisma file then Define the react component export default
async

05:20:19
function products DB page since server components run on the server we can directly
talk to our database without the need of an API from prismad db. TS import the get
products function here I'm using a path elas which refers to the source folder
within the react compon component await the function call and store the result in a
products variable so const products of type product is equal to await get products
for the jsx we are going to use the map method to bind the product information and
use tailin

05:20:57
classes to make it look pretty I'm going to copy paste the code to save us some
time so products. map and we bind product title description and price we use ID as
part of the key prop on the list item save the file head over to/ products hyphen
DB in your browser and you should see three products displayed from your database
we've got a working Prisma plus sqlite database with direct access from our nexs
server component no API layer required and while we are using sqlite here these
same Concepts

05:21:34
apply to any database you prefer the key takeaway is that you can query your
database directly from your next year server component all right up next we will
build on this Foundation to learn about data mutations and server actions we've
covered how to fetch data using server components in the app router now it's time
to explore something equally exciting data mutations when we work with data we are
typically performing what we call crud operations create read update and delete
we've already mastered the read part so

05:22:07
let's dive into the other three start starting with how to create data to follow
along make sure to check out the previous topic on fetching data from a database
where we set up our Prisma client with a sqlite database we have a products table
ready to use with some sample data and methods to perform crud operations to really
appreciate the app router's approach to data mutations it is worth looking at how
we have traditionally handle data mutations in react this comparison will help us

05:22:36
appreciate the benefits of the app router appr let's work through a practical
example of creating a new product in our products table now I prepared the code
ahead of time but it should look pretty familiar if you worked with react before
let me walk you through how everything works in a new folder called react form I've
created a page. TSX file with a component called create product here you create a
form with input fields for product title price and description you will need the
use State hook to keep

05:23:09
track of these field values then you add an onsubmit event listener to your form
that triggers a submit Handler function when the form is submitted now here is
something important to remember about the submit Handler for security reasons the
client side code can't directly interact with the database that is why you or your
backend team need to set up an apepi route to handle the create request in our
example I'm using a next Shar API route but you can think of this as a backend and
point this API route

05:23:40
does the heavy lifting of actually interacting with our database taking the form
data and creating a new product record using the add product function meanwhile on
the front end side you also need to handle the submission process elegantly this
typically means implementing a loading state to disable the submit button while the
submission is in progress if the submission is successful you will want to redirect
the user to the products page to see the newly created product in the browser head
over to/ react form and you will

05:24:11
see the form we have created fill it out and submit it you will see the loading
State and then be redirected to the products page we see our newly created product
in the list as you can see there is quite a bit going on here we are managing form
State handling submissions interacting with an API route dealing with loading
States and handling redirects but here is a good news if you're thinking there must
be a better and simpler way to do this in nexs you're absolutely right up next we
will explore how the nexs app router

05:24:48
transforms this entire process making it significantly more streamlined and
efficient previously we explored the traditional way of handling data mutations in
react now let's explore an exciting feature in the app router called server actions
server actions are asynchronous functions that are are executed on the server they
can be called in server and client components to handle form submissions and data
mutations in nexs applications you should use server actions when you need to
perform secure database operations

05:25:22
want to reduce API B plate code need Progressive enhancement for forms and want to
optimize for performance a server action can be defined with the react use server
directive you can place the directive at the top of an asnc function to Mark the
function as a server action or at the top of a separate file to mark all exports of
that file as server actions let's jump into V code and see how this works for our
example we will build a form to add a new product to our database first let's
create a new route

05:25:53
in the app folder create a new folder products DB create SL page. TSX file here
we'll Define and Export a react component called add product page so export default
function add product page this is a server component for the jsx we will copy the
form jsx from our previous example so from react form page. TSX copy the return
statement and then get rid of state and event handlers which don't work in server
components remove on submit from the form element on change from the three input
elements disable state with loading and
05:26:42
we can change the text to just add product now we will Define our first server
action to handle the form submission first we create an Asing function called
create product and Mark it with the use server directive at the top next we connect
this function to our form by assigning it to the action attribute so action is
equal to create product when someone submits our form this create product function
automatically receives the form data as an argument the type is form data then we
grab the fields we need from form data

05:27:24
and call our add product function from prismad db. TS file so const title form
data. get title as string similarly get hold of price and description make sure
your server is at the top once you have all the data call add product from Prisma
DB since price is numeric call pass in and pass in price because we're using a
server action in a server component we can talk directly to the database this code
never reaches the client's browser it's like having an API endpoint built right
into your component finally we can

05:28:12
add a redirect to take users back to the product lists after they've created a new
item so await add product and then call redirect from next SL navigation and
navigate to products hyphen DB which is the listing page make sure to add a forward
slash at the start so/ products DB let's try this out in the browser with the dev
tools Network panel open navigate to the new route SL products hyph DB hyphen
create fill in the form and submit it you will notice a network request to the
server as a server action runs and on

05:28:53
the products list page you should see our newly inserted product test product two
test description two price for $40 now I've already pointed out the benefits of
server actions but let me reiterate them now that we have seen the traditional way
of handling form submissions as well as the new server actions way first they
dramatically simplify your code as there is no need for separate Epi routes or
client side State Management for form data second they boost security by keeping
sensitive operations server side away from

05:29:27
potential threats third they improve performance because there is less JavaScript
running on the client leading to faster load times and better core web vitals but
the cherry on top is that several actions support Progressive enhancement this
means your forms keep working even if JavaScript is turned off in the browser
making your apps more accessible and resilient in the browser navigate to products
DB create and in Dev tools in the sources panel press command shift p and disable
JavaScript now fill in product details and try

05:30:04
submitting the form the product still gets created this is Progressive enhancement
in action hit command shift p again and enable JavaScript to summarize server
actions are asynchronous functions that are executed on the server they allow us to
perform data mutations without separate API routes we Implement them using the use
server directive and they simplify our code improve security and support
Progressive enhancement up next we will take things further by handling the form
submissions pending State we will learn
05:30:37
how to disable the submit Buton button to give users better feedback and prevent
accidental double submissions previously we explored several actions for handling
form submissions now let's enhance our user experience by adding feedback during
form submission using a react hug called use form status use form status is a react
hug that provides status information about the most recent form submission when you
call it it returns a status object with four Key Properties pending which is is a
bullion that

05:31:09
indicates if the parent form is currently submitting data an object containing the
form's submission data method a string either get or post showing the HTTP method
being used and action a reference to the function that was passed to the parent
forms action prop for our purposes we will focus on the pending property which we
will use to disable or submit button while the form is being processed let's head
back to vs code and implement this now we could use the use form status hook
directly in page. TSX but there is

05:31:45
an important consideration hooks can only be used in client components converting
our entire page to a client component would not be ideal we would lose all the
advantages of server components so what's a smart approach here we will extract
just the submit button jsx into its own client component this way we can use the
hook without compromising on the benefits of rsc's let me show you how first create
a new folder called components in the source directory and inside this folder
create a new file called submit.

05:32:20
TSX here we will Define our submit component export const submit is equal to an
arrow function first add the use C directive since we're using a hook next we
import the use form status Hook from react Dom in our component we we destructure
the pending property from use form status we return a button element with text
submit type is equal to submit and some tailin CSS styling finally we use the
pending Boolean to disable our button when the form is submitting so disabled is
equal to pending we also have a style

05:33:02
corresponding to disabled State now let's use this component in our page. TSX file
so within add product page component remove the button element and invoke the
submit component make sure it imported from at components slub submit if you try
this now in the browser you will see the submit component being displayed fill in
the form and click the submit button it becomes disabled immediately and when the
form submission completes the button is enabled again you will see the newly added
product in

05:33:37
the list now you can take this further by adding a loading spinner or changing the
button text if you want to give your users more feedback but to summarize what
we've learned with next's server actions we can use the use P status Hook from
react Dom to manage State related to active form submissions by extracting just the
submit button into a client component we can get the best of both worlds server
component benefits from our main component and dynamic client side updates for our
form submission state
05:34:09
up next we will explore how to handle error messages with server actions previously
we learned about handling loading states with use form status now let's dive into
something equally important managing error States in our forms we will be using
another new react hug called use action State use action state is a react hug that
allows us to update State based on the result of a form action it is particularly
helpful for handling form validation and messages let's jump into code and see how
it works in products DB create page.

05:34:44
TSX file let's start by defining our types for error handling type errors we will
track three potential errors one for the title one for the price and one for the
description field they're optional of type string the errors will be part of the
overall form state so let's define that type form state contains a key errors of
type errors now inside our component we will set up the initial form state so const
initial state of type form state is equal to an object with errors set to an empty
object we now have the

05:35:30
prerequisites in place for our use action State hug invoke it within the component
use action State make make sure to import it from react so import use action state
from react this hook takes two parameters first our server action which is create
product and second our initial form state which is what we have just defined you
might see a typescript error for create product but don't worry we will fix that
shortly next let's update our create product server action to work with this new
state first let's declare errors of type

05:36:11
errors which is an empty object to begin with next if there is no title in the form
data we set errors. title is equal to title is required similarly if price doesn't
exist in our form data we set errors. price price is required and finally if
description doesn't exist in our form data we set errors. description is equal to
description is required it is optional in our model but let's enforce a required
field validation once we perform these checks if object. keys of errors. length is
greater than zero

05:36:54
we return the errors object what we are doing here is validating the form data and
setting appropriate error messages if you find any errors we return an updated form
state without proceeding to the insert statement since the object key and value is
errors we can use the Shand notation this however should conform to our form State
type in case you're finding it difficult to keep track within our create product
server action we're getting hold of title price and description from form data and
then we

05:37:31
check if values exist for each of them if they don't we populate an errors object
when the different keys if even one key exists we have an error in our form and we
return the errors object instead of inserting the data into our database let's now
go back to our use action State hook this hook returns an array with three things
the const array is equal to use action State the hook Returns the current form
state which we will call State a new form action which we will call form action and
a Boolean

05:38:07
that indicates if the action currently is being executed let's call it e pending
now let's use the three values in our component first we will use the current form
state to display the error messages so below each label we will add a paragraph
that displays the error message if it exists so curly Braes state. errors. title
and if this exists add a paragraph tag rendering state. errors. tile also add
Tailwind styling to display the message in red I'm going to copy these three lines
of code and

05:38:48
paste it under price as well as description labels for Price update state. errors.
price and for description state. errors. description we will also group the form
field and the error message in a div tag so div tag wrapping label as well as error
message div tag wrapping label and error message and the final one this is purely
for grouping related elements and adding space between the different fields state
is now taken care of next we will point the form action to our form's action
attribute so instead

05:39:37
of create product we specify form action we will use the E spending Boolean to
conditionally disable the submit button when the action is being executed now this
is completely optional as we are already handling the pending state with use form
status in the submit component but I will show you how to do it anyway I will
comment out the submit button component copy the button element from the submit
component and paste it in place to the disable attribute we will pass e pending
Boolean returned by the use action State

05:40:12
hug ultimately what we have done here is instead of directly calling the server
action create product we pass it through the use action State hook that manages
State updates based on the form action now when we save the file and head back to
the browser we will run into an error can you guess why well we're using a react
hook in a server component use action State now your first instinct might be to add
use client at the top of our file let's do that use client when I save the file you
can see that gives us

05:40:46
a different error because it is not allowed to Define inline use server annotated
server actions in client components in simpler terms we can't use the use server
directive in a component marked with the use client directive so what is the
solution that is what we will explore next previously we hit a of a roadblock when
we try to define a server action in a client component next year wouldn't allow it
but don't worry I've got a neat solution for you the trick is to separate our
server action into its own

05:41:18
file keeping our serers side logic cleanly separated from our client side
components let me show you how to do this first create a new folder called actions
in your Source folder inside this folder create a file called products. TS we're
using this name because we are working with products but feel free free to name it
whatever makes sense for your project now let us set up our product. TS file here's
the thing about us server directive you can place a directive at the top of an
Asing function to Mark the function as a

05:41:50
server action or at the top of a separate file to mark all exports of that file as
server actions so we start this file with the use server directive at the top next
we will move our types errors and form state into this file and Export them then we
will bring over our create product server action but we will remove the US server
directive from inside the function as it's not needed here anymore let's make sure
we import product and redirect functions at the top import add product from Prisma
DB

05:42:38
and import redirect from next navigation make sure to also export create product
now let's update our page. TSX file we will delete the Imports for ad product and
redirect we will import form State and create product from our new products. TS
file in the actions folder we will still use use action state with our create
product function now if you save the file and try this out in the browser we have
an error that says did you mean use server so let's make sure we don't have any
extra spaces navigate to products DB

05:43:20
hyphen create and without filling the form Fields click on the submit button we
have form data. getet is not a function and this is because when we use use action
State and pass and create product the function automatically receives the previous
State as the first argument so previous state of type form State now when you
submit with empty Fields you'll see the error messages title price and description
all of them are required when you fill everything in correctly and submit your new
product will show up in

05:43:59
the list and there you have it we have successfully implemented form validation
using use action state with a separately defined form action this approach gives us
the best of both world we get to use client side react hooks for managing our form
state by leveraging the power of server actions for data mutations for our next
topic I want to take a quick detour to talk about pending returned from use form
status and is pending returned from use action State let's take a look at the
pending state from use form status and E pending

05:44:37
from use action State both booleans can help us determine if a form is being
submitted and let us disable the submit button but there's an interesting
difference between them that is worth understanding the pending state from use form
status is specifically for form submissions on the other hand EAS pending from use
action State can be used with any action not just form submissions now in our
example here you could actually use either one and get the job done pending from
use form status in its own submit component or a

05:45:09
regular button element with e spending from use action state but here is how I
think about choosing between them go with pending from use form status when you're
building reusable components that are meant to live inside forms for example submit
buttons or loading Spinners that you'll want to use across different forms in your
application choose e pending from use action State when you need to keep track of
server actions that aren necessarily related to form submission it gives you that
extra flexibility I

05:45:40
should mention that the official docs on react as well as next sh are a bit light
on this topic if you've got more real world examples of when you would use one over
the other I would love to hear about them in the comment section below all right
now that you've seen how to create a new product with server actions next let's
take a look at how to update an existing product using server actions let's dive
into implementing an update operation for our products and learn how to pass
additional arguments

05:46:10
to a server action in vs code we will Begin by creating a route to edit product
details under app SL products DB create a new Dynamic route within square brackets
id/ page. TSX go ahead and copy the code from product DB create page. TSX and paste
it in this new route rename the component to edit product page in the browser
navigate to products DB SL1 and we see our form to update product details now we
need to fetch the existing product data corresponding to id1 to populate this form
for that we

05:46:52
will extract the route parameter ID and fetch the corresponding product from the
database so destructure params which is of type promise object ID of type string
within the component D structure ID from params so const ID is equal to a we params
and then we will use the get product method from Prisma DB which returns a single
product given its ID const product is equal to a weit get product and we pass in
parse end ID now here is where we encounter our first challenge we cannot use the
AIT keyword as client components

05:47:38
can't be Asing components if I add the Asing keyword you can see the warning and we
can't remove use client either since we're using react hugs in the component this
is actually a common issue you'll come across in XS to solve this we will split our
logic in the same ID folder create a new file product hyphen edit hyphen form. TSX
copy all the code from peach. TSX but leave out the data fetching part so remove
get product await params and the props let's call this edit product form

05:48:19
component then in page. DSX we will focus only on the data fetching part so remove
the use C directive at the top use action state from react the invocation of use
action State and for the jsx we return our newly created edit product form
component we can also remove form State and create product as well as initial state
from the component we can add async as we don't have any hooks anymore pass product
as a prop to the form component so what we are doing here is extracting the route
params getting hold of the ID

05:48:57
getting the product corresponding to the ID and passing the details of that product
as props to edit product form in the edit product form client component specify the
prop product and for the type we're going to go to our products listing page in
products hyphen DB export type product and import it here I'll make sure to use
at /a/ products DB now use the product details as default values for all the form
Fields so for title default value is equal to product. title similarly for Price
default value is equal to product. price

05:49:42
and for description default value is equal to product description since description
could be null we use the nullish coalescing operator to provide an empty string as
the default value so double question mark empty string if we go back to our edit
product page we still have a typescript error first let's import the product type
I'm going to copy this line paste it here and specify the type of the product
variable now get product could return null If the product is not found so we need
to also handle that case if the

05:50:23
product is not found we call the not found function from next SL navigation make
sure to import it at the top typescript is now happy back in products DB listing
page wrap the product title with a link component to enable navigation to the edit
page so link component which we import from next SL link wrap the product title
specify each ref is equal to back text SL products hyphen DB slid and that is
dollar curly Braes product. ID in the browser clicking a product title so product
one takes us to the edit page prepopulated

05:51:10
with product details product One Price 500 description one our UI setup is now
complete let's move on to implementing the update server action for form submission
in products. TS within the actions folder duplicate the create product server
action and name it edit product in product edit form. TSX we will import edit
product server action instead of create product and pass it in as the argument to
use action State also back in edit product server action will modify it to call
update product from prismad db. TS which

05:52:01
updates the product in the database but we now face another interesting challenge
update product needs the product ID which means we need the product ID in our edit
product server action since product ID is not a form field we can't access it from
form data like our other fields now we could use a hidden input field so input type
is equal to Hidden name is equal to ID value is equal to product. ID but this would
expose the ID in the HTML without proper encoding instead let's use javascript's
bind method to pass

05:52:37
additional arguments in the edit product form component we can bind the ID to the
edit product server action so const edit product with ID is equal to edit product.
bind null comma product ID and then pass this function into use action State the
bound argument ID will now be available as the first argument in the edit product
server action so ID of type number comma previous state of type form State form
data of type form data pass this ID as a first argument to update product function
ID comma title price and description back

05:53:23
in the browser update the product details so updated description one click on
submit and the changes will be immediately reflected refed in the products listing
page our update server action is now complete I understand that was a lot to take
in so let me summarize what we did we created a dynamic route for updating
individual products we used route parms to fetch product details from our database
we found out that client components can't be async components to solve the async
issue we split data fetching into a server

05:54:02
component and form logic into a client component from the server component we
passed product details as a prop to the client component in the client component we
bound product details as default values to our form fields in our actions product.
TS file we created a new server action to handle product updates the database
function though required the product ID which was not available in the form data we
used the bind method to pass the ID argument without exposing it in the HTML we
retrieve the ID as the

05:54:37
first argument in our server action and passed it to the database function we got
our product update functionality working smoothly up next we will tackle the final
piece of our crud operations the delete functionality let's dive into implementing
delete functionality using server actions we will start by adding a delete button
for each product in our list so in products DB page. DSX after product. price I'm
going to add a delete button button type is equal to submit with a red background
for styling and

05:55:14
the text delete next let's define our delete server action in actions / products.
TS we will add a remove product function so export async function remove product
import the delete product function from prismad db. TS which handles deleting a
product by its ID remove product server action takes an ID parameter of type number
and passes it straight to the delete product function very straightforward now back
in our product page we need to call This Server action but here's the question how
do we do

05:55:54
that if we use the onclick Handler on the delete button it would make it client
side code we however want the component to remain a server component well the
solution is to wrap our button with a form element so form opening tag and closing
tag on the form element we will specify the action attribute to call the remove
product server action so action is equal to remove product make sure to import it
at the top import remove product from actions SL products now remove product meets
the ID parameter so we will also bind product.

05:56:36
idid using the bind method so null comma product. ID this makes the product ID
available as the first argument to remove product just like we did earlier with our
update product server action this same ID is passed to delete product let's save
everything and try it out in the/ products DB route we see our newly added delete
button against each product when we click delete on the last product so validation
typle one we see the network request but nothing seems to happen in the UI if you
refresh the page you will notice that

05:57:15
the last product is gone so what's missing well we need to refresh this product
list automatically after deletion to fix this we can use a function called
revalidate path make sure to import revalidate path from next slash as an argument
specify slash DB which is the path of our products listing page we are telling ni
shares to refetch data for/ products hyphen DB path after deletion make sure to add
the await keyword now when we delete a product submit product one you see the
network request and it disappears from

05:57:57
the list without needing a manual refresh you will still notice this 1.5 second
delay we built in though the real application this would typically be shorter still
any delay isn't ideal for user experience so up next we will look at how to make
this feel smoother using optimistic updates for the final topic related to crud
operations let's take a look at performing optimistic updates with the use
optimistic hook use optimistic is a react hook it provides a way to optimistically
update the UI while an

05:58:31
asynchronous action is underway this technique helps make our apps feel more
responsive especially when working with forms instead of making users wait for
Server responses we can show them the expected result right away let me show you
how this works with some code for our example when the user clicks on a delete
button instead of the 1.5 second delay to show the deletion we will remove that
product right away from the list to achieve that first we import use optimistic
Hook from react in our products DB page. TSX file import use

05:59:08
optimistic from react invoke it within the component after the data has been
fetched use optimistic and the hook takes two parameters the first parameter is the
initial state that you want to optimistically update this is a list of products
fetched from the database the second parameter is a function that determines how to
update the state optimistically this function takes to arguments the current state
which we will call current products and an additional argument to help create the
new state for our scenario the

05:59:46
additional argument is the product ID which corresponds to the product we want to
delete the function filters the current products array to exclude the product with
the given ID so current products do filter product such that product. ID is not
equal to product ID this is just simple JavaScript nothing specific to react or
next shes it is important that we return this updated list as our optimistic State
now what does this use optimistic hook return two things first is the resulting
optimistic state which we will call optimistic

06:00:27
products this is the array we will show to the user second is a function to trigger
the optimistic update the function takes one argument of any type and we'll call
the update function that we have defined as the second argument to use optimistic
so how do we make use of these two values first instead of iterating over the list
of products from the database we will iterate over the list of optimistic products
which is managed by the use optimistic Hook second we create an async function
remove product by

06:01:02
ID that takes a product ID of type number number and handles our delete server
action so await remove product passing in product ID before calling the server
action though we trigger our optimistic update so set optimistic products passing
in product ID this immediately shows the user their changes while the actual
deletion happens in the background now on the form element to the action attribute
we invoke the new function remove product by ID binding the product ID so bind null
comma product. ID this

06:01:46
value is the product ID that the function receives that was a lot to take in so
let's go over the flow of the use optimistic hook one more time we invoke the hook
with the current state and a function returning the optimistic State the optimistic
state is available as the first return value which we use to render the list of
products we use the second return value the setter function to call the update
function and execute a logic to return the new state this Setter function runs
right before the

06:02:20
server action users always see the optimistic State while the actual operation
completes in the background if we save the file we will see an error because we are
using a hook in a server component the solution we will need to separate our data
fetching from our data mutation logic similar to what we did with our update
operation earlier so alongside your page. TSX create a new file product hyphen
detail. TSX copy the entire code from page. TSX and paste it into this new file
rename the component

06:02:56
to product detail product detail becomes a client component handling the mutations
and optimistic updates add the use CLI directive at the top remove ASN keyword and
also the data fetching code it will receive data from the parent server component
instead we specify products of type product I will also make this unnamed export
perfect the page. TSX file will now be a server component in charge of only data
fetching let's delete The Unwanted code use optimistic remove product and the link
component can be

06:03:36
deleted instead import the newly created product detail component so import product
detail from do/ product detail for the component we will still fetch our products
from the database and then return the same component passing in the list of
products as a prop save both the files and try it out in the browser I want you to
observe what happens when we click the delete button so test product one delete and
the product disappears instantly while the actual deletion completes in the
background after 1.5 seconds but

06:04:13
your users get that smooth responsive experience they love so delete it's removed
right away and the delete operation completes in the background that wraps up our
look at crud operations with server components and server actions in the app router
for our final Topic in this section on data fetching and mutations let's take a
look at the newly introduced form component in XS the form component is built on
top of the HTML form element and it comes with some powerful features that make it
perfect

06:04:47
for modern web applications it automatically prefetches loaring UI it handles
client side navigation on form submission and it provides Progressive enhancement
out of the box let me show you how the component works with an example in our
application currently we have a homepage and a products hyphen DB page where we
display a list of products in the homepage we will add a product search feature
that will redirect to the products DB page to show the list of products filtered by
the search query let's jump into vs code and see how to

06:05:22
achieve that first let's set up our loading state in the products DB folder create
a loading. TSX file Define a simple react component export default function loading
that returns a Dev tag loading products next we will Define a search component
create a new file called search. TSX in the components folder export a react
component called search this component will render a form with a search input and a
submit button I will paste the code to save time so export const search return an
HTML form

06:06:04
element with action is equal to/ products hyphen DB with some styling and then we
have one input element name is equal to query with CSS styling and placeholder
search products we also have a button element of type submit tailin CSS styling and
the text submit a very straightforward form with input and button elements we will
however make use of the new form component instead of the form HTML element so
import form from next SL form and invoke the form component now that we have our
search component ready

06:06:45
let's add it to our homepage the root page. TSX file in the app folder will be the
entry point for our search functionality import the search component from at
components SL search and right after the main HTML element and before the image
component invoke search if you check the browser you will see that the search input
and submit button are rendered if you type a search query and hit submit you will
be navigated to the slash products DB page and the loading state will briefly
appear before the

06:07:25
products are rendered the list of products however is not filtered for our search
to work we need to update our data fetching logic based on the search query so back
in vs code in Prisma db. TS let's modify the get products function to handle search
queries accept query which is optional of type string and then if query exists
we're going to return Prisma do product. find many and we're going to specify a
condition where or title contains query description contains query in other words
if a query

06:08:08
parameter exists find all products whose title contains that search query or
description contains the search query if the query doesn't exist return the full
list of products finally we need to update our products DB page. TSX to handle the
search parameter so the page component now has props and we destructure search
params of type promise object it's going to contain query which is optional and of
type string within the function body we destructure query from search params and
pass query as an argument to get
06:08:54
products back in the browser when you type product three in the search input and
hit submit you will be navigated to the/ products DB page and product will be
filtered based on the search query we just see the one product that contains
product three in the title or the description now this might not seem anything
special but nexs is actually doing a ton of work behind the scenes first when the
form component becomes visible it prefetches the loading UI Associated with/
products DB route this is the value of the action prop second

06:09:32
when a user submits the search it instantly navigates to the product page client
side and the form data gets turned into URL patterms for example question mark
query is equal to product 3 third it will show the loading State while the search
results are being fetched we see our loading div tag while the products are being
fetched in the background finally once the data is ready the results are displayed
in the UI a lot of functionality is happening here now the form component also
supports Progressive enhancement out of

06:10:04
the box this means that even without JavaScript the form will still work as a
regular HTML form the form component gives us a really smooth user experience with
minimal effort on our part it handles all the complex parts of form submission
navigation and loading States letting us focus on building features rather than
dealing with Messy code like prevent default manual State Management or any of that
old school form handling stuff and you should know that the form component also
supports server actions

06:10:36
in our product Details page product details component rather we have a form that
allows us to delete a product let's replace the HTML form element with the form
component so import form from next SL form and replace the HTML element with the
form component head back to the browser and delete a product it continues to work
as expected to summarize the form component is in new component in X shs that
extends the HTML form element and provides a lot of powerful features like
prefetching loading UI client side navigation on

06:11:14
form submission and Progressive enhancement out of the box with that we complete
this third section on data fetching and mutations we learned how to fetch data in
client components how to fetch data in server components with async a handle
loading and error states with loading. TSX and error. TSX and about fetching data
directly from a database we also learned about server actions for data mutations
validation and pending State feedback with use form status and use action State
hooks separating server actions

06:11:48
for use in client components how to pass additional data to perform update and
delete operations how to perform optimistic updates and finally how to handle forms
with a new form component you should now have a solid understanding of fetching
data and handling forms in next sh for the next section of our next year's course
let's tackle another crucial aspect of web applications which is authentication if
you think about it most apps revolve around users when building for users we need
to consider
06:12:20
three fundamental concepts identity sessions and access identity is about verifying
who someone is through authentication sessions keep track of a user's logged in
state across requests and access controls what they can do developer terms we call
these authentication session management and authorization now nexs handles this a
bit differently than traditional react apps with react single page applications
you're only dealing with client side code but next sh you've got to protect your
application from three different

06:12:53
angles client side code server side code and API routes when implementing
authentication you will typically want to let users sign up give them a way to sign
in enable them to manage their account show or hide UI elements based on whether
they're logged in protect certain routes depending on authentication status access
session and user data when needed set up ro-based access control and finally
provide a way to sign out here's the thing building all of this from scratch would
take forever that's why even nexts themselves

06:13:25
recommend using an authentication Library the dogs explicitly State while you can
Implement a custom oolution for increased security and simplicity we Rec using an
authentication Library this brings us to clerk clerk is this really cool
authentication and user Management Service that works beautifully with next shares
the best part it is free for up to 10,000 monthly active users which is perfect for
our course and most projects you will build I've actually used clerk in a few of my
site projects and I can

06:13:56
tell you it's the most straightforward authentication solution I found for next
years stick around and you'll see why to get us started with this section on
authentication I've already set up a fresh next year project in vs code using the
command npx create next app at latest authentication hyphen demo go ahead and run
this command you should end up with a similar project to what I have here now we
can begin our journey to building a secure NEX application let's get started by
setting

06:14:29
up a clerk account I recommend following along with me to quickly set up your
account in parallel go to Clerk's homepage the link is in the description and click
on get started create an account using your preferred method I'm going to enter an
email and password click on continue enter the verification code once loged in
create a new application in clerk enter the name of the application as next sh's
application select the signin options that you want to support and you can see a
preview of the UI on the right hand

06:15:02
side we will have email password and Google authentication I will also add GitHub
you can see the same updated in the preview to proceed click on the create
application button this brings us to the setup instructions page choose next shares
as the framework if it's not already selected now let's follow these steps together
to add clerk to our project step one install the clerk package copy the command
from the setup instructions page and run it in your terminal npm install at clerk
nextjs step two set your environment
06:15:44
variables in your project create a env. loc file in the root of your project and
add your clerk API Keys copy the publishable key and secret key from the setup
instructions page and add them to the env. looc file make sure to use your own keys
and not mine step three create a middleware dots file in the source folder invs
code in the source folder create a middleware dots file copy the code from the
setup instructions page and paste it here this will help us access Au data and
configure protected routes later and I

06:16:31
just realized this should not be inside app but inside Source folder step four wrap
your entire application with the clerk provider component which is a react
component that provides Clerk's context to your application we will do this a
little differently to what the setup instructions show in the root layout file
layout. TSX import clerk provider component at the top from at clerk SL nextjs and
wrap the jsx with it clerk provider opening tag and closing tag this now gives us
access to Clerk's

06:17:12
Hooks and components with the setup now complete we can start writing code to
implement our goals all right now that we have clerk set up let's add signin and
sign out functionality to our application the great thing about clerk is that it
provides pre-built components that handle all the authentication flows for us let's
start with the signin functionality Begin by creating a folder in the source folder
called components inside this folder create a file called navigation. TSX here
Define and Export a react

06:17:50
component called navigation I want a decent looking navigation bar with a logo and
a sign-in button so to save time I'll paste the component code which you can find
on my GitHub repo export const navigation we have the nav HTML element plenty of
taor CSS classes and each one tag next sh's app which is supposed to be our logo
and a placeholder for where the sign-in button should go include this component in
your layout. TSX file so it's rendered on every page right before children invoke

06:18:24
navigation and make sure to import it from at/ components SL navigation check the
browser and you should see the navigation bar with the logo like shs app now let's
add the sign-in button in navigation. TSX import the signin button component from
clerk import sign in button from at clerk / nextar render the component within the
div tag where you see the placeholder component sign in button on this component
set a prop mode is equal to modal this means clicking the button will open a nice
model dialogue instead

06:19:06
of redirecting to a separate page check the browser and you will see a sign-in
button in your nav bar go ahead and click it you will see Clerk's beautiful signin
model with all the authentication options we configured earlier since we don't have
an account yet I'm going to click on the sign up button at the bottom of the model
this presents us with the UI to create your account let's create an account with
email and password click continue and enter the verification code once verified we
will be redirected back to
06:19:40
the homepage we are now signed in let's proceed to add the sign out functionality
for signing out clerk provides a component called sign out button let's import and
add that right next to our signin button check the browser and you will see a sign
out button in your Navar go ahead and click it you will be signed out from the
application clerk automat automatically handles everything clearing the session
removing tokens and updating the UI if needed but right now there is no UI change
to indicate that

06:20:14
we are signed in or signed out let's work on that next we have the signin button
and sign out button components for signing in and out but for signing out cler
provides an even nicer component called user button let's import it comment out
sign out button and add it to the jsx instead us a button in the browser try
signing in and you will see it up here when you click it opens a drop- down menu
with two options we have sign out which performs the same function as our sign out
button component but the second is

06:20:56
manage account which opens a full profile management interface in a model dialogue
here you can update your profile picture update your email address update your
password delete your account and much more depending on your configuration in the
clerk dashboard but what if you prefer having a separate profile settings page and
not a model well no problem clerk provides a us a profile component that we can
embed in an optional catchall route I'm going to comment out the sign out button
import to make sure we don't

06:21:30
have a red squiggly error now for the separate profile page in the app folder
create a new folder called user profile user hyphen profile here add an optional
catchall route called user profile so double square brackets dot dot dot user
hyphen profile within this folder create a page. TSX file Define and Export a react
component called user profile page export default function user profile page at the
top import the user profile component from Clerk and render it as part of the jsx
so return a div tag to

06:22:10
add some styling to the page and then we invoke our user profile component with a
path prop set to/ user Hy profile now in the navigation component add a link to the
user profile page so link which needs to be imported from next SL link the text is
going to be profile hre is going to be equal to slash user profile the same path we
have specified here and comment sign out button and comment user button instead the
same for the import statement check the browser and you should see the profile Link
in the Navar clicking on it

06:22:53
should take you to the profile page with pa/ Usery profile and clicking on Security
will take you to/ user hyen profile SL security page clicking on sign out should
sign you out and redirect to the homepage as you can see clerk makes it super easy
to add profile management to your application next let's take a look at how to
conditionally render different parts of our UI based on the user's authentication
State previously we added signin sign out and profile management functionality to
our Niar application everything works

06:23:30
great but there is still a small issue a sign-in button and profile link are both
visible when we are already signed in and the sign out button is visible when we
are already signed out let's fix that by learning how to conditionally render UI
elements based on the user's authentication State clerk once again makes this super
easy with two special components signed in and signed out let's import them and use
them to update our navigation component so signed in and signed out components from
at clerk

06:24:02
SL nextjs in the Js X wrap the signin button with the signed out component and the
profile link plus the sign out button with a signed in component now the signin
button only shows up when the user is signed out and the link and sign out button
only appear when the user is signed in pretty neat right clerk handles all the
state man mement for us check the browser and you should see the signin button only
when you're signed out and when you sign in the profile link and sign out button
should appear the signin button is Now

06:24:49
hidden simple and straightforward now that we understand how to conditionally
render UI elements let's take it a step further and learn how to protect entire
pages from unauthenticated users if you're signed out try navigate to localhost
3000 SL user hyphen profile you will encounter a clerk runtime error user profile
cannot render unless a user is signed in what we need to do is protect this route
so that only authenticated users can access it the most robust way to protect
routes in X is through Clerk's middleware as

06:25:27
part of the setup you've already created a middleware dots file in the source
folder this is where you can configure Clerk's middleware Begin by importing a
function called create route matcher from clerk next create a matcher for the
routes that you want to protect invoke the function and pass an array of routes
that need to be protected in this case we want to protect SL user hyphen profile
route let's store the return value in a constant called is protected route finally
pass a function to clerk

06:26:03
middleware the function receives the Au object and the request object as arguments
in the function body we check if the request matches any of the protected routes if
is protected route passing in request and if it does we call the protect method on
the o object so o. protect we will need to await this and add the Asing keyword
make sure to get your parenthesis right as well protect method will redirect the
user to the signin page automatically if they're not signed in in the browser if we
try

06:26:38
to navigate to/ user profile again while being signed out we will be redirected to
the signin page that is hosted by clerk sign in with your credentials and you will
be redirected back to/ user profile we have successfully protected the user profile
route now in the middleware you can also invert the protection logic instead of e
protected route create e public route our public routes are the root route signin
route and signup route in the clerk middleware if not is public route passing in
request await or. protect so

06:27:18
the middleware will now protect all routes by default and you specify which routes
should be public this is useful when most of your application requires
authentication in the browser if we try to navigate to/ user profile while signed
out we will still be redirected to the sign-in page that is hosted by clerk sign in
and you can access SL user profile now if you want even more control over what your
application does based on user authentication status you can use the Au argument in
the middleware await

06:27:53
Au to get the user ID and the redirect to signin function if the user is not signed
in so if not user ID and the route is is not public so not is public route request
you can redirect to the sign-in page return redirect to sign in make sure to
destructure user ID the same logic as before but now you can add custom logic to
run before redirecting this could include logging unauthorized access attempts for
security monitoring routing users to region specific signin Pages or handle
maintenance windows for

06:28:32
specific routes whatever might be relevant for your application protecting routes
is a crucial part of building secure and personalized web applications which clts
middleware the process is simple and flexible when building web applications we
often need to access user and session data to personalize experiences and track
user actions with their account to read user and session data flirt provides two
helpers Au and current user let's understand how to use them with an example for
this example we will create a new

06:29:06
route called dashboard within the amp directory create a dashboard folder and add a
page. TSX file export a default function dashboard page that returns a heading
within the page import and invoke the O and current user helpers and inspect the
returned objects in a console so first import the Au and current user methods for
from clerk slns SLS server then invoke them in the dashboard page component so Au
and current user and await the returned objects the O helper will return the O
object of the currently active user so

06:29:52
const o object is equal to await o the current user helper will return the backend
user object of the currently active user so const user object is equal to await
current user log both the objects to the console object comma user object in the
browser once we are signed in if we navigate to/ dashboard we should see the Au and
user objects logged in the console if you inspect the O object you'll see user ID
session ID session claims redirect to signin and so on the user object contains
email

06:30:34
addresses first name the user ID image URL last name Etc in sever components and
Route handlers you will typically use the user ID from the Au object and query the
database with it of these two helpers Au and current user are useful in server
components and Route handlers but don't work in client components in a client
component you can read the same data using use Au and use user hooks let me show
you how in the components folder create a new file called counter. TSX Define and
Export a simple counter

06:31:13
component export const counter we invoke US state with a value of zero we render
the count value and on click we call set count incrementing the count value by one
a very straightforward counter component and use client directive at the top to
make it a client component a very straightforward client counter component let's
import and invoke this component in the root page. TSX file below the image
component so counter make sure to import it from at/ components SLC counter then
back in the counter component import the use Au and

06:31:56
use user hooks from clerk from at clerk SL nexts in the component invoke use o and
destructure The Returned object to access the properties is loaded user ID session
ID and get token also invoke use user and destructure The Returned object to access
the properties is loaded is signed in and user they do have conflicting properties
so let's use them one at a time from use o you can use the East loaded and user ID
properties to return null in case the user signs out while the component is mounted
so if not

06:32:46
e loaded or not user ID return null save the file head back to the browser and
click sign out and you can see the component is removed from the UI similarly from
use user you can use the E loaded and is signed in properties to return null in
case the user signs out while the component is mounted either of these conditions
work in the browser sign in again and we can see the counter component sign out and
our app continues to function as expected the component has been removed you can
rely on use o

06:33:27
if you just need the user ID to personalize experiences or associate data with the
user use use user only if you need the full user object speaking of users up next
we will learn how to work with roles and permissions now that we have covered
authentication and session management let's move on to something really important
for your web applications user roles and permissions most apps need more than just
checking if someone is logged in or not they need different permission levels for
different users so

06:34:01
let's learn how to implement role-based Access Control using clerk first things
first we need to configure clerk to make user roles available in our session token
clerk gives us something called user metadata which is like a storage space for
extra user information in our case we will use it to store user roles we will
specifically use something called public metadata because it is read only in the
browser making it super secure for storing sensitive information like user roles to
build a basic arbac

06:34:32
system we need to make sure this public metadata is readily available in the
session token by doing this we can quickly check user roles without having to make
extra Network requests every time we need this information this makes our
application much more efficient here's what you need to do head over to the clerk
dashboard and under the configure tab find the sessions page under customize
session token click edit in the model that opens add Json with the following key
and value metadata within double curly braces userpublic

06:35:10
metadata scroll down and click the save button for the second step we will need to
create a global typescript definition to work with roles back invs code in your
applications root folder create a types directory inside this folder create a
global. D.S file here start by exporting an empty object this makes the file a
module next we Define what roles are available in our application imagine a social
media app where moderators can moderate content and admins can manage moderators so
export type roles is equal

06:35:52
to admin or moderator these are the two roles for our application next extend
Clerk's session token type globally declare global Li brais interface custom GWT
session claims we specify metadata role optional of type roles this will provide
Auto completion and prevent typescript errors when working with roles throughout
our application for the third step we will manually add the admin role to our own
user in the clerk dashboard navigate to the users tab select your own user account
which should be the only user in the list

06:36:33
scroll down to the user metadata section and next to the public option click edit
update the Json with the key roll and value admin click save for the fourth step we
will Define and protect a new admin route in the app directory create a new admin
folder with a page. TSX file here export default function admin returns an H1 tag
admin only page now to view this page you not only have to be signed in but also
have the admin role so to protect this route we will apply Ro based Access Control
in our

06:37:15
middleware dots file first use create route matcher to create a matcher for the
admin route so const is admin route is equal to create route matcher and the path
is/ admin next add a check for the user's role in the middleware function if is
admin route of request and await Au dot session claims do metadata. rooll is not
equal to admin const URL is equal to new URL path is for Slash and the second
argument is request. URL we return next response. redirect and pass in url make
sure to import next response from next

06:38:03
SL SL server in the browser make sure you're signed in and navigate to the admin
route SL admin you should be able to access it now back in the cler dashboard
change the role to moderator and click save try to access the admin route again so
SL admin and you will be redirected to the homepage our rback system is working as
expected of course manually adding roles to users is not scalable in a real world
application an admin will want to be able to manage user roles so for the fifth
step we will create server

06:38:44
actions to manage user roles in the admin folder create a new actions. TS file
start with the use server directive next we will Define a function to set a role
for a user export Asing function set role and the function receives the form data
of type form data within the function we first need to check that the user calling
this action is an admin we can do this by checking the session claims. metadata.
roll on the Au object at the top import o from clerk nexs SLS server and within the
function extract

06:39:26
the session claims const session claims is equal to await all if the user role is
not an admin if session claims metadata role is not equal to admin we will return a
not authorized error so throw new error not authorized if the user is an admin we
will get the clerk client to update the user's role so import clerk client from
clerk nexs SLS server and invoke it within the component const client is is equal
to a wait clerk client now this server action expects a form submission with two
types of info so const ID is

06:40:13
equal to form data. get ID as string and Ro is equal to form data. getet roll as
roles make sure to import it from types SLG globals ID here refers to the user we
are updating and roll ref refers to what role we are giving the user either admin
or moderator next within a tri block use the clerk client to update the user role
so await client. users. update user we pass in ID as the first argument and for the
second argument it's an object where we specify public metadata this is an object
where we set

06:41:00
role equal to the Past in role if there is an error throw new error failed to set
role let's make sure the syntax is Right similarly we'll Define a function to
remove a role from a user I'll paste the code here but let me walk you through the
code so export using function remove role which receives form data once again start
by checking that the user calling this action is an admin then get the clerk client
and extract the ID from the form data finally within a triy block use a clerk
client to update the user's role

06:41:38
to null if there is an error through a new error failed to remove Ro in both the
functions if the update operation is successful we will call revalidate Path and
revalidate SL admin this will automatically update the admin UI without us having
to refresh the page when we update a role all right with these two server actions
we can now manage user roles in our application for the final step we will flesh
out the admin page to let admins manage user roles from the user interface now this
is a pretty verbose react component but

06:42:14
you already know the fundamentals of how to write react components I'm going to
paste the code to save us some time it's about 78 lines of code but let me walk you
through what I've pasted we still have export default function admin we get hold of
clerk client and call users. getet user list. data to fetch the list of users from
clerk we then map over that users list in the UI there's some Tailwind CSS styling
for alternate rows we render user. first name and user. last name the primary email
address the

06:42:51
role of the user and then against each user we have make admin and make moderator
buttons which include hidden inputs for user ID and rooll these buttons use the set
rooll server action to update the role for the given user ID we also have a remove
roll button that calls the remove roll server action passing in the user ID let's
go back to the browser change our user Ro back to admin and navigate to the admin
route so slash admin I'll close the dev tools for some extra space I'm also going
to

06:43:32
register with a new user behind the scenes in a different browser all right I've
registered with a new user in Firefox but this user will not have the admin rooll
so they won't be able to access the admin dashboard navigate to/ admin and you will
be redirected to the homepage in the first browser refresh the page and you will
see the new user using this admin account update the role of the new user to admin
so click on make admin we can see the role is now admin with the user logged in
Firefox try to access the

06:44:10
admin dashboard again/ admin we able to view the admin component our custom rbac
system is working as expected now to make arback more streamlined in larger
applications clerk also provides a built-in organizations feature with a roles and
permission system you can learn more about it in the documentation but if you're
building a small application our custom arbac system should be good enough with
that we have successfully implemented all our authentication goals next let's take
a look at some of the customization

06:44:45
options available when using Clerk's components now that we have an end to-end
example of authentication with clerk let me walk you through customizing the signup
and signin flows currently our navbar has a sign-in button that triggers a model
when clicked this model lets users sign in and if they don't have an account they
can easily switch to sign up using the link at the bottom however many applications
prefer to have a dedicated signup button that initiates the signup flow directly
you can easily achieve

06:45:18
this by importing the sign up button component from clerk in navigation. TSX import
sign up button from Clerk and add it right below signin button mode is equal to
model in the browser you will see a sign up button appear in the Navar clicking it
launches the signup model and users can switch to sign in using the link at the
bottom if needed very straightforward next let's talk about styling when working
with clerk you're not stuck with the default button Styles you can completely
customize how your signin and sign up

06:45:59
buttons look it is as simple as nesting a button element with your own CSS inside
the signin button and sign up button components change from self closing to opening
and closing tags in between the tags include an HTML button element this is sign in
and this is sign up let's add some tailin CSS to both buttons take a look at the
browser and you will see both buttons have been customized now what about having
dedicated Pages for sign in and sign up instead of models that is also very easy in

06:46:42
navigation. TSX on the sign-in button and sign up button remove the mode is equal
to model Pro back in the browser click on sign in and clerk will redirect you to
the dedicated sign-in page similarly click the sign up button and you will land on
the signup page now if you check the URL you might notice we don't see our apps
domain that is because these pages are hosted by clerk if you would prefer to keep
users on your domain you can create your own signin and sign up Pages while still
using Clerk's components here's how to

06:47:21
do it in your app directory create a signup folder with an optional catch all route
so new folder within double square brackets dot dot dot sign up is the name and add
a page. TSX file with a simple react component export default function sign up page
and we return a div tag that renders the signup component from clerk make sure to
import it from at clerk sln shares I will also add some styling to the div tag FX
justify Center item Center and some padding do the same for signin by creating a
new signin

06:48:08
folder with an optional catch all route so double square brackets dot dot dot sign
in and add a page. TSX file copy paste the component code for signup page. TSX and
change sign up to sign in sign in is another component that cler provides when you
add these two pages ensure both routes are public in your middleware dots file we
already have it from the time we learned about middleware if you don't please make
sure to add these two routes finally update your env. looc file with two new
environment variables next public clerk

06:48:52
signin URL and next public clerk sign up URL they point to slash signin and SL
signup which are the two routes that we have just created make sure to restart your
Dev server so npm run Dev and head back to the browser now when users click either
button to sign in or sign up they will stay on your domain at/ signup or/ signin
lastly let's talk about redirects after authentication by default clerk is pretty
smart it remembers where users came from using a redirect URL query parameter try
it out let's create a

06:49:35
simple upout page in the app folder export default function about return H1 tag
about page and navigate to localhost 3000 slab since every page is a protected Page
by default we are redirected to/ signin you'll notice how redirect URL is equal to
http localhost slab when you continue you're redirected to slab about while this
default Behavior works well in most cases you can customize it using environment
variables you have two options for fallback URLs next public clerk sign up fallback

06:50:20
redirect URL and next public clerk sign in fallback redirect URL the first one is
to set the fallback redirect URL after sign up in case the redirect URL query
parameter is missing the second one is to set the fallback redirect URL after sign
in in case redirect URL query parameter is missing if you don't care about the
redirect URL query parameter and you want to force specific redirects regardless of
where users came from you can make use of next public clerk signup Force redirect
URL and next public clerk signin Force

06:50:56
redirect URL with these Force redirects users will always land on/ onboarding after
sign up and/ dashboard after signin currently we haven't created the onboarding
route so make sure to create it if you want to test this out but as you can see
clerk offers plenty of flexibility in customizing your authentication flows next up
we will look at deploying our application all right for the final Topic in this
course let's see how to deploy an EXs application for this demo I will be using
GitHub and ver

06:51:33
verell is a platform by the nexs team that lets you seamlessly deploy nexs
applications step one ensure your code is pushed to GitHub as you can see I already
have a repo created which is the same repo I've used for the entire series next
year 15 tutorials we have a couple of applications in here and we will deploy the
authentication demo amp we have recently worked on step two head over to ell.com
and sign up if you're new to verell I I'm going to log in with GitHub once you're
logged in add a new

06:52:08
project if you're doing this for the first time you will need to install verell
when prompted I'm going to select my GitHub account which is already linked our
code is in the nus 15 tutorials repo which I'm going to import for verel team I'm
going to select my personal account and choose the framework preset as ni shares
for the root directory we're going to click on edit and select authentication demo
continue we can leave the build and output settings as they are but expand the

06:52:42
environment variable section to enter the key value pairs from your project our
project has four environment variables select all copy and paste where cell
automatically creates the four environment variables with the values finally click
on deploy this will take a minute to build and deploy for your application once the
process completes we should have a preview of the application clicking on it will
take us to our application hosted on a verel URL next sh 15 tutorials. verel doapp
sign in with the test account

06:53:19
credentials and our application works as expected now if you have a custom domain
you can of course point this app to that domain but as far as a simple build and
deploy with GitHub and verell is concerned this is all you have to do very very
straightforward well with that we come to the end of this course on nexs I hope you
have a much better understanding of the concepts now than you did before starting
if you enjoyed the course and found it helpful please click the like button and
subscribe to the channel as

06:53:51
it helps out a lot share this course with your friends or teammates and hopefully
they start using this amazing framework as well as always thank you for watching
and until next time take care supporting the channel is free please like And
subscribe it helps a lot

You might also like