Next auth credentials - signup & login with email & password (Next JS app router)

  Рет қаралды 56,487

WebDevEducation

WebDevEducation

Күн бұрын

Implement signup and login functionality with next-auth with the Next app router, postgres hosted on vercel, typescript, bcrypt, & SQL.
THE SHADCN UI COURSE IS NOW AVAILABLE - GET IT FOR JUST $12.99 BELOW!
www.udemy.com/course/shadcn-u...
Want the EASIEST way to implement auth?
• EASIEST auth in Next J...
⭐️ webdeveducation.com
💻 next-auth tutorial github repo:
github.com/tomphill/nextauth-tut
🔔 Subscribe if you want more free tutorials like this one! kzbin.info...
Chapters:
0:00 Intro
0:15 Tutorial overview
1:15 Project setup
1:40 Postgres db setup
2:27 Upload to github
3:39 Link postgres db to project
5:44 Install deps & create login & register page
8:25 Setup next-auth
13:12 Setup register endpoint
14:55 Hook up the register form
17:40 Create Form client component
19:07 Fix register endpoint issues
20:49 Create users db table
21:50 Hash password & save new user to db
24:29 Create login form
27:02 Implement authorize logic
32:19 Test login functionality
33:17 Add login / logout links
36:52 Redirect on successful login
38:20 Protect routes if logged in
40:01 Protect routes if logged out
#nextjs #nextauth #nextjstutorial

Пікірлер: 152
@WebDevEducation
@WebDevEducation 8 ай бұрын
Who thinks I should create a next-auth with github login next? 👀😆
@kamaboko1
@kamaboko1 8 ай бұрын
Nah....how about a MySpace login. Lol.
@WebDevEducation
@WebDevEducation 8 ай бұрын
😂
@agneldominique352
@agneldominique352 7 ай бұрын
Facebook login
@dinoDonga
@dinoDonga 7 ай бұрын
next auth is discouraging the use of credentials due to the inherint security risk. Imo who the frick wants to log in with email and password anyways and then confirm - when i can let google / github / discord handle that? If an app does not offer SSO chances are people just dont try them
@WebDevEducation
@WebDevEducation 7 ай бұрын
@@dinoDonga sure, personally I use auth0 for everything because I can't be bothered to set up auth myself. but it doesn't mean knowing how to set it up isn't useful.
@bandekhoda7801
@bandekhoda7801 2 ай бұрын
Finally someone making a simple yet completely efficient auth example; I watched and read 20+ tuts on this matter and all of them either cut corners or implemented the most obscure auth ever... Subscribed!
@osoznayka
@osoznayka 7 ай бұрын
Finally at least something usefull. I don't want to use any "cloud" services. All tutorials anbout nextJS is only about "connecting" a lot of cloud services. In this video I see only postgres via Vercel - very nice. 8 cloudless NextJS points out of 10 Thanks!
@oguzhanercelik
@oguzhanercelik 7 ай бұрын
This is the INSANE video i have ever seen. I was searching this tech stack and implementations for a week but, i couldnt find full of this on the same video. Thank you very very much you'r the best!!
@tsykin
@tsykin 3 ай бұрын
Immediately subscribed! This content is golden! 💎 Thank you so much for showing credentials setup with NextAuth. I really enjoy how well-structured your guides, and you also manage to add a human touch to them. Please, continue will this great content! 👍
@marcinknara4147
@marcinknara4147 14 күн бұрын
Bless your soul for this tutorial, came in clutch when no other documentation or tutorials made any of this clear. Cheers!
@zarkarkas
@zarkarkas Ай бұрын
Thank you for the video! I'm learning NextJs now but it's difficult to find clear tutorials with App Router. This is finally clear on the project structure and flow for NextAuth!👍
@kamikazeslammer
@kamikazeslammer 5 ай бұрын
This is exactly what I was looking for. Thank you for helping with next-auth!
@uchennaofoma4624
@uchennaofoma4624 4 ай бұрын
This video is amazing. Rewatching it for the 4th time
@mattcrane5203
@mattcrane5203 2 ай бұрын
Great Tutorial!, would be keen to an extension to this tut to add google sign in to same login page. Thanks for the hard work putting this tutorial together!
@hakanaki
@hakanaki 6 ай бұрын
Finally, someone with brains. Thanks for this tutorial
@WebDevEducation
@WebDevEducation 6 ай бұрын
Haha you're welcome 🙏
@OlesyaSolovtsova
@OlesyaSolovtsova Ай бұрын
Thank you! amazing tutorial!
@DiksiAhida
@DiksiAhida 7 ай бұрын
This is the tutorial that im searchin for! thank you so much 💖
@WebDevEducation
@WebDevEducation 7 ай бұрын
You're welcome 😊
@JCDZK
@JCDZK 6 ай бұрын
Great video! Does getServerSession on a next page opt you out of ISR? I'm assuming it does but want to be sure
@j7coder
@j7coder 4 ай бұрын
Amazing brother! great content!
@naatr2668
@naatr2668 4 ай бұрын
It's really helpful for me thanks for this video I want to specify
@Evaldo_Souza
@Evaldo_Souza 8 күн бұрын
Thanks man, really thanks.
@Alex.Shalda
@Alex.Shalda 3 ай бұрын
awesome! seamlessly implemented it
@webdeveloper2769
@webdeveloper2769 6 ай бұрын
OMG. what I am looking for, Thank you
@TheBuddilla
@TheBuddilla 8 ай бұрын
This is great, thank you... As a suggestion maybe go a little deeper and show a graphql implementation.
@MrBassBD
@MrBassBD 7 ай бұрын
Intro just 🔥 🔥🔥🔥🔥
@Not_Aran8276
@Not_Aran8276 29 күн бұрын
Programming while in a car turned off is wild. Insane that you didn't get hot while inside the car (still watching 3 mins in)
@WebDevEducation
@WebDevEducation 29 күн бұрын
Haha the car was on, I live in Indonesia so would not have survived without the AC 😆
@Not_Aran8276
@Not_Aran8276 29 күн бұрын
@@WebDevEducation Wait no way, I also live here in Indonesia (East Java, Malang). No wonder why you have that Suzuki Baleno car since that car is pretty popular here, and I guess I didn't notice the white and black license plate coloring format on the back of the car (0:08). Nice, keep up the good work!
@WebDevEducation
@WebDevEducation 28 күн бұрын
Ahhh awesome! Yes I live in Bali :)
@wandie87
@wandie87 7 ай бұрын
Mans here making tutorials from the car. Dedication.
@WebDevEducation
@WebDevEducation 7 ай бұрын
😂
@amanuelmekashaw8738
@amanuelmekashaw8738 4 ай бұрын
Great tutorial but how do we send axios post request if the backend is separate from the front end and the api needs an authorization jwt token
@rezakhani8627
@rezakhani8627 4 ай бұрын
Hello, I am developing the front-end of a project with Next.js, but the back-end of the project is in Django. I want to know if I can use NextAuth for authentication without causing any issues with the Django back-end? Also, could you advise me on whether I should store the token in a cookie or use NextAuth? Please guide me.
@mikhacavin
@mikhacavin 7 ай бұрын
sir, what is the difference between this method and server action for handling login/register?
@armantgoldswain3951
@armantgoldswain3951 4 ай бұрын
60sec, fully agree! They do it because its an easy tutorial and drives views, but lacks real world value imo...
@limhongchuan1031
@limhongchuan1031 8 ай бұрын
Hi from Singapore!
@alemendieta3346
@alemendieta3346 3 ай бұрын
Great tutorial! How can i implement both Credentials and oAuth providers in Auth.js, but with my backend logic in NestJs? That is, store my users in DB, but only NestJs can read/write database?
@JuanMunoz-yt5ke
@JuanMunoz-yt5ke 6 ай бұрын
is it possible to store sessions in database? to be able to keep track of sessions and expire sessions manually
@BartoszJarzyo
@BartoszJarzyo 2 ай бұрын
Hello. I used your guide, logging in/registering with next-auth is a new topic for me and I have a problem. Logging out doesn't work for me, i.e. sign-out with next-auth logs me out, but when I refresh the page in localstorage, a new session immediately appears, so I'm de facto logged in all the time, without the option of permanently logging out. Could you advise me something? I've been looking for documentation, etc., but I haven't yet found a reason why it keeps setting a session at startup, even without logging in.
@interceptorghost1149
@interceptorghost1149 Күн бұрын
"who the freak is logging in to the application using github" killed me 🤣
@jrmayol857
@jrmayol857 7 ай бұрын
Great vid. For the next vid, maybe an online payment for next jd.
@jdooweb
@jdooweb Ай бұрын
Great TUT! I learned a shit-ton from this video! I appreciate you, Man! Quick question, at 37:50, regarding the 'router.refresh'. For some reason, I had to remove it because the page would not push back to the homepage. Was that deprecated? Again...thank you so much!
@aminsoraya4517
@aminsoraya4517 19 күн бұрын
Very useful
@davidkorn5253
@davidkorn5253 7 ай бұрын
intro 10/10
@radutarean9616
@radutarean9616 7 ай бұрын
Hello, thanks for the awesome content! Got one question though, given this setup, what would be the best way to handle making requests to a backend using the jwt-token in the header?
@radutarean9616
@radutarean9616 7 ай бұрын
While the heart is awesome, answers would be even more appreciated. :) No pressure. I am genuinely wondering what the best setup for this is and some resources or something would be much appreciated. Thanks in advance, you deliver awesome content!
@WebDevEducation
@WebDevEducation 7 ай бұрын
The route handlers in Next JS are the backend, and we can grab the session from getServerSession. You should be able to grab any headers you need from the route handler. If you're using a different backend then you'll probably need a different solution than next-auth as its next specific. With that said next-auth team have created authjs.dev/, (which I believe will be used instead of next-auth in the future) which provides more generic auth solutions for other frameworks and backends that may be more suited to your needs.
@JuanDavidPF
@JuanDavidPF 5 ай бұрын
I think you can just add the jwt token your auth provider gives you and use it as a bearer token in all your requests
@jovanjevtic1620
@jovanjevtic1620 7 ай бұрын
Absolutely love the mentality
@user-iz5mo2dq2u
@user-iz5mo2dq2u 2 ай бұрын
how did u manage to start a session using credentials login , i watched the video many time but i didn't find a way to createSession on login using credentials ,please explaine
@mzakysyukur3417
@mzakysyukur3417 3 ай бұрын
when i test register the response show in client side not server side what happen about that?
@Robert-jt9yg
@Robert-jt9yg 7 ай бұрын
Hello thank you for the great tutorial! I have a project with an Express.js backend and a Next.js frontend, does it make sense to use NextAuth in that case? If so how would you do it? Cheers
@WebDevEducation
@WebDevEducation 7 ай бұрын
I would assume it's possible but I've never tried to hook up next auth with express so I'm not sure.
@user-es2ri7lb7h
@user-es2ri7lb7h 7 ай бұрын
잘 배우고 갑니다 next-auth 어려운거 아니었네
@vbtux1
@vbtux1 8 ай бұрын
Very useful post🔥🔥🔥
@WebDevEducation
@WebDevEducation 8 ай бұрын
Glad it was helpful!
@user-lc6cv6sq6j
@user-lc6cv6sq6j 4 ай бұрын
thank you!
@user-kr7bi7ec8j
@user-kr7bi7ec8j 6 ай бұрын
@WebDevEducation At 23:51, won't the code be vulnerable to an SQL injection attack, as you are directly inputting the given values into the database without formatting?
@WebDevEducation
@WebDevEducation 6 ай бұрын
Nope. Check the docs: vercel.com/docs/storage/vercel-postgres/sdk#preventing-sql-injections
@ubucux
@ubucux 4 ай бұрын
I understood everything (even with my broken English).
@aliyevruslan936
@aliyevruslan936 16 күн бұрын
You are awesome
@60Ji5
@60Ji5 3 ай бұрын
Subscribed!
@WebDevEducation
@WebDevEducation 3 ай бұрын
🙏
@saptoarray79
@saptoarray79 3 ай бұрын
Man, you are funny. I like your video. Thanks though, it's helpful.
@pomiusu
@pomiusu 3 ай бұрын
tysm!!!
@facundocarreno8956
@facundocarreno8956 2 ай бұрын
Hello, excellent course, but I have a question. In the documentation, it says that I need to create the path "pages/api/auth/[...nextauth].js," but in the course, you do it like this: "pages/api/auth/[...nextauth]/route.ts." Is it the same, or what differs when doing it this way?
@WebDevEducation
@WebDevEducation 2 ай бұрын
Both ways are correct, it just depends on if you're using the pages directory or app directory. With the app directory it should be app/api/auth/[...nextauth]/route.ts
@facundocarreno8956
@facundocarreno8956 2 ай бұрын
@@WebDevEducation Thank you very much for the response
@facundocarreno8956
@facundocarreno8956 2 ай бұрын
thank for the help @@WebDevEducation
@super..legend
@super..legend Ай бұрын
the middleware part is not working not restricting the dashboard page if logged out !!
@dmsnm
@dmsnm 5 ай бұрын
How can this code be refactored if the backend is handled by a different server?
@Thelukkest
@Thelukkest 7 ай бұрын
Nice video! What‘s the benefit of extracting the forms into their own client components leaving the register and login pages as server components?
@WebDevEducation
@WebDevEducation 7 ай бұрын
You know what? I'm not actually sure why I did it that way 😆 I think the pages as client components would be a better approach in this example.
@HokagePain07
@HokagePain07 6 ай бұрын
It's just a good practise, it allows to load page faster, in this example it's not much, but in page with more elements it will do diffrence
@antares-the-one
@antares-the-one 4 ай бұрын
because of async
@yogyyconst
@yogyyconst 3 ай бұрын
does vercel/postgres work with local postgres?
@dreker337
@dreker337 7 ай бұрын
U r the best
@benyamin4634
@benyamin4634 4 ай бұрын
finallyyyyyyy, somebody that think properly has released a good tutorial😐😐
@Pulguetafx
@Pulguetafx 8 ай бұрын
I have the same code as you at 31:43 but I keep getting an error in the authorize function where it says the type credentials Record is not assignable to a type and it goes like a waterfall of type errors. Does anyone know why this happens? I appreciate the responses
@tharishaperera9345
@tharishaperera9345 7 ай бұрын
I have the same issue and need help
@Holsp
@Holsp 3 ай бұрын
Same problem. I solved it by including if( user == null ) return null; before the const passwordCorrect and deleting a question mark in "user.password" in the compare function.
@idrisolamideganiyu1395
@idrisolamideganiyu1395 6 ай бұрын
What if I want to show the custom error coming from the backend instead of just the credentialsSignin error
@oliverwolfson
@oliverwolfson 8 ай бұрын
thank you.
@ilmifaizan1496
@ilmifaizan1496 6 ай бұрын
How to get rid of the callback url that appears in the browser url. I just want to display /login without /login?callbacksUrl=...
@user-zn9mg4sf2k
@user-zn9mg4sf2k 8 ай бұрын
Nice. Can you do a video on authentication using JWT and next auth using backend nestjs and frontend nextjs?
@WebDevEducation
@WebDevEducation 8 ай бұрын
Unfortunately I've never used nest js so wouldn't know how to
@LOGFILEGDmegusta
@LOGFILEGDmegusta 4 ай бұрын
Perfect
@wjlee7003
@wjlee7003 7 ай бұрын
thanks for the vid. curious, when I look inside session from getServerSession after logging in, it returns an object likeso: { user: { name: undefined, email: undefined, image: undefined } } why?
@WebDevEducation
@WebDevEducation 7 ай бұрын
it might be because I forgot to pass the authOptions to the getServerSession: next-auth.js.org/configuration/nextjs#in-app-router
@cjt9150
@cjt9150 6 ай бұрын
Can you create this video using NextJS14, server actions, prisma with sqlserver - and credentials using email & password
@ajml_hnter
@ajml_hnter 3 ай бұрын
Now how do I store the session in database and use it
@user-gb2io2cb9o
@user-gb2io2cb9o 7 ай бұрын
Thank you!!! How would you add admin approval before users can login?
@Chambrln
@Chambrln 7 ай бұрын
I would suggest adding an additional field in the user database. Upon registering the field defaults to loginApproved=false. You would need an admin page where the account could be approved and then change the loginApproved=true. Modify the SQL query in your authorize function to include a WHERE loginApproved = true.
@user-gb2io2cb9o
@user-gb2io2cb9o 7 ай бұрын
Thank you!@@Chambrln
@navjotsingh2457
@navjotsingh2457 4 ай бұрын
tysm
@WebDevEducation
@WebDevEducation 4 ай бұрын
🙏
@user-jf5zr2wz2z
@user-jf5zr2wz2z 7 ай бұрын
I have issues as I have pages as root folder then inside I have _app.tsx and _document.tsx it is hard for me to manage the session and also use the navbar globally everywhere
@WebDevEducation
@WebDevEducation 7 ай бұрын
This tutorial uses the app router. The setup is slightly different if you're using the pages router. If you check the next auth docs they have the differences in setup outline there 🙏
@user-jf5zr2wz2z
@user-jf5zr2wz2z 7 ай бұрын
can you imagine I had the bugs for 2 weeks 😪 I was trying to use a session when the user was signed in or out but it was hard I found that I had to wrap the session provider in _app.tsx the useSession maybe next time better to give us the link who used different setup @@WebDevEducation
@antares-the-one
@antares-the-one 4 ай бұрын
why do you fetch email and pass to your API at 21:00 without hashing them? wouldn't it be very insecure? just asking because I don't know how it works
@WebDevEducation
@WebDevEducation 4 ай бұрын
hashing client side doesn't really make anything more secure. to make it secure you need to be using https (which you should *always* be using in production), and so you can hash password server side before storing it. in next 13.5 and newer you can run https in development pretty easily as well.
@antares-the-one
@antares-the-one 4 ай бұрын
@@WebDevEducation https makes total sense. Thanks for the guide, it is great showcase of bare minimum that illustrates the principle
@vinodverma-cohunt-tech
@vinodverma-cohunt-tech 7 ай бұрын
thanks
@EtienneDev
@EtienneDev 6 ай бұрын
Your introduction just killed me. 'login with github' 😀.
@WebDevEducation
@WebDevEducation 6 ай бұрын
😂
@tomassabol59
@tomassabol59 7 ай бұрын
10/10
@sowmocoding5740
@sowmocoding5740 4 ай бұрын
best best best
@wadahkodeofficial5389
@wadahkodeofficial5389 6 ай бұрын
Tutorial yang sangat bagus, Tapi saya punya kendala untuk menampilkan pesan error dibrowser jika kata sandi yang dimasukan salah, saya menggunakan prisma di /api/auth/login dan saya sudah membuat Response.json({status: false, message: "Password is wrong."}), bagaimana caranya response tersebut ditampilkan pada browser? Terima kasih.
@WebDevEducation
@WebDevEducation 6 ай бұрын
Makasih kak 😊 Kalo mau tampilkan error bisa pake useState kayak ini (app/login/form.tsx): const router = useRouter(); const [error, setError] = useState(""); const handleSubmit = async (e: FormEvent) => { e.preventDefault(); const formData = new FormData(e.currentTarget); const response = await signIn('credentials', { email: formData.get('email'), password: formData.get('password'), redirect: false, }); console.log({ response }); if (!response?.error) { router.push('/'); router.refresh(); }else{ setError(response.error); } }; return (error ? {error} : Login );
@wadahkodeofficial5389
@wadahkodeofficial5389 6 ай бұрын
@@WebDevEducation Terimakasih, tapi sudah solved kok dari kemarin-kemarin.
@wadahkodeofficial5389
@wadahkodeofficial5389 6 ай бұрын
@@WebDevEducation Oh iya btw cara diatas kita tidak bisa mengatur custom message. async handleSubmit(...) { // Mencari pengguna const res = await fetch("/api/accounts/search?username="+username) const user = await res.json() if (res.ok && !user.found) { setMessage(user.message || "Nama pengguna tidak terdaftar.") } } Ini caraku sih buat mengatasi signIn() yang tidak bisa membuat custom message.
7 ай бұрын
You've got the explanation for client/server components wrong when creating the Registration page. Also, you're not seeing the console log during registration in your terminal because you moved the handler to the client component, so it's logged in the browser.
@WebDevEducation
@WebDevEducation 7 ай бұрын
What did I get wrong?
@WebDevEducation
@WebDevEducation 7 ай бұрын
Also, the console logs I'm referring to the second time "we should see some console logs in our terminal" is the console log from the api endpoint, not the handlesubmit function. You're right tho, when I originally said we should see it in the terminal for handlesubmit, that's not the case and are indeed logged in the browser because it's within the client component.
7 ай бұрын
You're right@@WebDevEducation , I got confused at 16:56 because the error message in the browser states "Client Component", but by default it's a server component in Next.js 13.4
@radekvlk8474
@radekvlk8474 5 ай бұрын
bro learning from a car:DDD
@mohammadutd2323
@mohammadutd2323 3 ай бұрын
Note: using raw SQL code will make vunrable to SQL injection please use an orm or sanitize the user input
@WebDevEducation
@WebDevEducation 3 ай бұрын
Please read the docs. This method isn't vulnerable to sql injection 🙏 vercel.com/docs/storage/vercel-postgres/sdk#preventing-sql-injections
@philipjobran2716
@philipjobran2716 3 ай бұрын
great video.. but the middleware is not working properly
@pomiusu
@pomiusu 3 ай бұрын
it actually works, I were facing issues with middleware just not working but then I tried moving middleware.ts to the root directory and it worked, before that it was at approot/app
@kakun7238
@kakun7238 3 ай бұрын
i love how simple next auth is but the error handling is just so trash
@shoaibshaikh3651
@shoaibshaikh3651 26 күн бұрын
create a video on Auth.js credentials
@WebDevEducation
@WebDevEducation Күн бұрын
Watch this space 👀
@Skyfuck
@Skyfuck 2 ай бұрын
Thank you!
@hktang13
@hktang13 Ай бұрын
I'm getting this error when using getServerSession(): ./node_modules/next-auth/core/init.js:10:14 Module not found: Can't resolve 'crypto' Any idea??
Bro be careful where you drop the ball  #learnfromkhaby  #comedy
00:19
Khaby. Lame
Рет қаралды 47 МЛН
I Built a Shelter House For myself and Сat🐱📦🏠
00:35
TooTool
Рет қаралды 12 МЛН
ПООСТЕРЕГИСЬ🙊🙊🙊
00:39
Chapitosiki
Рет қаралды 8 МЛН
NextAuth Credentials Provider Integration | Next.js App router
7:55
NextJS 13. Аутентификация и приватные роуты
33:59
Михаил Непомнящий
Рет қаралды 41 М.
Next.js App Router Authentication (Sessions, Cookies, JWTs)
11:31
Lee Robinson
Рет қаралды 139 М.
The Ultimate Guide to Next Auth - Everything You Need
1:36:26
Brett Westwood - Software Engineer
Рет қаралды 56 М.
Next Auth Sign in With Credentials
14:51
Full Stack Niraj
Рет қаралды 130 М.
Next.js Authentication With Next-Auth V5 Credential Provider
21:02
tapaScript by Tapas Adhikary
Рет қаралды 2,3 М.