Next-Auth Login Authentication Tutorial with Next.js App Directory
Summary
TLDRIn this tutorial, Dave introduces viewers to adding authentication to a JavaScript application using Next Auth. He highlights the ease of integration with Next.js, showcasing support for JSON Web Tokens and OAuth, including GitHub login. Dave demonstrates setting up Next Auth with the new Next.js app router, creating API routes, and customizing options for providers. He also discusses the use of Cody AI for code analysis and test generation, emphasizing its benefits for ensuring code reliability. The video concludes with examples of protecting pages and utilizing client components with Next Auth, encouraging further exploration of its customizable features.
Takeaways
- π The tutorial demonstrates how to add authentication to a JS app using NextAuth and Next.js.
- π It introduces Kodium AI, a tool that generates tests to ensure code reliability and correctness, supporting JavaScript, TypeScript, and Python.
- π The video provides a step-by-step guide on setting up NextAuth with JWT and OAuth for GitHub login, emphasizing ease of use and customization.
- π It mentions the support for serverless environments and the ability to use NextAuth without a database.
- π The script covers the creation of API routes and the use of the new app router in Next.js version 13.2 and above.
- π οΈ The tutorial explains how to set up environment variables for NextAuth, including a secret for encryption.
- π The process of configuring OAuth with GitHub is detailed, including generating client IDs and secrets.
- π± The script discusses different methods of protecting pages in a Next.js application, such as using server components and middleware.
- πΌοΈ It highlights the ability to display user data, such as images from GitHub, after OAuth login.
- π The importance of using Next.js configuration to handle images from external sources is mentioned.
- π The video concludes with an invitation for viewers to request more tutorials on advanced authentication topics like role-based authorization.
Q & A
What is the main topic of the video?
-The main topic of the video is adding authentication to a JavaScript app using NextAuth and Next.js.
What is the sponsor for this video?
-The sponsor for this video is Kodium AI, a tool that analyzes code and generates tests to catch bugs.
What does NextAuth support for authentication?
-NextAuth supports JSON Web Tokens (JWT) and database sessions for authentication.
What is the default session handling strategy used by NextAuth?
-The default session handling strategy used by NextAuth is encrypted JWTs, referred to as JWEs, stored inside a session cookie.
How does NextAuth handle OAuth authentication?
-NextAuth handles OAuth authentication by allowing users to set up providers like GitHub, Twitter, Google, and Facebook, and configuring them with their respective client IDs and secrets.
What is the purpose of the 'credentials' provider in NextAuth?
-The 'credentials' provider in NextAuth allows users to authenticate using a username and password combination.
How does the video demonstrate setting up GitHub as an OAuth provider?
-The video demonstrates setting up GitHub as an OAuth provider by creating a new OAuth app in the GitHub account, obtaining the client ID and secret, and configuring them in the NextAuth options.
What is the role of the '.env.local' file in the NextAuth setup?
-The '.env.local' file is used to store environment variables such as the NextAuth secret and provider secrets, which are essential for the authentication process but should not be shared publicly.
How does NextAuth apply authentication to the entire Next.js site?
-NextAuth applies authentication to the entire Next.js site by using middleware that checks for user authentication on every page request.
What is the difference between server components and client components in Next.js?
-Server components in Next.js are rendered on the server and can access server-side data, while client components are rendered on the client side and are typically used for interactivity. Server components are usually used as the parent, and client components are imported where needed.
How does the video handle user session data in client components?
-The video creates a React context called 'auth provider' that wraps client components, allowing them to access session data from NextAuth.
What additional configuration is needed in Next.js to display images from external sources like GitHub?
-To display images from external sources, the video mentions configuring 'next.config.js' with remote patterns to allow images from specific origins.
Outlines
π Introduction to NextAuth for JS Apps
Dave introduces the tutorial on integrating NextAuth for authentication in a Next.js application. He mentions resources, a Discord server for discussion, and highlights Kodium AI as a sponsor, which generates tests for code review. The video covers setting up NextAuth with JWT and OAuth for GitHub login, using Next.js 13.4.7, and installing NextAuth with npm.
π Setting Up NextAuth with Route Handlers
The tutorial explains how to set up NextAuth using the new route handlers in Next.js 13.2 and above. It details creating the necessary API routes and directories, and initializing the NextAuth configuration. The video also discusses NextAuth's support for JSON Web Tokens, database sessions, and its serverless compatibility.
π Configuring OAuth and JWT in NextAuth
Dave walks through configuring OAuth for GitHub and setting up JSON Web Tokens in NextAuth. He explains creating a .env.local file for environment variables, including the NextAuth secret, and obtaining GitHub's client ID and secret. The process of setting up providers in the options object is also covered.
π Implementing Credentials Provider and GitHub OAuth
The video demonstrates how to implement the credentials provider for username and password authentication and set up GitHub as an OAuth provider. It includes creating an authorized function for the credentials provider and using environment variables for storing sensitive information like GitHub's client ID and secret.
π Applying NextAuth for Site-Wide Protection
Dave shows how to apply NextAuth for protecting entire site routes using middleware in Next.js. He explains creating a middleware file and using a matcher to apply authentication to specific routes. The video also reviews different ways of protecting pages, such as using server components and NextAuth's auto-generated sign-in pages.
π Utilizing Client Components with NextAuth
The tutorial covers using client components with NextAuth, including creating an auth provider with React context to share session data. It explains the use of the 'use client' hook, session handling, and conditional rendering based on authentication status in client components.
πΌοΈ Displaying User Data and Images from OAuth Providers
Dave discusses displaying user data, such as images from GitHub, after OAuth login. He shows how to modify the user card component to display the user's GitHub image and mentions the need to configure Next.js for remote images from OAuth providers.
π Conclusion and Future Tutorials
In conclusion, Dave expresses his satisfaction with NextAuth's ease of use and customization options. He invites viewers to request future tutorials on topics like role-based authorization and thanks the audience for their support, emphasizing the importance of making progress in learning.
Mindmap
Keywords
π‘NextAuth
π‘Authentication
π‘JSON Web Tokens (JWT)
π‘OAuth
π‘Serverless
π‘Environment Variables
π‘API Route
π‘Middleware
π‘React Context
π‘Client-Side Rendering
π‘Server-Side Rendering
π‘Progress over Perfection
Highlights
Introduction to integrating NextAuth for authentication in JS apps with detailed tutorial and resources.
Invitation to join Discord server for web development discussions and support.
Sponsorship by Kodin AI, a tool for code analysis and test generation to ensure code quality.
Kodin AI supports JavaScript, TypeScript, and Python, and can be integrated into VS Code and other IDEs.
Demonstration of Kodin AI's test generation feature for code review and reliability assurance.
Installation guide for Next.js project and the importance of selecting the correct version for tutorial alignment.
Explanation of NextAuth's support for JSON Web Tokens and database sessions, and its compatibility with serverless environments.
Guide on setting up NextAuth with the new Next.js app router for API route configuration.
Step-by-step instructions for creating API routes using Next.js 13.2 and above with route handlers.
How to set up a custom options object for NextAuth, including providers and other settings.
The use of environment variables for storing NextAuth secrets and the creation of a .env.local file.
Configuration of OAuth for GitHub login, including setting up a new OAuth app in GitHub settings.
How to retrieve and securely store GitHub client ID and secret in the .env.local file.
Setting up the credentials provider in NextAuth for username and password authentication.
Different methods of protecting pages in Next.js using NextAuth, including server and client components.
Middleware implementation in Next.js for applying NextAuth across the entire site or specific routes.
Discussion on the use of server components versus client components in Next.js for optimal performance.
How to create an auth provider using React context for client components that require session data.
Final thoughts on the ease of use and customization options of NextAuth for Next.js projects.
Transcripts
[Music]
hello and welcome I'm Dave today we're
going to learn how easy it is to add
authentication to your next JS app with
next auth and I'll provide links to all
resources in the description below I'll
also provide a link for you to join my
Discord server where you can discuss web
development with other students and you
can ask questions that I can answer and
receive help from other viewers too I
look forward to seeing you there I'm
ready for a highly requested tutorial
about next auth with the new next.js app
router but first i'm happy to introduce
kodium AI as the sponsor for this video
codium AI analyzes your code and
generates meaningful tests to catch bugs
before you ship to production or even
before you have a code review with your
boss or Mentor with kodium AI you can
easily and quickly create comprehensive
test Suites that help ensure the
reliability and correctness of your code
and Cody may I currently supports
JavaScript typescript and python in VSCO
code and several other popular Ides
let's look at how it works just click
the generate test button above any
function and codium AI will begin
generating tests for your code review
the test created and even add your own
custom tests also check out the code
analysis and code suggestions I love
these features and when you're happy
with the tests save the test Suite to a
file I'm going to provide links to their
vs code extension and main website below
hey guys adding codium AI to your vs
code is as easy as going to extensions
searching for kodium AI and then
installing it it's free add it to your
vs code extensions today okay let's get
started I've already created a new
next.js project and I've said yes to all
of the questions as the project was
created now looking at the package Json
if you're completing this tutorial in
the future you should note that I'm
using next version
13.4.7 its current as of today and if
you want next to behave the way it does
here in the tutorial you may want to
install this version but I'm just
letting you know that you could try to
use the latest as well so after that we
need to go ahead and install next auth
so let's open up a terminal window once
again type npmi and then next Dash auth
and we'll install the next auth package
we're back at the next auth website and
I'm looking at the introduction they
really have great docs and you can
explore these because next auth is very
customizable we're going to go over some
of the basic settings for a quick
implementation today and that will get
you started and of course I could cover
other customizable settings in future
tutorials as well so let's look at some
of the introduction here on next auth
and I want to highlight just a few
things we've got support for Json web
tokens and database sessions and this is
designed for serverless next.js does run
on serverless but it can also run
anywhere so next auth can work with AWS
Lambda Docker Heroku Etc It also says
own your own data here and I just want
to highlight that it says it can also be
used without a database and that's what
we're going to do today we're going to
use the default settings for JWT but
we're also going to set up oauth for a
GitHub login now let's go to the getting
started link over here in the left hand
menu and on getting started we're going
to scroll down just a little bit and we
can already see the install for next
auth and we've already done that then it
says add an API route but notice a lot
of the examples here in the docs at
least currently as I'm making this video
show the old version here with Pages
slash API slash auth but then you need
to read some of the documentation as
well because it says if you're using
next.js 13.2 or above it does support
the new app router and you can
initialize the configuration using the
new route handlers by following our
guide so let's just go ahead and click
that guide and look at the setup here
for a route Handler you can see this has
a different different path now it's in
the app directory as we're provided in
next js13.2 and above then we create an
API directory inside then an auth
directory and then this catch-all route
here inside of brackets with the three
dots that says next auth and then route
TS so let's go to visual studio code now
and do that back in vs code we need to
open up the source directory if you
added the source directory to your
project if not you just have the app
directory on that level and that's where
you need to create the next directory or
folder if you will inside and it's
called API and then inside of that one
we need to create another directory and
this is going to be called auth and then
finally inside of auth we need to create
that catch-all that has a bracket three
dots and then next auth and another
bracket now inside of this directory is
where we create the route.ts file we'll
start by importing next auth and that's
going to come from next Dash auth after
that we're we're going to import options
here in just a moment but I won't do
that yet let's define our Handler
and we're going to set this equal to
next auth and this is where next auth
will receive the options so it's going
to have a red squiggly until we pass in
our options object but after this we
just simply need to export and we'll say
Handler as get comma and also Handler as
host so our route.ts file is not too big
and you will see some go ahead and
Define their options object inside of
this file but I prefer to create a
separate file so let's go ahead and do
that and we'll just call this
options dot TS we're back in the next
auth documentation we're under options
now in the left hand menu and looking
under options the main thing we need to
provide inside of our options object is
the providers themselves what we plan on
using so this is where we will say a
GitHub provider that we're going to use
with oauth we're also going to have a
credentials provider and we'll learn how
to set that up but there are some other
settings they cover on this page so let
me scroll down just a little bit it
talks about a secret here we're going to
need to set a next auth underscore
secret as an environment variable so
we're going to create a DOT env.local
file in our next JS project for that and
then there's some other settings they
cover as well oh and we're going to use
this by the way to go ahead and create
that random secret we can do that easily
with this command in the terminal okay
underneath that a few other settings
that we can look at although we're just
going to use the default today so we
will not need to provide these but I
just want to draw your attention to them
you can set some settings for a session
here and this is where I wanted to
really highlight this because note the
default is a JWT that's encrypted so
it's referred to as a jwe so if you've
watched any of my previous React auth
videos in the past where we use JWT this
is a little different strategy but I
really like what they're doing and
really rather than rolling your own
which creating your own like we did in
that react auth series is a great way to
learn about auth but this has a little
more full featuredness to it and I
really like how it's set up so I
recommend this strategy actually and you
would use this encrypted jwe that's
stored inside of a session cookie so
that's how they're doing this by default
and then you could use a database
instead but that's not what we'll be
doing we will just be using the JWT that
is once again the default so just
highlighting that okay let's scroll down
to just a little bit more and then
there's also a JWT setting once again we
won't need to do any of this because
we're using the default and we're not
using a database and then they've got
some other settings for the JWT but the
other one I want to find is pages so
notice this this pages is a property
here inside of that options object and
then it has its own object here you can
set up custom pages but if not these
will be created for you they'll just be
found at a specific address that next
auth provides so if you wanted to create
a custom sign in page then you could
have it at say just slash sign in
instead of the default which might be
auth sign in or auth sign out and so on
ours because of this new router or route
Handler set up inside of the API slash
auth directory everything that's created
by default will actually be inside of
Slash API slash auth and then then we
would have our sign in and sign out but
next auth creates these for us and so
just by using the defaults we can
implement this next auth quickly okay
let's go back to the code and set up our
options object and our next auth secret
as well let's start with import type and
then we need next auth
options and this is also going to come
from next Dash auth after we've imported
our type we will import our providers
when we're ready for those but let's
first just set up the object so I'll say
export const
options and we'll set this of course the
type being our next auth options we'll
set this to an object then that has a
providers and this providers is an array
so this is where we will put our
providers that we decide to import and
use in our application now after this
this is where we would put for example
the pages object that we looked at so if
we had a specific sign in then we could
give the path for that so you might want
to move it to just sign in but then you
would have to create your own sign in
page and next auth we'll create one for
you so we're not going to provide this
here the same for the session you would
set a session and then set the related
properties for that session that we
looked at inside of the documentation
but now we're just going to focus on the
providers but before we go back to the
docs and look at each individual
provider let's go ahead and open up a
terminal so control in the back tick now
inside of the terminal let's type that
command that will will just generate
that random secret for us so it's open
SSL
Rand and then Dash base 64 and then the
number 32. we'll press enter and there
is our random secret that we have so we
can just highlight and copy this with
Ctrl C and now we need to go ahead and
create a DOT env.local file in our next
project and we want this on the same
level as the package Json file so now
let's create this file and it's dot
env.local by default this would be
listed inside of your git ignore file
you never want to send your environment
variables to GitHub so these are secrets
you keep them in your Dev environment in
the dot enb.local and then when you
deploy your application you set the
environment variables in your host
whether that's versl or somewhere else
that you would deploy your next JS
application so this is a next auth
underscore
secret and we'll set it equal to and
just paste in that value with control V
is what I use to paste and now we have
in that random value you will have a
different value here and of course I'll
delete these secrets in the future and
won't be using those online so no luck
using mine just go ahead and generate
your own you will not find this dot
env.local file in the source code for
this video because as I said you do not
share this file in your GitHub back in
the documentation we're under
configuration providers and then
credentials this is where we would sign
in with a username and a password and
this is showing us how to set up the
credentials provider that we would need
to import at the top here and it has
some explanations but I'll of course
walk you through this as we created in
our project as well and then another
type of provider is oauth now oauth can
be GitHub Twitter Google Facebook any of
these providers that provide an oauth
sign-in and you've probably seen before
where you can just click sign in with
GitHub or sign in with Google and so on
so that's what we'll be setting up now
there is a full list of them further
down in the menu here under providers
and then you can scroll to get the
details for each one that you want to
set up here's GitHub and after we scroll
down just a little bit you'll see
there's a link and we need to configure
this in our GitHub account so now you'll
already need a GitHub account to do this
and so if you don't have a GitHub
account I'd go ahead and suggest going
to github.com and getting that free
account set up and then coming back and
do this but most of us probably already
have a GitHub account at this point so
let's go ahead and click this link and
it should open up directly to the page
we need of course inside of your GitHub
account this one is mine as you can see
my little icon up here in the top right
so now that we're at the GitHub apps
page we want to click on oauth apps and
we want to set one up you can see I
previously set one up as I did some prep
for this tutorial now I'm going to click
new oauth app here in the top right I
need to give this a name so I'm going to
call this
next auth Dash Tut for tutorial and then
the home page URL is going to be HTTP
colon slash slash localhost colon 3000
so this is for our Dev environment when
you would deploy your application you
would need to come back into your GitHub
settings for this oauth setting and
change it to your deployed URL and then
the other URL here at the bottom
authorization callback URL starts the
same but after that we're going to have
a slash and say API slash auth slash
callback slash GitHub and that would be
the full callback URL this is basically
saying where it's going to send you
after you authenticate with GitHub where
should it send you back in your
application so now let's go ahead and
click register application and we should
be good to go now what we want to have
here is a client ID and a client secret
we haven't generated that yet let's
first get the client ID copied I just
put my client ID in a text file for now
and you could do the same or paste it
into a file in vs code whatever just so
you make sure you have that or you could
come back to this tab then generate a
new client secret and you'll need to log
in if you're not logged into your GitHub
or actually I was logged in they just
want you to confirm access so you'll
need to log in again okay I logged in
and now notice I have make sure to copy
your new secret client now you won't be
able to see it again so make sure to
just click the copy little icon here and
copy this and again save it somewhere
and we're going to put it in our DOT
env.local so if you just want to go
straight to that file we can do that now
too so make sure you get it here because
when you come back it will no longer be
available to see the full length of this
secret you would just have to generate
another one if you didn't save it back
in our DOT env.localfile I'm going to
call this
GitHub Secret
and after that I'm going to set it equal
to the value that I copied out of GitHub
for the secret I'm also going to have
GitHub underscore ID and I need to get
that ID value that I saved in a text
file and then I'll paste it in here as
well so now I've got my GitHub ID and
GitHub secret saved in the dot env.local
file and it's worth noting that even the
GitHub client ID that you have here
changes for each one of those that you
generate for oauth so this isn't the
same between those and of course I'll be
deleting this as well now that we have
our secrets in our DOT env.local file
let's go back and complete our options
with the providers that we need to
insert so once again at the top of the
file we need to import each provider so
I'm going to
import then say git hub
provider and this is going to come from
next Dash auth slash providers slash
GitHub and then I'm also going to import
the credentials
provider
which should come from next
Dash auth slash providers slash
credentials okay we've imported both
providers we need now let's set those up
so I'll go ahead and create some space
here in the array and the first is the
GitHub provider then we have a
parenthesis and an object inside now
we'll have a client ID and this refers
to the value that we set up for the
GitHub ID so we want to say
process.env dot
GitHub underscore ID now notice
typescript still doesn't like this and
we can Mouse over and says type string
undefined is not assignable to type
string so we can just use an assertion
here at the end because we know we have
a string in r dot env.local file so we
can just say as string remember an
assertion is essentially telling
typescript that you know better then
we've got client secret we'll set this
to process.env dot GitHub underscore
secret and we can then once again say as
string and that's really all there is to
setting up our GitHub provider so our
oauth with GitHub is ready to go now
let's go ahead and set up the
credentials provider it takes just a
little bit more work but this is
something you're almost always going to
want as far as having users be able to
use a login name and a password so here
we're going to have
credentials provider and then we've got
a parenthesis and an object once again
where the name here will just say
credentials after that we've got a
credentials property
and here this is going to be an object
and then inside of this object we're
going to have a username set up which is
another object so here let's say
label and we're going to have this as
username and this will actually appear
on the page so I want username colon
then after that there's going to be a
type and this is a text type and then
we're going to have a placeholder so
really we're kind of defining our HTML
input here and the placeholder you could
put pretty much anything you want to I'm
going to say your
Dash cool Dash username so this is just
a placeholder for that text field then
after that we're going to have another
comma here so we've got the comma for
the credentials then we've got that's
actually for the username and then we've
got the comma or the credentials and
after that we need to have an async
function here that is an authorized
function and we pass in those
credentials that are received now this
is where you would actually want to get
your data from a database if you had a
user database and you typically would
with credentials or some place you're
getting the information from where
you've set up these users already I'm
just going to hard code in a user and
I'm just going to copy and paste this
part in because it's mostly just a
comment here that I wanted to note
inside of the code for this tutorial to
remind you this is where you would
retrieve your credentials from whatever
user table or other source where you are
storing your user information so here
I'll hide the file tree with control B
just so we can read all of this but I
said this is where you need to retrieve
your user data to verify credentials and
then reference the docs at this page
where you shows how to configure the
providers because they do Show an
example of retrieving some user data and
then comparing it so how that would work
I'm just hard coding this user here
which is my name Dave and a simple
password next auth but you would not
want to do this this will run on the
server but this is not probably what
you'd want to recommend by hard coding
users that's not too flexible certainly
doesn't grow with your application
compared to setting up something where
you would retrieve users from and now we
just need an if statement so let's say
if and we'll have our credentials that
the
function receives and will say if there
is a username notice I'm using optional
chaining here if that's equal to the
user.name and remember users what I just
defined right here then let's use the
double Ampersand because we also need to
say
prudentials
password once again optional chaining
equals the user
dot password and I'm going to press alt
Z to wrap this down so it just wraps all
the way down oh and I'm getting a red
squiggly here because I didn't Define
the password up here under credentials
so that's reminding me to go back so
thank you typescript we will go back
let's finish this if statement quickly
and then inside of the if statement if
they match we're just going to return
the user and then we can have an else
and if they don't we're just going to
return null so you could make this a
ternary statement if you wanted to I
think the if statements may be just a
little easier for everyone to read let's
go ahead and Define the password up here
as well which is of course why we had
the comma there to begin with so now
we'll have our password and this gets
defined much the same way so we'll start
with our label and the label is going to
be
password and I'll put a colon there as
well because this does appear on the
page now the type of input here
is a password
and then finally we'll put a placeholder
you may not want a placeholder for your
password field but I'll go ahead and put
one and I'm going to say here
awesome
password now we should not have a red
squiggly from typescript because we've
defined both username and password on
the credentials that are passed in and
so then it recognizes both properties
let's take a quick scroll down to make
sure we've closed out our object and yes
everything looks good so the options are
now set up let's go back to our route
file and import those options here at
the top so I'm going to say
import
options and that's going to come from
dot options so now we've got that we can
just pass it into our next auth here
inside of the route and the routes
configured I'm going to press Ctrl B to
show the file tree once again over here
so we're inside of the route file and
now this is configured with options that
we defined in the separate file and we
could go ahead and start the application
now and what we want to do is make a get
request because it will already give us
some information about our next auth
setup so let's go ahead and open a
terminal and I'm going to type clear
first just to get everything else out of
here then type npm run Dev which should
start the application and it won't take
too long and it will tell us it's
running here at localhost 3000. it's
already up and running so we can close
the terminal now I've got thunderclient
installed you could make a git request
with Postman you could actually take the
URL and paste it into a browser and make
a get request that way also so just
let's look at what we've got here I've
got thunderclient and now I'm going to
make a get request and I already have it
set up but here's what we want is our
HTTP not https just HTTP in our Dev
environment colon slash localhost colon
Port 3000 then API auth providers so
that's where we're going to make our
request let's send that get request and
let's see what we get back from next
auth with our information and it's
telling us quite a bit about our setup
here so we have GitHub set up as a
provider it's type oauth and the sign in
url that is generated for us
automatically is found at API auth sign
in GitHub and then here's the Callback
as well now here is the sign in url for
credentials API auth sign in credentials
and then here's the Callback URL and of
course it's type credentials so just by
sending a get request to our API auth
providers we can get this information
from next auth so again just by using
the default settings in next auth it
does a lot of the heavy lifting for us
and that's what I wanted to show today
now I'm going to throw a few examples
into the front end of our next JS app
and then we'll review those as well okay
I've got the front end project up and
running and I want to show you the
behavior of the project before we look
at the code notice I'm on the home page
right now and it says You shall not pass
so I am protecting this page and what I
have in this project are three different
server components that are all protected
in a different way so I want to show you
all three ways you can do that I also
have a client component so first we're
on the home page we're not logged in
with GitHub or our credentials so it
says you shall not pass now I could try
to go to the server page it's protected
in a different way so let's try that if
we go here we instantly get the sign in
page that next auth creates on its own
you can see it says your cool username
name your awesome password just like we
set up for the placeholders we could
click here to use oauth to sign in with
GitHub or I could sign in here with my
username and password and of course I
would have to use the ones I hard coded
since we're not retrieving those from a
user table anywhere so that's another
option so that's how the server page
here protects itself which is different
than the home page and then I have one
other server page that right now it's
not protected and it's just called extra
it's an extra page I made however I want
to show the easiest way to apply next
auth to your entire site and then it
will be protected so let's go back to vs
code back in vs code there's one file I
haven't created yet so let's do that we
want to make it inside the source
directory it needs to be at the same
level as the app directory so we're
going to make it inside the source
directory and this is our middleware
file so
middleware.ts now this runs on the edge
and there's some special things about
this file if you haven't worked with
next JS middleware but you only need to
add one line to this file to protect
your entire site with next auth so I'm
just going to paste this in because I
also have a note with it so it says
without a defined matcher which we're
going to talk about in just a second
this one line applies next auth to the
entire project so we can save this and
now next auth is applied to all pages in
our project so let's go back to the
browser quickly and now I'm going to
reload
and what should happen is yes we get the
sign in page automatically we're not
signed in anywhere if I were to go back
to the home page just getting rid of
everything else in the URL there just go
to localhost 3000 it should also want us
to sign in with the GitHub page now
because next auth is applying itself to
every page let's go back to vs code and
we'll also look at how we can just set
this for a few select pages with a
matcher so now underneath this I'm going
to paste in a matcher now I'll press alt
Z so we can read all of this which is
just a link to the reference about a
matcher in the next JS website not the
next auth website but this applies next
auth only to matching routes so this can
be a regex as well and it can exclude so
you could look at way more details on
this next JS page but with this matcher
I've just got an array here that is
applying it to the extra route that
would be our extra page and I'm imagine
we had a dashboard that we wanted to
have authentication for for example so I
just put in slash dashboard as another
example although I don't have a
dashboard page in this application now
if we go back to vs code or actually if
we go back to the browser we should see
a difference here so now I'm going to
reload the home page once again that is
just localhost Port 3000 now we go back
to our you shall not pass Behavior
instead of the behavior that was applied
by putting the auth on the entire site
with middleware so now we have the you
shall not pass here but now if I go to
the extra page it should still be
protected remember earlier it wasn't
when we had that previous Behavior with
the home page so now the middleware has
applied next auth to our extra route
because it's in that matcher now let's
look at the code for the home page and
the server page here because they are
very similar but they're both applying
off in a different way here's the code
for our home page come component now
notice what we're doing we're importing
options that we defined for next auth
inside of that route that we have at the
beginning there when we started working
on the project API slash auth and the
catch-all here's our options then we
also need to import git server session
from next auth Dash next and then I have
a user card component that I just
imported so I could use it in all of the
examples and you could look at that
inside of the components directory if
you want to now inside of this
functional component we await the git
server session and we pass in the
options that gives us our session so
here I'm using kind of logic to
determine what we display I'm not doing
anything else that's just how I'm
protecting the page so if we have a
session it shows the user card and if we
don't have a session it gives us that
message that we were looking at you
shall not pass now in comparison let's
look at the server route here and the
page inside of it it's very much the
same but notice I also import reported
redirect from next navigation so here we
once again await the server session but
if we don't have a session we just
redirect and we use this callback here
inside of the path so API slash auth
sign in where our sign in is and then we
put the Callback value here the param
inside of the URL that is slash server
so after we log in it would take us
right back to the page that we were
wanting to go to and other than that it
displays the user card so we're just not
using the same logic in the page so two
different ways to protect it there if we
look at our extra route you'll see
inside of the code very very simple here
it's not protected at all with this code
it doesn't even get the session but
because we applied the next auth
protection through middleware this page
is protected it's just applied in a
different way back in the browser now
let's talk about the client component
now it's worth noting that I don't use
use any compliant components that need
session data unless it's absolutely
necessary so that's just shipping extra
code to the client when I can easily
request that same data in a server
component and not need to ship all of
that code to the client so for me server
components are usually the bulk of any
page and the client components are
imported for what I would call Islands
of interactivity so the server is
usually the parent and then I'm putting
some client components where needed
inside of it so you don't have to choose
server or client whenever possible you
just make the server component the
parent and import the client component
however what we're going to look at is a
page completely made up of a client
component just as an example here not
something I would usually do so let's
click client here and you shall see it
is also protected let me go ahead and
log in just so we can see some behavior
from these Pages after I'm logged in
and so I just typed in my username and
password that we hard coded inside of
the code sign in with credentials it
says hello Dave and this is a client
page if I refresh because we're using
that cookie that we described in the
docs it's still there and it works just
fine notice it takes just a second here
on the client page it flashes just a
little bit that's a little different
Behavior than you'll get on the server
page because the server page is rendered
and then sent so you don't get that
flash so that's something worth noting
as well but they both work now we can go
to the extra page also that's protected
by middleware we can go back to the home
page and instead of saying you shall not
pass it also says hello Dave and this is
the home page so we're clearly logged in
if we go to sign out then it takes us to
the auto-generated sign out page as well
which you can see is at API auth sign
out you would just change this to sign
in for the auto-generated sign in page
so we can sign out here now I'm going to
go ahead and log in with GitHub and
we'll talk a little bit about what that
does as well you're going to need to
authorize the use if you haven't done
this after you do this the first time
it's going to probably save that and you
won't have to do that again unless you
delete all your data for that site
notice I have a image coming in now my
image from GitHub as well so we'll talk
about that too but let's go back to this
client page and discuss how all of this
is applied and of course now it says
client page so I'm doing the same thing
on this page if we refresh this should
still keep us logged in and it does back
in vs code I'm not showing you the
client component code first what I am
showing you is the layout page that we
have here at the root level along with
the root page for the home that's
because for the client to access that
user data that we get from the session
from next auth we need to go ahead and
create an auth provider and that is a
react context so let's do that first
and then of course after we create it it
gets imported in here to the layout and
we wrap that around everything that we
want to send that context to which is
just like working with any other react
contacts okay so I created a context
directory and inside of there I have a
file called auth provider.tsx notice
it's a client component we say use
client then we import the session
Provider from next Dash auth react then
I went ahead and created the auth
provider now it gets children just like
the layout component does so you can
look at the layout component and see
what it's receiving here is just the
same as that is and then inside of this
we just wrap the children in this
session provider that we imported now if
we go back and look at the layout TX TSX
it might make a little more sense
because look this root layout receives
the exact same thing as far as children
goes then we're just importing the auth
provider here and we're wrapping it
around everything okay now that we've
covered the provider which is only
necessary for the client components that
need the session let's look inside of
this client directory and look at the
page because it's a little different
than the server components there's a
little more work involved as well it
says use client here at the top I put in
a reminder comment that you need that
auth provider to go ahead and get the
session data then there's a use session
hook that we import from next Dash auth
react we're going to go ahead and import
redirect as well so we get redirected to
that login or sign in page with a
callback that says slash client because
then we'd want to come back to this page
so you always make the Callback value
the page that you're on and then inside
of you session here notice we get data
and we're renaming it session we set
required to true and then there's an on
unauth account if I could pronounce it
on on unauthenticated it there we go I
need more coffee this morning and then
we redirect of course if we're not
signed in so that's what all of that
does then if we are signed in well then
we're just passing it once again to that
same user card that we have right there
and note I'm using the same user card
inside of those server Pages like the
home page or the server page I didn't
think I don't think I put it on the
extra page that was just very simple but
I'm using it inside of this client
component too and I've been asked by
some can I use a server component inside
of a client component you wouldn't want
to do that but don't think of this
component which is more of a generic
component in that regard just think of
it as a react component that we're using
wherever we need it because this is
within a client component I don't have
used server or anything at the top of
this user card component it's just a
component that we can reuse just like a
button so we're not really nesting what
you would think of as a server component
inside of a client component and there
shouldn't be a reason to do that either
remember what I was advising use the
server components as the parents
whenever possible and then import the
clients and just use those where needed
however in this example this is
completely a client component because
that's what the whole page is I wouldn't
normally do that but if you need to do
it of course it is possible okay now
that we've looked at this code also and
we know how the entire app works one
other thing to cover and that is just
the details on showing that image or
anything you would get say you log in
with oauth and there's something you
want to display so let's go ahead and
once again look at the user card because
it's displayed in all of these different
examples except extra and we'll see what
I put in that user card it's in the
components directory here we are so
after we get the types of course
correctly I am using the next image up
here because we could get an image from
GitHub and so we're saying hello and
having a username I also commented out
the email you could get the email from
GitHub if you want to get the email so I
just wanted to leave that code in there
in case you want to try it out I am not
using that and then we get the image as
well and it's coming from GitHub so
after you set all of this up and you can
see how I'm displaying it down here in
the section I just defined the greeting
above you could have the email display I
defined the user image above and this is
what we're of course displaying and
here's why I changed out which page type
whether it said it was a client type or
a server type or the home page or
whatever so now that we've looked at all
of that the setting that you need to
remember about bringing in an image
because you could set all of this up and
you could still get an error from next
JS is when you're bringing in images
from an outside Source you need to set
those up in the next JS config and I did
that here under remote patterns for the
image that I would get from GitHub this
isn't so much a next auth thing as it's
something you need to remember when
you're pulling in any image from any of
these other oauth providers or anything
you might be getting from them like I am
getting my image from GitHub back in the
browser one last time let's go to the
home page and it looks the same except
it says home page and of course we do
persist to log in if we refresh I am
really impressed with next auth and how
easy it is to apply especially with the
default settings to your next JS project
and if you'd like to see more and of
course I bet I'm asked about role-based
user authorization for say protected
routes and things like that or other
topics just let me know in the comments
because it's very customizable that
makes next auth awesome because you can
customize it kind of any way you need to
use it so just let me know in the
comments and I'm looking forward to
hearing you and creating more
authentication tutorials in the near
future remember to keep striving for
Progress over Perfection and a little
progress every day will go a very long
way please give this video a like if
it's helped you and thank you for
watching and subscribing you're helping
my channel grow have a great day and
let's write more code together very soon
Browse More Related Video
![](https://i.ytimg.com/vi/ED8uWgE-KeY/hq720.jpg?sqp=-oaymwEmCIAKENAF8quKqQMa8AEB-AH-CYAC0AWKAgwIABABGH8gFSglMA8=&rs=AOn4CLCPsCEnecwkd49t4FWbGoZqVVsjxg)
NestJs REST API with MongoDB #4 - Authentication, Login/Sign Up, assign JWT and more
![](https://i.ytimg.com/vi/ijU6GU3IFgM/hq720.jpg)
Clerk vs Next-Auth.js | It's not that simple...
![](https://i.ytimg.com/vi/P0EGYTb1cBs/hq720.jpg)
Introduction to HTML | An HTML5 Tutorial for Beginners
![](https://i.ytimg.com/vi/x8SlYljxKPY/hq720.jpg)
Serverless Auth with Lucia Auth V3
![](https://i.ytimg.com/vi/wi8kF8UniUI/hq720.jpg)
Learn Next.js Parallel Routes In 16 Minutes
![](https://i.ytimg.com/vi/tqvvZhGrciQ/hq720.jpg)
A deep dive into using Tailscale with Docker
5.0 / 5 (0 votes)