Another great episode mate, getting closer to having a full site made up now with your help! Getting more comfortable with the CRUD side of postgres and next.js. Keen to move on to the next video.
Hello, thanks for the video. I have a question about how to implement multiple custom logins for different user roles, such as clients and administrators. Can you provide some guidance on this?
Thanks! @0xtz_ is right, this can be accomplished with FormData. I'll see what I can do on making a guide for this! Also, keep in mind that you can't save the images on the server if deploying serverless -- you need to use object storage like S3. developer.mozilla.org/en-US/docs/Web/API/FormData
This is a good one. If you want some help setting up Next Auth and prisma (really, with any database), check out ua-cam.com/video/2kgqPvs0j_I/v-deo.html
Hi, I can't my wrap my head around how I can redirect users to dashboard if they are logged in already. I want to do this via a middleware. I tried to use `getServerSession` but that does not work in middleware.
Nevermind, getToken approach was not working for some reason it kept giving me null but 5 mins after this comment it started working. idk what i was doing wrong.
pl share the github repo for better understanding. I want to see the NextAuth part. I've to login from my own external endpoints and create a user session in NextAuth. But I'm not getting the credentials that I'm sending from signIn function of NextAuth.
Hey, source code can be found at the bottom of the blog post: ethanmick.com/build-a-custom-login-page-with-next-js-tailwind-css-and-next-auth/ (Become a member! 😊 )
Great episode. 1) I noticed during the middleware section that my home page was protected as well. What is the way to unprotect it along with register, api and login? 2) Is there a downside to not protecting your api folder? 3) I redirect to signin after registering a user. Once I sign in, the app redirects back to the signin page rather than dashboard. It works normally if I start from home page, then signin page, then dashboard. Any ideas why that happens? #EDIT# My signin page url has a callback to signup. Do I need to use useRouter in my signup page rather than using nextAuth's signIn() functionality when I successfully signed up a user?
I'll add it to the list! React can't do things server side so it ends up being more session management. But there are some good libraries to help with this.
Hi, ethan thanks for making the video! Can you talk about how to save states in the local storage in next 13? Or have you ever made an article about it? Thank you!
Your content is so good, I've been looking for these solutions for the past month, will you also be showing how you can use stripe payments with route handler API vs the pages API? thank you so much for this!
amazing brother! I am about done auth part, so i am gonna pass to opearations like fetching data or crud operations. but just have a quick question to u:) when i get session object, as you know we dont get accessToken property. so do we really need it or not? cause i wanna send request to for instance "/product" root to fetch some products with axios. so do i need send accessToken in header part of axios to check if i am authenticated in api route handler. or we just should write getServerSession() to get session object in api handler file and check authentification?
You shouldn't need the "accessToken" property. When you make the request with Axios to your own domain, it will include the cookies by default. You can use the cookie server side to check the authentication. Assuming valid auth, you can then return "/products" or whatnot. In general, I'd use middleware to protect the routes (including API routes) and then in your handlers you can just trust there is a valid user and use the session data.
@@ethan_mick I mean, if someone try to send request to api from external device or postman to fetch my database. So in this case, what i have to do in my api handlers? u said, i dont need accessToken check, so i can just call const session = getServerSession() function and if(!session) return error u mean?
@@tunaralyarzada Right. You can either use middleware or "const session = await getServerSession()" to get the session. Next-Auth will validate that it is a VALID session. If not, return an error. If it is, then you can lookup the data in your database.
hi i get unhandeled runtime error: Unhandled Runtime Error Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports. Check the render method of `Form`.
Hmmm, perhaps try something like the following: (^\/$|((?!api|_next\/static|_next\/image|favicon.ico).)*) The ^\/$ part of the regex matches the root ("/") exactly. The | (pipe) acts as a logical OR, so either the root path is matched, or any path not starting with "api", "_next/static", "_next/image", or "favicon.ico" is matched.
@@ethan_mick I ran into the same problem of including the root page inside the middleware exclusion pattern. it looks like Next.js doesn't allow doing it this way. throwing error of "`source` does not start with / for route {"source":"(^/$|((?!random|singin|api).)*)"}" Do you have another solution?
Thanks for the videos, really amazing!. One thing tho, after adding the folders to (app) and (auth) and changing the middleware configuration, the login and sign up pages look very different. I created my own form instead of the prebuilt ones you used and now the form shrunk and the image I had is not accessible. Any ideas?
The redirect is handled by the "export { default } from ..." code. Docs: next-auth.js.org/configuration/nextjs#middleware Essentially you're exporting the default function from Next Auth which is the entire middleware. You can see what this function does here: github.com/nextauthjs/next-auth/blob/4f3241f8ddc84958774707de37be4da05ad1de93/packages/next-auth/src/next/middleware.ts#L99-L154 It does what you'd expect: Read the request, check the cookie, get the JWT, and check if it's valid. If it is, continue. If it's not, redirect the user to the signin page.
Man keep going ur videos are so helpful 🔥, thanks 🙏
Dude, thank you so much. Time to start getting deep into the weeds and build some SaaS!!
@@ethan_mick 🙏 I'm planning to start an open source project hhh, but idk what it is exactly 😂
Another great episode mate, getting closer to having a full site made up now with your help! Getting more comfortable with the CRUD side of postgres and next.js. Keen to move on to the next video.
That's awesome! Glad your project is coming along well. Once the CRUD mechanics are familiar you're 90% of the way there :)
Hello, thanks for the video. I have a question about how to implement multiple custom logins for different user roles, such as clients and administrators. Can you provide some guidance on this?
Love this channel. So clear and straight to the point. Good work!
Thank you so much!
user roles like admin, reviewer and user to complete authentication. Tks
Great idea, I'll definitely dig deeper into this. Important stuff for any SaaS
I hope ur, make crud with image upload with next js 13.
BTW great video
I think for the image upload use normal form data, but not sure if that's what u need
Thanks! @0xtz_ is right, this can be accomplished with FormData. I'll see what I can do on making a guide for this! Also, keep in mind that you can't save the images on the server if deploying serverless -- you need to use object storage like S3.
developer.mozilla.org/en-US/docs/Web/API/FormData
I’ll look into this later, because lately I spend few projects on clerk now had to come back to next-auth but things was little bumpy 😊
This is a good one. If you want some help setting up Next Auth and prisma (really, with any database), check out
ua-cam.com/video/2kgqPvs0j_I/v-deo.html
My saviour 🙏
Glad I could help, haha. Cheers!
I have a problem with the middleware setting, It also protect files in /public folder, so I can't access them from the login page, how can I fix this?
Hi, I can't my wrap my head around how I can redirect users to dashboard if they are logged in already. I want to do this via a middleware. I tried to use `getServerSession` but that does not work in middleware.
Nevermind, getToken approach was not working for some reason it kept giving me null but 5 mins after this comment it started working. idk what i was doing wrong.
Sometimes you just need to post a comment and then it starts working. Let me know if you need anything else!
@@ethan_mick😂💪
pl share the github repo for better understanding. I want to see the NextAuth part. I've to login from my own external endpoints and create a user session in NextAuth. But I'm not getting the credentials that I'm sending from signIn function of NextAuth.
Hey, source code can be found at the bottom of the blog post: ethanmick.com/build-a-custom-login-page-with-next-js-tailwind-css-and-next-auth/ (Become a member! 😊 )
how can this work with auth0 provider? ideally id like to show all the options auth0 has.
Great episode.
1) I noticed during the middleware section that my home page was protected as well. What is the way to unprotect it along with register, api and login?
2) Is there a downside to not protecting your api folder?
3) I redirect to signin after registering a user. Once I sign in, the app redirects back to the signin page rather than dashboard. It works normally if I start from home page, then signin page, then dashboard. Any ideas why that happens?
#EDIT# My signin page url has a callback to signup. Do I need to use useRouter in my signup page rather than using nextAuth's signIn() functionality when I successfully signed up a user?
Great explanation sir. Could you please make a tutorial on best way to protect routes in react. Thankyou
I'll add it to the list! React can't do things server side so it ends up being more session management. But there are some good libraries to help with this.
Great content! Just wonder how to not show the password in the URL when using a custom login page?
If you're seeing the URL your form is making a GET request. Make sure it's calling the `signIn` method or making a POST request.
Hi, ethan thanks for making the video! Can you talk about how to save states in the local storage in next 13? Or have you ever made an article about it? Thank you!
Thanks! I can write/video something up on that. It'll be similar to React, so consider something like this: usehooks.com/useLocalStorage/
Your content is so good, I've been looking for these solutions for the past month, will you also be showing how you can use stripe payments with route handler API vs the pages API? thank you so much for this!
Yeah, I think I'm going to build some full featured SaaS apps in the future and walk through all of that.
amazing brother! I am about done auth part, so i am gonna pass to opearations like fetching data or crud operations. but just have a quick question to u:) when i get session object, as you know we dont get accessToken property. so do we really need it or not? cause i wanna send request to for instance "/product" root to fetch some products with axios. so do i need send accessToken in header part of axios to check if i am authenticated in api route handler. or we just should write getServerSession() to get session object in api handler file and check authentification?
You shouldn't need the "accessToken" property. When you make the request with Axios to your own domain, it will include the cookies by default. You can use the cookie server side to check the authentication. Assuming valid auth, you can then return "/products" or whatnot.
In general, I'd use middleware to protect the routes (including API routes) and then in your handlers you can just trust there is a valid user and use the session data.
@@ethan_mick I mean, if someone try to send request to api from external device or postman to fetch my database. So in this case, what i have to do in my api handlers? u said, i dont need accessToken check, so i can just call const session = getServerSession() function and if(!session) return error u mean?
@@tunaralyarzada Right. You can either use middleware or "const session = await getServerSession()" to get the session. Next-Auth will validate that it is a VALID session. If not, return an error. If it is, then you can lookup the data in your database.
@@ethan_mick thank u so much, man!
how to hide navbar when login page with app dir
Try putting the login page in it's own route group (auth) so it can have a different root layout.
hi i get unhandeled runtime error:
Unhandled Runtime Error
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check the render method of `Form`.
Loved the middleware exclusion pattern but what if I would also like to include the root page in that pattern?
Hmmm, perhaps try something like the following:
(^\/$|((?!api|_next\/static|_next\/image|favicon.ico).)*)
The ^\/$ part of the regex matches the root ("/") exactly. The | (pipe) acts as a logical OR, so either the root path is matched, or any path not starting with "api", "_next/static", "_next/image", or "favicon.ico" is matched.
@@ethan_mick I ran into the same problem of including the root page inside the middleware exclusion pattern. it looks like Next.js doesn't allow doing it this way. throwing error of "`source` does not start with / for route {"source":"(^/$|((?!random|singin|api).)*)"}"
Do you have another solution?
Thanks for the videos, really amazing!. One thing tho, after adding the folders to (app) and (auth) and changing the middleware configuration, the login and sign up pages look very different. I created my own form instead of the prebuilt ones you used and now the form shrunk and the image I had is not accessible. Any ideas?
Hmmm, off the top of my head, not totally sure. Are you using Tailwind? Is that configured properly?
how can i add a field userRole in my session or jwt based on my user.role field?
You can see how I do this here: ua-cam.com/video/2kgqPvs0j_I/v-deo.html
Instead of the ID, pass through your userRole.
@@ethan_mick i'll check, thank you ethan!
15:48
How this automatically redirecting into login page when its protected by routes? i mean whats the code here!
The redirect is handled by the "export { default } from ..." code. Docs: next-auth.js.org/configuration/nextjs#middleware
Essentially you're exporting the default function from Next Auth which is the entire middleware. You can see what this function does here: github.com/nextauthjs/next-auth/blob/4f3241f8ddc84958774707de37be4da05ad1de93/packages/next-auth/src/next/middleware.ts#L99-L154
It does what you'd expect: Read the request, check the cookie, get the JWT, and check if it's valid. If it is, continue. If it's not, redirect the user to the signin page.
@@ethan_mick Got it...and thanks man for this amazing tutorial
Usually I watch tutorials at 1.5-2x speed but I regularly need to pause to see what the heck you are typing
Are usestate still a thing in nextjs app directory?
Yes, for sure. It only works in client components, so the question is more "In places where you had to `useState`, is there a better way?"
csrf token??
That’s taken care of by the “signIn” method of Next Auth: next-auth.js.org/getting-started/client#signin
Are you a developer laid off by FAANG? 😅
LOL, no, but I did work at Apple and Microsoft a long time ago.