@@MaxProgrammingI have an input field of type date from the UI library shadcn. They also have form components that use react hook form. I am using their form components as well as their input, checkbox, and button fields. The issue is react hook form is trying to make the value of the input type Date because of the Zoe schema I set up. It is telling me that the input value cannot have type date and must have type string, but Zoe and my database all need type date. How can I fix this?
)} /> The yearMonthDay function: const useYearMonthDay = (date: Date) => { // because of undefined errors if (date === undefined) return ""; // I get the year, month, and day and put it in a string const year = date.toLocaleDateString("default", { year: "numeric" }); const month = date.toLocaleDateString("default", { month: "2-digit" }); const day = date.toLocaleDateString("default", { day: "2-digit" }); return year + "-" + month + "-" + day; };
@@fieryninja2374 Looks like a fine solution but if you can remove all the boilerplate code like adding regex patterns by simply using valueAsDate, I'd go with that then
what is the point of putting something like this in the auth.ts file credentials: { username: { label: "Username", type: "text", placeholder: "jsmith" }, password: { label: "Password", type: "password" }, }, is this a default login page that nextauth is creating for us?
The credentials object is the one that allows you to define the form fields. Like in this case it's username and password. Also it helps inferring types in the authorize function Similarly you can put email and password if you want those. Passing these also automatically puts input fields on the default login page by next auth
for your register.tsx page in your app/register directory how are you able to pass the event handler "" without using client component props, 'use client' . I am assuming because of this issue i cannot register an account to my prisma db.
In this demo I am not using the app directory. But if you use the the app directory with this form, you will have to put it inside a client component for it to work. Or else you can use server actions but they're in alpha now so don't use them in production
@@MaxProgramming I have another question, sorry to bother, do tsx files and jsx files work together, e.g my api files are .tsx and my app pages are that of jsx type.
Thanks 🙂! Well as far as I have seen, the account and session tables don't get updated when we use Credentials provider. Because (as in the video) I only updated the users table through prisma. NextAuth doesn't change anything in the database when it comes to the credentials provider, it comes down to the Developer itself. The authorize function can still be made better using the other tables maybe somehow. But I still haven't seen any *perfect* representation of the Credentials provider
A very good tutorial video for a beginner like me! Quick question: Would this work when I want to use MySQL as my database instead of SQLite? and If I wanted to add more fields to be inserted(such as real name), I just need to insert more variables under username and password correct?
Yes it will work as intended. And about adding more fields you can do the same as username and password. But you will have to manually handle those after registration
I want to plzzzz ask u a question. How can I use NextAuth with Google to authenticate the user and then pass the session to NestJS project to authenticate the user there also so I can use the guards' features in NesfJS. There are no guides or tutorials about this at all
I haven't done anything like this but I don't think it's possible either. Even I wanted to do something like this recently but couldn't. If you use NextAuth, you use Next.js's serverless endpoints, and Nest will be it's own separate server. So you need to set up auth in Nest. But what you can do is have your API on Nest, then you communicate with that on the Next API routes, and you hit the /api/whatever from the frontend. But I will not recommend this approach as this is way too much work and will impact performance
@Max Programming thank you taking the time to reply. I don't mind using NextJS for everything including the API provider as well. But I read somewhere that it is not as powerful as NestJS. Is thst true? Can I build a large social media app based on NextJS? I am a beginner and I am working on something that might be huge eventually
@@yasserhy You can definitely build large scale apps with only the Next API router. But yes it's true that it's not as powerful as Nest because it's not a STATEFUL backend. Here's a video I'll recommend you to watch and this will make it more clear what to use in what scenario: ua-cam.com/video/Rrz2q5uCHdE/v-deo.html Although you can make good use of Next.js through things like tRPC, zod etc. But if are someone who likes to keep both front and back different, then Next + Nest without NextAuth will be the option for you
In this video I didn't send an email to the user so without any sort of email verification it's almost impossible to do a forgot password. You'd have to manually add that functionality. With the Credentials Provider, Next Auth only provides you the "Authentication" part. In simple words, only the log in functionality Things like sign up and reset password have to be done manually. This article might be helpful to reset password; www.smashingmagazine.com/2022/08/implementing-reset-password-feature-nextjs-dynamic-routes/
Great video! I think this authentication method with next-auth credentials or Clerk are in my opinion a big solution to the authentication problem, thanks for the tutorial!. PD: Did you tried Clerk? Because i would like to know if there is a way to handle the verification of the email in next-auth. Clerk has this option, but next-auth does?
Clerk is definitely amazing! I love it! Also to do email verification in Next Auth you kinda have to handle it manually. Would you like to see a video on that?
@@MaxProgramming I think that if you can handle it easily not depending to many external things like complicated mail services or, things i don't really know of the email verificacation. I would like to see how to do it, thanks!
Instead of using sqlite like I did, you can also use Postgres with Prisma or any other ORM like TypeORM for example. All integrations are listed on the Next Auth docs
Yes I have plans to do so. Stuck in college these days. Btw for SessionProvider you need to make a client component where you can put SessionProvider and which you can use inside your layout.tsx file.
what about the db ? we instantiate prisma client in each page render and everithing its fine ? 😂 thats ridiculous please be serious put at least singleton idk
Your idea about the singleton is fine. However this is just a demo, and this tutorial was about Next Auth, not Prisma. Plus, the prisma client isn't instantiated on each page render but only when the /api/auth/* or /api/register API Route is hit (and it gets disposed once the api route ends) So in this demo it doesn't make any difference of using a singleton. My focus was solely on how we can use the credentials provider with nextauth not how we can use prisma with nextauth.
This is the point where i felt, he is just writting code because he knows what is happening. For those like me doesn't know why he is placing the code in callbacks in next auth. Need to improve on this point.
@@thi_thi_ko ahh that was a filthy mistake lol. Anyways, my suggestion would be to start using TypeScript as you will instantly find out about these mistakes
well this is the most clear tutorial about nextAuth on youtube.
Really appreciate that buddy! I'm glad this helped you out 😄
He solved every question and problem I ever had with credentials provider
I'm glad this was useful to you
@@MaxProgramming one request. Couod you make a video that explains how to use multiple providers at the same time
@jellyfish1772 That seems like a great idea. I'll see what I can do
Best one, i did not know that we have to register the user ourselves and no other video talks about it. Thanks
I'm so happy this video gave you good insight about that 😀
@@MaxProgrammingI have an input field of type date from the UI library shadcn. They also have form components that use react hook form. I am using their form components as well as their input, checkbox, and button fields. The issue is react hook form is trying to make the value of the input type Date because of the Zoe schema I set up. It is telling me that the input value cannot have type date and must have type string, but Zoe and my database all need type date. How can I fix this?
You basically have to set valueAsDate to true in your register function.
Here's a demo
codesandbox.io/p/sandbox/gracious-tdd-dych5d
@@MaxProgramming I found my solution:
(
Birthday
{
// css
if (
e.target.value === null ||
e.target.value === undefined ||
!e.target.value
)
setIsDateFocused(false);
else setIsDateFocused(true);
// getting values
const dateStringArray: any = e.target.value.split("-");
field.onChange(
new Date(
Number(dateStringArray[0]),
Number(dateStringArray[1]) - 1,
Number(dateStringArray[2])
)
);
}}
/>
)}
/>
The yearMonthDay function:
const useYearMonthDay = (date: Date) => {
// because of undefined errors
if (date === undefined) return "";
// I get the year, month, and day and put it in a string
const year = date.toLocaleDateString("default", { year: "numeric" });
const month = date.toLocaleDateString("default", {
month: "2-digit"
});
const day = date.toLocaleDateString("default", { day: "2-digit" });
return year + "-" + month + "-" + day;
};
@@fieryninja2374 Looks like a fine solution but if you can remove all the boilerplate code like adding regex patterns by simply using valueAsDate, I'd go with that then
Have to admit it you explained it very well! 👍
Thank you 😄
Thankyou so much plzz keep sharing more videos and projects like this.
I'm glad this helped 🙂
Bro your website looks amazing. How did you built it ? What technology used ?
My personal site is built with Astro and Tailwind CSS. Really appreciate you liked it 😀
what is the point of putting something like this in the auth.ts file
credentials: {
username: { label: "Username", type: "text", placeholder: "jsmith" },
password: { label: "Password", type: "password" },
},
is this a default login page that nextauth is creating for us?
The credentials object is the one that allows you to define the form fields. Like in this case it's username and password. Also it helps inferring types in the authorize function
Similarly you can put email and password if you want those.
Passing these also automatically puts input fields on the default login page by next auth
for your register.tsx page in your app/register directory how are you able to pass the event handler "" without using client component props, 'use client' . I am assuming because of this issue i cannot register an account to my prisma db.
In this demo I am not using the app directory. But if you use the the app directory with this form, you will have to put it inside a client component for it to work.
Or else you can use server actions but they're in alpha now so don't use them in production
@@MaxProgramming Thank you for your reply, if it works with client then i need to check why account data is not being saved in the prisma db.
@@MaxProgramming I have another question, sorry to bother, do tsx files and jsx files work together, e.g my api files are .tsx and my app pages are that of jsx type.
@@inzolis2551 Inside your tsconfig.json, if you have allowJs option to true, jsx and js files will work just fine with tsx and ts
@@MaxProgramming Thank you, I already had it set to true
Useful video, thanks! ⭐
What if your backend was a separate Nodejs/Express server? Is it still possible to use NextAuth?
As far as I know then you can't use NextAuth because it's only for Next.js server less api routes. Then you need to handle auth manually
Your VS code typing looks so smooth, how did you do that?
There is a setting called "Smooth Caret Animation" that will make your movement look a lot smoother
Well explain tutorial but nobody shows what's updated to session , account tables and how all next-auth tables are connected to each other ?
Thanks 🙂! Well as far as I have seen, the account and session tables don't get updated when we use Credentials provider. Because (as in the video) I only updated the users table through prisma.
NextAuth doesn't change anything in the database when it comes to the credentials provider, it comes down to the Developer itself.
The authorize function can still be made better using the other tables maybe somehow. But I still haven't seen any *perfect* representation of the Credentials provider
A very good tutorial video for a beginner like me! Quick question: Would this work when I want to use MySQL as my database instead of SQLite? and If I wanted to add more fields to be inserted(such as real name), I just need to insert more variables under username and password correct?
Yes it will work as intended. And about adding more fields you can do the same as username and password. But you will have to manually handle those after registration
I want to plzzzz ask u a question. How can I use NextAuth with Google to authenticate the user and then pass the session to NestJS project to authenticate the user there also so I can use the guards' features in NesfJS. There are no guides or tutorials about this at all
I haven't done anything like this but I don't think it's possible either. Even I wanted to do something like this recently but couldn't.
If you use NextAuth, you use Next.js's serverless endpoints, and Nest will be it's own separate server. So you need to set up auth in Nest.
But what you can do is have your API on Nest, then you communicate with that on the Next API routes, and you hit the /api/whatever from the frontend. But I will not recommend this approach as this is way too much work and will impact performance
@Max Programming thank you taking the time to reply. I don't mind using NextJS for everything including the API provider as well. But I read somewhere that it is not as powerful as NestJS. Is thst true? Can I build a large social media app based on NextJS? I am a beginner and I am working on something that might be huge eventually
@@yasserhy You can definitely build large scale apps with only the Next API router. But yes it's true that it's not as powerful as Nest because it's not a STATEFUL backend.
Here's a video I'll recommend you to watch and this will make it more clear what to use in what scenario: ua-cam.com/video/Rrz2q5uCHdE/v-deo.html
Although you can make good use of Next.js through things like tRPC, zod etc. But if are someone who likes to keep both front and back different, then Next + Nest without NextAuth will be the option for you
Do you address protected routes in this tutorial ?
I showed how to do it with useSession but not with server-side rendering and middlewares
for credential providers how does it handle forget/reset password? did i miss somewhere in the tutorial?
In this video I didn't send an email to the user so without any sort of email verification it's almost impossible to do a forgot password.
You'd have to manually add that functionality. With the Credentials Provider, Next Auth only provides you the "Authentication" part. In simple words, only the log in functionality
Things like sign up and reset password have to be done manually.
This article might be helpful to reset password; www.smashingmagazine.com/2022/08/implementing-reset-password-feature-nextjs-dynamic-routes/
Hello.. Is this based on the latest version of next js 13. 4??
Yes. But I'm not using the app directory here.
can i use an external api? that returns a token if login is sucessfull ?
Yes but probably not with Next Auth. If you use an external API you might have to handle the cookies yourself
Great video! I think this authentication method with next-auth credentials or Clerk are in my opinion a big solution to the authentication problem, thanks for the tutorial!.
PD: Did you tried Clerk? Because i would like to know if there is a way to handle the verification of the email in next-auth. Clerk has this option, but next-auth does?
Clerk is definitely amazing! I love it!
Also to do email verification in Next Auth you kinda have to handle it manually. Would you like to see a video on that?
@@MaxProgramming I think that if you can handle it easily not depending to many external things like complicated mail services or, things i don't really know of the email verificacation. I would like to see how to do it, thanks!
I think mail services are easy to use. Anyways I'll see what I can do 😉
Nice
Thank you
Can you the same app but this postgres?
Instead of using sqlite like I did, you can also use Postgres with Prisma or any other ORM like TypeORM for example.
All integrations are listed on the Next Auth docs
what if I want to register a user with google provider?
You can easily add the Google Provider with NextAuth. Thier docs show how easily it can be done
next-auth.js.org/providers/google
server actions used ?
I didn't use the app directory coz the stable build wasn't announced at the time of recording of this video
@@MaxProgramming What about Server Actions ? like 'use server' and 'use client' ?
Do you want me to explain server actions in another video? I haven't used server actions in this tutorial
@@MaxProgramming yes i want a complete NEXT.js 13.4 tutorial. Please. I will be waiting
@@sidharthb3538 I'll try for sure. By building a project with it! Thanks for the suggestion.
How about [auth][error] CredentialsSignin: ???
There are several reasons this error occurs, but it's hard to find out what by just seeing [auth][error] CredentialsSignin
Looks you're NOT using nextjs13 ???
I am using Next.js 13.
Just without the app router 😉
@@MaxProgramming Can you provide a another one using app router? A lot of bugs from my side... particularly: sessionProvider.
Yes I have plans to do so. Stuck in college these days.
Btw for SessionProvider you need to make a client component where you can put SessionProvider and which you can use inside your layout.tsx file.
what about the db ? we instantiate prisma client in each page render and everithing its fine ? 😂 thats ridiculous please be serious put at least singleton idk
Your idea about the singleton is fine. However this is just a demo, and this tutorial was about Next Auth, not Prisma.
Plus, the prisma client isn't instantiated on each page render but only when the /api/auth/* or /api/register API Route is hit (and it gets disposed once the api route ends) So in this demo it doesn't make any difference of using a singleton.
My focus was solely on how we can use the credentials provider with nextauth not how we can use prisma with nextauth.
You should have shown the api response first and taught the callbacks part more deeply. A beginner will have trouble here
Thanks for the suggestion. Placing the part for callbacks was time-consuming. I'll keep this in mind next time...
This is the point where i felt, he is just writting code because he knows what is happening. For those like me doesn't know why he is placing the code in callbacks in next auth. Need to improve on this point.
I'll make sure to improve explanation of crucial stuff like this. Thanks for the feedback.
1⃣
1st ^_*
I tried implementing the code. Register form data is getting saved in DB but when I try the same credentials in login page I'm getting 401 error from credentials in the network tab. I'm using Next 13.4.2. Below is my code (I'm sorry pasting code in the comments..)
// filename: api/auth/[...nextauth].js
import NextAuth from "next-auth/next";
import prisma from "../../../utiils/prisma";
import bcrypt from "bcryptjs";
import { z } from "zod";
import CredentialsProvider from "next-auth/providers/credentials";
import { PrismaAdapter } from "@auth/prisma-adapter";
const loginUserSchema = z.object({
username: z.string().regex(/^[a-z0-9-_]{3,15}$/g, "Invalid Username"),
password: z.string().min(5, "Password should have atleast 5 characters"),
});
const authOptions = {
adapter: PrismaAdapter(prisma),
providers: [
CredentialsProvider({
credentials: {
username: {
type: "text",
placeholder: "username",
},
password: {
type: "password",
placeholder: "some password",
},
async authorize(credentials, req) {
console.log("credentials", credentials);
const { username, password } = loginUserSchema.parse(credentials);
const user = await prisma.user.findUnique({
where: { username },
});
const isvalidPassword = await bcrypt.compare(password, user.password);
if (!user || !isvalidPassword) return null;
return user;
},
},
}),
],
callbacks: {
session({ session, token }) {
session.user.id = token.id;
session.user.username = token.username;
return session;
},
jwt({ token, account, user }) {
if (account) {
token.accessToken = account.access_token;
token.id = user.id;
token.username = user.username;
console.log({ user });
}
return token;
},
},
pages: {
signIn: "/login",
},
session: {
strategy: "jwt",
},
secret: process.env.JWT_SECRET,
};
export default NextAuth(authOptions);
// login.js
"use client";
import Bg from "@/assets/images/bg.jpg";
import Image from "next/image";
import Link from "next/link";
import { signIn } from "next-auth/react";
const LoginPage = () => {
const handleSubmit = async (e) => {
e.preventDefault();
const form = new FormData(e.target);
const res = await signIn("credentials", {
username: form.get("username"),
password: form.get("password"),
callbackUrl: "/",
});
if (res?.error) console.log(error);
// console.log(form);
};
return (
LOGIN
Username
Password
Not a registered user?{" "}
Register Here
);
};
export default LoginPage;
Hey could you send me a friend request on Discord? I might be able to help you there in detail
usmans.me/discord
I found out the issue.. I called authorize under credentials which I moved outside and it started working..
@@thi_thi_ko ahh that was a filthy mistake lol. Anyways, my suggestion would be to start using TypeScript as you will instantly find out about these mistakes