How to use Credentials Authentication in Next.js with NextAuth?

Поделиться
HTML-код
  • Опубликовано: 14 июн 2024
  • Hello, my friends and fellow developers!
    In this video, we cover how you can set up the Credentials Provider by NextAuth properly in your Next.js app! We also use Prisma, Zod, and TypeScript to the mix
    Let me know in the comments below if you want more Next.js content or something else.
    GitHub Repository - github.com/max-programming/au...
    NextAuth Prisma Adapter - authjs.dev/reference/adapter/...
    🔥 Timestamps Start 🔥
    00:00 - Intro
    00:30 - Create Next App
    01:14 - Setup Prisma with SQLite
    03:34 - Install NextAuth + Other Dependencies
    04:06 - User Registration API
    10:13 - NextAuth - Create API Route
    11:36 - NextAuth - Credentials Provider
    16:38 - NextAuth - Callbacks
    19:21 - NextAuth - Pages
    19:43 - NextAuth - Session Strategy
    19:57 - NextAuth - JWT Secret
    20:23 - Working on the frontend
    20:56 - Register Page Functionality
    26:12 - Open Prisma Studio
    26:30 - Display logged-in user on the homepage
    29:28 - Login Page Functionality
    30:40 - Fixing a TypeScript error
    31:22 - Conclusion
    🔥 Timestamps End 🔥
    Other Tutorials:
    ⚛️ React and Material UI Todo App: bit.ly/reactmattodo
    🟨 Other JavaScript videos: bit.ly/jstutorials
    📘 Visual Studio Code videos: bit.ly/vscodevids
    🔋 Build a Battery App in JS: • 🔋 Build a Battery Info...
    Connect 🔗 :
    Twitter: / maxprogramming1
    Facebook: / max-programming-103081...
    Github: github.com/max-programming/
    VS Code Theme used: 😎 Dark Modern
    Suggest, ask doubts in the comments and share these videos to help!
    Thanks for Watching!
    #nextjs #typescript #reactjs

Комментарии • 80

  • @mohammedgazi786
    @mohammedgazi786 Год назад +4

    Have to admit it you explained it very well! 👍

  • @cuti9114
    @cuti9114 Год назад +2

    Thankyou so much plzz keep sharing more videos and projects like this.

  • @MudassirKhan-sx9jy
    @MudassirKhan-sx9jy Год назад +1

    well this is the most clear tutorial about nextAuth on youtube.

    • @MaxProgramming
      @MaxProgramming  Год назад +2

      Really appreciate that buddy! I'm glad this helped you out 😄

  • @jellyfish1772
    @jellyfish1772 11 месяцев назад +1

    He solved every question and problem I ever had with credentials provider

    • @MaxProgramming
      @MaxProgramming  11 месяцев назад

      I'm glad this was useful to you

    • @jellyfish1772
      @jellyfish1772 11 месяцев назад +1

      @@MaxProgramming one request. Couod you make a video that explains how to use multiple providers at the same time

    • @MaxProgramming
      @MaxProgramming  11 месяцев назад +1

      @jellyfish1772 That seems like a great idea. I'll see what I can do

  • @fieryninja2374
    @fieryninja2374 11 месяцев назад +1

    Best one, i did not know that we have to register the user ourselves and no other video talks about it. Thanks

    • @MaxProgramming
      @MaxProgramming  11 месяцев назад

      I'm so happy this video gave you good insight about that 😀

    • @fieryninja2374
      @fieryninja2374 11 месяцев назад +1

      @@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?

    • @MaxProgramming
      @MaxProgramming  11 месяцев назад

      You basically have to set valueAsDate to true in your register function.
      Here's a demo
      codesandbox.io/p/sandbox/gracious-tdd-dych5d

    • @fieryninja2374
      @fieryninja2374 11 месяцев назад +1

      @@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;
      };

    • @MaxProgramming
      @MaxProgramming  11 месяцев назад

      @@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

  • @reynardsimano5691
    @reynardsimano5691 11 месяцев назад +1

    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?

    • @MaxProgramming
      @MaxProgramming  11 месяцев назад

      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

  • @sidharthb3538
    @sidharthb3538 Год назад +5

    Bro your website looks amazing. How did you built it ? What technology used ?

    • @MaxProgramming
      @MaxProgramming  Год назад +2

      My personal site is built with Astro and Tailwind CSS. Really appreciate you liked it 😀

  • @joacopontello585
    @joacopontello585 Год назад +2

    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?

    • @MaxProgramming
      @MaxProgramming  Год назад +1

      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?

    • @joacopontello585
      @joacopontello585 Год назад +1

      @@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!

    • @MaxProgramming
      @MaxProgramming  Год назад +1

      I think mail services are easy to use. Anyways I'll see what I can do 😉

  • @bassam.2023
    @bassam.2023 8 месяцев назад

    Useful video, thanks! ⭐
    What if your backend was a separate Nodejs/Express server? Is it still possible to use NextAuth?

    • @MaxProgramming
      @MaxProgramming  8 месяцев назад

      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

  • @suen-tech
    @suen-tech Год назад +1

    Thank you

  • @devanshdsoni
    @devanshdsoni 11 месяцев назад +2

    Your VS code typing looks so smooth, how did you do that?

    • @MaxProgramming
      @MaxProgramming  11 месяцев назад +2

      There is a setting called "Smooth Caret Animation" that will make your movement look a lot smoother

  • @LarryOklahoma
    @LarryOklahoma 2 месяца назад +1

    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?

    • @MaxProgramming
      @MaxProgramming  2 месяца назад +1

      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

  • @SuperShivammm
    @SuperShivammm Год назад +2

    Well explain tutorial but nobody shows what's updated to session , account tables and how all next-auth tables are connected to each other ?

    • @MaxProgramming
      @MaxProgramming  Год назад

      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

  • @ElevateMonk
    @ElevateMonk Год назад +2

    can i use an external api? that returns a token if login is sucessfull ?

    • @MaxProgramming
      @MaxProgramming  Год назад +1

      Yes but probably not with Next Auth. If you use an external API you might have to handle the cookies yourself

  • @inzolis2551
    @inzolis2551 11 месяцев назад +1

    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.

    • @MaxProgramming
      @MaxProgramming  11 месяцев назад

      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

    • @inzolis2551
      @inzolis2551 11 месяцев назад +1

      @@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.

    • @inzolis2551
      @inzolis2551 11 месяцев назад +1

      @@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.

    • @MaxProgramming
      @MaxProgramming  11 месяцев назад +1

      @@inzolis2551 Inside your tsconfig.json, if you have allowJs option to true, jsx and js files will work just fine with tsx and ts

    • @inzolis2551
      @inzolis2551 11 месяцев назад +1

      @@MaxProgramming Thank you, I already had it set to true

  • @malikbhai2285
    @malikbhai2285 Год назад +1

    Nice

  • @asfnobambu
    @asfnobambu Год назад +1

    Do you address protected routes in this tutorial ?

    • @MaxProgramming
      @MaxProgramming  Год назад

      I showed how to do it with useSession but not with server-side rendering and middlewares

  • @Adrian-mu8gg
    @Adrian-mu8gg 11 месяцев назад +1

    for credential providers how does it handle forget/reset password? did i miss somewhere in the tutorial?

    • @MaxProgramming
      @MaxProgramming  11 месяцев назад

      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/

  • @yasserhy
    @yasserhy Год назад +1

    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

    • @MaxProgramming
      @MaxProgramming  Год назад

      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

    • @yasserhy
      @yasserhy Год назад +1

      @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

    • @MaxProgramming
      @MaxProgramming  Год назад

      @@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: ruclips.net/video/Rrz2q5uCHdE/видео.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

  • @codewithsam7300
    @codewithsam7300 Год назад +1

    Hello.. Is this based on the latest version of next js 13. 4??

    • @MaxProgramming
      @MaxProgramming  Год назад

      Yes. But I'm not using the app directory here.

  • @ghulamilyas6020
    @ghulamilyas6020 Год назад +1

    what if I want to register a user with google provider?

    • @MaxProgramming
      @MaxProgramming  Год назад

      You can easily add the Google Provider with NextAuth. Thier docs show how easily it can be done
      next-auth.js.org/providers/google

  • @tsykin
    @tsykin 3 месяца назад +1

    Can you the same app but this postgres?

    • @MaxProgramming
      @MaxProgramming  3 месяца назад +1

      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

  • @sidharthb3538
    @sidharthb3538 Год назад +3

    server actions used ?

    • @MaxProgramming
      @MaxProgramming  Год назад

      I didn't use the app directory coz the stable build wasn't announced at the time of recording of this video

    • @sidharthb3538
      @sidharthb3538 Год назад +2

      @@MaxProgramming What about Server Actions ? like 'use server' and 'use client' ?

    • @MaxProgramming
      @MaxProgramming  Год назад +2

      Do you want me to explain server actions in another video? I haven't used server actions in this tutorial

    • @sidharthb3538
      @sidharthb3538 Год назад +2

      @@MaxProgramming yes i want a complete NEXT.js 13.4 tutorial. Please. I will be waiting

    • @MaxProgramming
      @MaxProgramming  Год назад +1

      @@sidharthb3538 I'll try for sure. By building a project with it! Thanks for the suggestion.

  • @asimalqasmi7316
    @asimalqasmi7316 Год назад +2

    1⃣
    1st ^_*

  • @camembertsucreausucre3440
    @camembertsucreausucre3440 10 месяцев назад

    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

    • @MaxProgramming
      @MaxProgramming  10 месяцев назад

      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.

  • @ggff2269
    @ggff2269 Год назад +2

    You should have shown the api response first and taught the callbacks part more deeply. A beginner will have trouble here

    • @MaxProgramming
      @MaxProgramming  Год назад

      Thanks for the suggestion. Placing the part for callbacks was time-consuming. I'll keep this in mind next time...

    • @KochharAmandeep
      @KochharAmandeep Год назад +1

      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.

    • @MaxProgramming
      @MaxProgramming  Год назад

      I'll make sure to improve explanation of crucial stuff like this. Thanks for the feedback.

  • @nobody2937
    @nobody2937 10 месяцев назад

    Looks you're NOT using nextjs13 ???

    • @MaxProgramming
      @MaxProgramming  10 месяцев назад +1

      I am using Next.js 13.
      Just without the app router 😉

    • @nobody2937
      @nobody2937 10 месяцев назад +1

      @@MaxProgramming Can you provide a another one using app router? A lot of bugs from my side... particularly: sessionProvider.

    • @MaxProgramming
      @MaxProgramming  9 месяцев назад

      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.

  • @thi_thi_ko
    @thi_thi_ko Год назад +1

    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;

    • @MaxProgramming
      @MaxProgramming  Год назад

      Hey could you send me a friend request on Discord? I might be able to help you there in detail
      usmans.me/discord

    • @thi_thi_ko
      @thi_thi_ko Год назад +1

      I found out the issue.. I called authorize under credentials which I moved outside and it started working..

    • @MaxProgramming
      @MaxProgramming  Год назад

      @@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