Protect your NextJs 13 app using Next-Auth

Поділитися
Вставка
  • Опубліковано 22 жов 2024

КОМЕНТАРІ • 274

  • @user-bf7td1gn3t
    @user-bf7td1gn3t Рік тому +8

    This was insanely helpful I'm always lost when there are not much documentation about new things so this video saved from a lot of headache.

    • @hamedbahram
      @hamedbahram  Рік тому +2

      Very glad to hear that. Thanks for leaving your feedback.

  • @n3uron_bloom938
    @n3uron_bloom938 Рік тому +1

    Thank you SO MUCH for this video. a very clear explanation of how to get the session data using the NextJS App Router. As someone who started learning NextJS in the last 2 weeks I felt the NextAuth documentation was unclear to how to best utilize the App Router with Next Auth. You cleared up all of my questions! Thanks!

    • @hamedbahram
      @hamedbahram  Рік тому +1

      I'm glad I was able to help. Thank you for leaving a comment, I appreciate it.

  • @John-ez6nh
    @John-ez6nh Рік тому +17

    As someone fairly new to React and Backend Development, navigating NextJS and NextAuth has been kind of a nightmare. (Do I use pages or the app router, what happened to _document, where do my session providers go, etc...) Changes are happening so frequently, and they seem so fundamental. This video was very helpful. Thank you!

    • @hamedbahram
      @hamedbahram  Рік тому +2

      My pleasure John! I'm glad you found the video helpful. Thanks for tuning in!

  • @reddpy
    @reddpy Рік тому +7

    You're really great at explaining things in a very slow and digestible way! Please keep it up, this was very much needed!

    • @hamedbahram
      @hamedbahram  Рік тому +3

      Thank you for you comment, I appreciate it. I'm glad you find the content helpful.

  • @coxjack
    @coxjack 10 місяців тому +1

    Thanks so much for the clear walk through of this process. I only wish that I had watched this video first, it would have saved me a day of messing around with another tutorial that was wrong and didn't lead to working code.

    • @hamedbahram
      @hamedbahram  10 місяців тому

      Glad it was helpful! And welcome to the channel :)

  • @run4ever102
    @run4ever102 Рік тому +1

    Subbed~ ! Configuring this for work, and was running into so much conflicting documentation, just needed to get a quick demo up and running for testing purposes - You're the man ! Checking out your route handler video next :)

    • @hamedbahram
      @hamedbahram  Рік тому

      Thanks for the sub! Glad it was helpful. Appreciate the comment.

  • @andreanwinz8603
    @andreanwinz8603 Рік тому +3

    thanks for the explanation, and actually I feel bad because I was looking for trouble when following someone else's next project tutorial (stuck because of a different version of nextAuth) and I actually found what I was looking for in this video,, thank you for your efforts I really appreciate it,, may good things always be with you,, after finishing this 11 hour tutorial, I promise to see another video from you,, thanks again😁

    • @hamedbahram
      @hamedbahram  Рік тому

      You are welcome! Glad you found the video helpful!

  • @John-eq5cd
    @John-eq5cd 8 місяців тому +1

    Very good, thank you
    With many web dev videos I have to reduce the speed to 75% so I have time to understand the concepts, but not with yours. They are well paced for those who are trying to learn.

  • @IMegz
    @IMegz 11 місяців тому +1

    That is exactly what I wanted + more. Perfect, clean, and easy explanation.

  • @friendly__drone9352
    @friendly__drone9352 Рік тому +7

    Someone (more eloquent than me) should make a PR to update the documentation for NextAuth to explain where to put SessionProvider because it's not obvious for a lot of beginners.

    • @hamedbahram
      @hamedbahram  Рік тому +3

      I agree, NextAuth documentation needs some help. Did watching the video help? Is there anything else you'd wish to see?

    • @friendly__drone9352
      @friendly__drone9352 Рік тому +2

      @@hamedbahram I keep coming back to this video to reference the SessionProvider section. Thanks again! The video is so helpful

    • @hamedbahram
      @hamedbahram  Рік тому

      @@friendly__drone9352 Glad to hear that!

  • @mahmodissa4169
    @mahmodissa4169 Рік тому

    Man you have no idea how much time been spending to a content like this one!!! Thank you so much!!! Owe you a soda!!! Shokran!!

    • @hamedbahram
      @hamedbahram  Рік тому

      I'm so glad to hear that Mahmod! I appreciate your comment.

  • @semajroyam3725
    @semajroyam3725 Рік тому +1

    this is what I'm looking for, i need this for our capstone project, thank you!

  • @w3mw
    @w3mw Рік тому +1

    Amazing video, you are one of my favorite content creator out there! Good work.
    One question. Do you or do you already have a video about next js 13 next auth with role authentication? Like admins, moderator and users?

    • @hamedbahram
      @hamedbahram  Рік тому +1

      Glad to hear that! I don't have a role based authentication video yet, but I'll make one soon :)

  • @faizanjan102
    @faizanjan102 Рік тому +1

    I can't even begin to explain how helpful this video was after banging my head for hours to find the answer to a bunch of questions from documentation and stackoverflow. Keep up the good work Hamed 👍
    Just 1 question though. You have not exactly explained how the signing in in is implemented...

    • @hamedbahram
      @hamedbahram  Рік тому

      Glad to hear that! Sign in flow is pretty straightforward, you just call the sign in method and pass the ID of the provider you want to use. You can look at my code for the sign in page and see how I've implemented it.

  • @mryoung205
    @mryoung205 Рік тому +1

    best next auth video for app router

  • @timeforrice
    @timeforrice Рік тому

    I like how he explained those topics. Hope to see an extended version of this or a full stack of an app.

    • @hamedbahram
      @hamedbahram  Рік тому

      Hey Jackson, glad you liked the videos, thanks for tuning in!

    • @MrMaraxli
      @MrMaraxli Рік тому

      Yes please it will be great to see everything step by step

    • @hamedbahram
      @hamedbahram  Рік тому

      @@MrMaraxli Absolutely Tony!

  • @tarsisiushp
    @tarsisiushp Рік тому +1

    Thanks for sharing, this is really what i need for project that im working on.

  • @27sosite73
    @27sosite73 Рік тому +1

    great!
    sounds super!
    high quality
    nice!
    subscribed

  • @web-constcode6252
    @web-constcode6252 Рік тому +1

    Thanks, it was very useful
    Design of auth-form is standart for AuthNext? Or you create?

    • @hamedbahram
      @hamedbahram  Рік тому

      Glad you find the video useful. The `next-auth` package provides standard built-in pages, but the sign-in page in this example is a custom page I created. You can reference the source code in the `app/signin/page.jsx` to see the component rendering this page.

  • @iCanfixit_
    @iCanfixit_ 4 місяці тому +1

    Thank you very much, this was very helpful

    • @hamedbahram
      @hamedbahram  4 місяці тому +1

      My pleasure! Glad it helped!

  • @irtazahussain8118
    @irtazahussain8118 Рік тому +1

    Great Hamed, Nice to see that you are focusing on the main aspect of any application and that's is absolutely strong authentication. Can you please do a video where we can authenticate all the client pages, server pages and apis routes by just one file/point. Like we have Login, signup, otp, forgot page which should not required any authentication and we consider them in (unauthedpagegroup) and we add all those pages which required auth is in (authedpages) group and they should be authenticate otherwise redirect them to login.

    • @hamedbahram
      @hamedbahram  Рік тому +1

      Thanks for tuning in Irtaza. That can be done with using route groups where you would require auth at the root layout level to effect all the sub-pages. You can also use a middleware, define your protected pages, and intercept the request and redirect if not logged in. That'll be an interesting topic for a future video.

  • @theweekendcoder
    @theweekendcoder Рік тому +1

    Great explanation. What if we have 5+ client or server side pages. Do I have to write useSession in each of those files or creating a wrapper with the useSession logic inside would handle that as well.

    • @hamedbahram
      @hamedbahram  Рік тому +1

      I think you can use the `useSession` hook directly. An alternative is to use the middleware option where you can define what pages would be protected pages, so you don't have to use the `useSession` hook or the `getServerSession` on each page.

  • @weeseenman2248
    @weeseenman2248 8 місяців тому +1

    Thanks for your very useful explanation. But I have just a question. Can you explain your photo which at 15:32 ? :)

    • @hamedbahram
      @hamedbahram  8 місяців тому

      😂 It think that's because of the layout `fill` property and how I'm styling the image.

  • @amirmp3715
    @amirmp3715 9 місяців тому +1

    Your content is stellar, and I admire your thorough explanations. I'm eager for a video on using Next.js exclusively as the front-end, particularly with App Router. My React app has a backend with Express.js and JWT authentication. I'd love guidance on migrating to Next.js while smoothly handling JWT authentication for both server and client components. I've scoured the internet without finding a suitable guide, and your expertise would be a game-changer. Thanks for considering this request!

    • @hamedbahram
      @hamedbahram  9 місяців тому

      My pleasure! Glad you find the content helpful. As far as using your own backend with NextJs, I have an upcoming video covering that, it's not necessarily migrating from a React app, but more so how you'd go about using your own server when using NextJs. So stay tuned and I think that'll help you.

    • @amirmp3715
      @amirmp3715 9 місяців тому +1

      ​@@hamedbahram Thank you so much for the quick and thoughtful response! I'm genuinely excited about your upcoming video on integrating a custom backend with Next.js. Your willingness to address this specific scenario is truly appreciated, and I can't wait to gain insights from your expertise. Your dedication to providing valuable content is evident, and I'll definitely be staying tuned for the release. Keep up the fantastic work!

    • @hamedbahram
      @hamedbahram  9 місяців тому

      @@amirmp3715 Absolutely!

  • @lukaszsl
    @lukaszsl Рік тому +1

    Hi Hamed,
    Great video and great channel ! It helps me a lot in understanding next.js 13 :)
    Just for info: For me ClientProtectPage works ( redirect to /protected/client) also without the below method:
    onUnauthenticated() {
    redirect('/signin?callbackUrl=/protected/client')
    }

    • @hamedbahram
      @hamedbahram  Рік тому

      Hey! I'm glad you found the channel helpful. That's interesting, do you have the same setup as mine?

  • @minhtimus
    @minhtimus Рік тому +1

    Great vid! One question, once the user is logged in, how can I prevent them from accessing the /signin route?

    • @hamedbahram
      @hamedbahram  Рік тому

      You can check the session on the `/signin` page and should them a `SignOut` form or redirect them to home page.

  • @darawan_omar
    @darawan_omar Рік тому +1

    That is really helpful for me thank you a lot teacher you are the best ❤❤

  • @richardjamesbunker
    @richardjamesbunker Рік тому

    Instant subscribe. This video I was so clear and helped me understand exactly what I needed. ❤

    • @hamedbahram
      @hamedbahram  Рік тому

      Glad it was helpful! I appreciate your comment.

  • @TarekHolanda
    @TarekHolanda Рік тому

    Extremely helpful! Thank you for the great video!

    • @hamedbahram
      @hamedbahram  Рік тому

      Thanks Tarek, I'm glad you found it helpful.

  • @sahandsanaei3086
    @sahandsanaei3086 Рік тому

    best as always. thanks for keeping up the high quality of content.

  • @NIKHILVERMA-hm9nl
    @NIKHILVERMA-hm9nl Рік тому +3

    That's really helpful i was searching for the same but since nextjs is continuously updating getting the updated content is a pretty hectic task obviously apart from the DOCS. While i was searching there was the concept of MIDDLEWARES also.
    It will be quite helpful if you can make a video on that also.
    And BTW The way you explain is really awesome. Thank you

    • @hamedbahram
      @hamedbahram  Рік тому

      Thanks for the feedback Nikhil, and I'm glad you found the video useful.

  • @karimla9338
    @karimla9338 Рік тому +3

    I think you have a bug in the Provider component. That's why the screen flashes the unauthenticated view first when you're authenticated. Since a session prop wasn't passed to SessionProvider. It's only picked on the client thus the view flashes. This is how I fixed that in the RootLayout:
    ```
    export default async function RootLayout({ children }: PropsWithChildren) {
    let session: Session | null = null;
    try {
    session = await getServerSession(authOptions);
    } catch (error) {
    session = null;
    console.log('failed to get session', error);
    }
    return (


    {children}

    );
    }
    ```
    PS: thanks for the great content.

    • @hamedbahram
      @hamedbahram  Рік тому +1

      Thanks for the feedback Karim. That's right you can fetch the session server-side and provide it to the session context provider to avoid fetching it on the client-side.

  • @sevenseven6123
    @sevenseven6123 Рік тому +1

    Hi, just stumbled upon this. Question regarding server/client components. If you wrap everything inside , and Provider is using the 'use client', isn't everything inside it automatically a client component? So there are no server rendered pages anymore? Or am I missunderstanding something?

    • @hamedbahram
      @hamedbahram  Рік тому

      Good question! Passing server components as children to client components (like this example) won't make them client components. Only when you import server components inside a client component it will turn everything into a client component. Does that make sense?

  • @AlfredoPutraDjaruBangun
    @AlfredoPutraDjaruBangun Рік тому

    this is really helpful. thanks Hamed! god bless

  • @nammdev97
    @nammdev97 Рік тому +1

    Thank you so much. Can you share a video to working with Next Auth & external API (provides token)?

    • @hamedbahram
      @hamedbahram  Рік тому

      You're welcome man. Sure I'll have that in mind. Thanks for tuning in.

  • @samuelliotta9437
    @samuelliotta9437 Рік тому +1

    Thanks for the great explanation! :) what still puzzles me is: let's say I have not only protected routes, but protected api endpoints as well - which is what you would expert in a real world scenario. For example in order to get myData, I need not only to be logged in, but to pass a Bearer token to myData endpoint. How can I pass the token to the endpoint in next 13? It would be trivial to do that client side, but on the server? I have not been able to find any explanation on that.

    • @hamedbahram
      @hamedbahram  Рік тому

      You can use the `getServerSession` function to check if the user is authenticated from inside your route handlers (API routes) - which eliminates the need to pass any tokens from the client-side to your endpoint. Does this answer your question? or am I missing something?

    • @samuelliotta9437
      @samuelliotta9437 Рік тому

      @hamedbahram thanks a lot for the reply! :) if I have an external backend (let's say in django) that requires me to pass a token in the url's headers, I would still need to pass the token. And I wouldn't know how to do that with next 13. :/

    • @hamedbahram
      @hamedbahram  Рік тому

      @@samuelliotta9437 If you're using the fetch API to hit your external backend, then you can pass tokens to your request headers. Does that answer you question or am I missing something?

    • @samuelliotta9437
      @samuelliotta9437 Рік тому +1

      Yes and no. The point is, where would I store the token to pass to the requests headers? The local storage is not available, some state manager would also not do, because the token needs to be available server side. I assume I'd have to set the token as a cookie upon successful login and that would make it available on the server (and I could set it through next's Middleware for those specific routes that need it). Does that make sense? Ps. I really appreciate your help! ;)

    • @hamedbahram
      @hamedbahram  Рік тому +1

      Ok now I see what the problem is. Depending on the authentication flow you're using, you can store the access token in your session database in the backend, retrieve the sessionId from the cookies on the request, lookup the session and retrieve the access token from your session database. As you mentioned it would involve using cookies to pass references to the server, that said, It wouldn't be safe to store the access token itself as a cookie.

  • @MichalRutz
    @MichalRutz Рік тому +1

    I love your delivery!
    Will be there any promo code soon for your next.js course? 🙏🏻

    • @hamedbahram
      @hamedbahram  Рік тому +1

      Glad you like it! I can give you student discount if it helps? send me an email.

  • @osamaehsan4926
    @osamaehsan4926 Рік тому +1

    Great video! But can you please create another video explaining how we can use Next Auth with our custom NodeJS backend that provides you an access token and a refresh token.
    Actually I don't want to use the token generated by Next Auth.

    • @hamedbahram
      @hamedbahram  Рік тому

      You can use the `encode` and `decode` function in next-auth to create your own tokens. You can read more about it here => next-auth.js.org/configuration/options#override-jwt-encode-and-decode-methods

  • @shawn-skull
    @shawn-skull Рік тому +1

    Please talk about the route protection with the middleware as you did in the Clerk video. The section about it of the Next-Auth documentation is confuse to me.

    • @hamedbahram
      @hamedbahram  Рік тому

      Thanks for the feedback Shawn! Will do!

    • @KyleMcNally
      @KyleMcNally Рік тому

      @@hamedbahram Yes, defintely need this video with a middleware how-to

    • @hamedbahram
      @hamedbahram  Рік тому

      @@KyleMcNally You got it Kyle. Thanks for tuning in.

  • @prkkarki8942
    @prkkarki8942 Рік тому +1

    I did exactly the same by wrapping the components in layout with a client compoent Session Provider, but deployment failed, it caused a prerender issue while deploying the app to vercel, but works fine locally. I checked multiple times by adding and removing the Provider wrapper from the layout. Do you have any idea how I can fix this?

  • @LbovboE
    @LbovboE Рік тому +1

    I got error when deploying to vercel due to the "Type error: Route "app/api/auth/[...nextauth]/route.ts" does not match the required types of a Next.js Route." How can i solve it? or vercel does not support latest app folder?

    • @hamedbahram
      @hamedbahram  Рік тому

      It should work; not sure why you're getting the error. Vercel does support the App router, but Typescript support of the new features is not 100% there.

    • @LbovboE
      @LbovboE Рік тому +1

      @@hamedbahram thx for the reply. It works locally with typescript and it’s able to run nicely with all the auth features. Only got this error when deploy to vercel not sure why.

    • @LbovboE
      @LbovboE Рік тому

      @@hamedbahram the app router for other api files all working file. Only the auth not building right.

    • @hamedbahram
      @hamedbahram  Рік тому

      @@LbovboE run a build locally and see if you get the same error and if you can trace what's causing it.

  • @elbezz
    @elbezz Рік тому +1

    awesome , thanks!

  • @tongthanhvinh2824
    @tongthanhvinh2824 Рік тому

    clear explaination, thanks man!

  • @aurelienchevillotte2874
    @aurelienchevillotte2874 Рік тому +1

    Nice Video, Can you tell me if that's possible to use Next Auth with JS and not TS and not in experimental version of Next ? thanks :)

    • @hamedbahram
      @hamedbahram  Рік тому +1

      Thanks Aurelien, yes you can use next-auth with `.js` files, and you can most definitely use them in the `pages` directory. see this video I have on the channel: ua-cam.com/video/AI9jExb5dDA/v-deo.html

  • @kakun7238
    @kakun7238 Рік тому +1

    Really helped me understand next-auth thank you could you make a video on how to decrypt the jwt token from next-auth like roles and username

    • @hamedbahram
      @hamedbahram  Рік тому +1

      Not sure if I understand your question correctly. Did you want to add `username` and `role` to JWT token? If yes you can use the `jwt` callback to customize the token and `session` callback to pass that to the browser. You can read more on it here: next-auth.js.org/configuration/callbacks#jwt-callback. If you meant that you want to override the JWT encoding and decoding methods, you can do so by passing `jwt` option to your `next-auth` config as follows: next-auth.js.org/configuration/options#override-jwt-encode-and-decode-methods. Does this answer your question?

  • @luizinhogm
    @luizinhogm Рік тому

    Thank you for sharing this excelent studies material ♥

    • @hamedbahram
      @hamedbahram  Рік тому

      Your welcome! Thanks for tuning in Luis.

  • @baybay1234
    @baybay1234 Рік тому

    Thanks for the explanation. I'm curious to know the reason you chose to get the session data (for displaying the user info on the Navbar) from the client side instead of the server component? if I understand it correctly, on the server component, the data is automatically cached? so it should be more performant than the client side? any insights would be helpful! thanks!

    • @hamedbahram
      @hamedbahram  Рік тому

      Hey! you can definitely use a server rendered component, I used a client side component to be able to add user interaction like clicking the avatar.

  • @amershboul9107
    @amershboul9107 Рік тому +1

    Very useful! thank you

    • @hamedbahram
      @hamedbahram  Рік тому

      Thanks for tuning in Amer.

    • @amershboul9107
      @amershboul9107 Рік тому

      @@hamedbahram but im getting this error
      decryption operation failed {
      message: 'decryption operation failed',
      stack: 'JWEDecryptionFailed: decryption operation failed
      ' +
      ' at gcmDecrypt (webpack-internal:///(sc_server)/./node_modules/jose/dist/node/esm/runtime/decrypt.js:81:15)
      ' +
      ' at decrypt (webpack-internal:///(sc_server)/./node_modules/jose/dist/node/esm/runtime/decrypt.js:104:20)
      ' +
      ' at flattenedDecrypt (webpack-internal:///(sc_server)/./node_modules/jose/dist/node/esm/jwe/flattened/decrypt.js:127:90)
      ' +
      ' at async compactDecrypt (webpack-internal:///(sc_server)/./node_modules/jose/dist/node/esm/jwe/compact/decrypt.js:22:23)
      ' +
      ' at async jwtDecrypt (webpack-internal:///(sc_server)/./node_modules/jose/dist/node/esm/jwt/decrypt.js:12:23)
      ' +
      ' at async Object.decode (webpack-internal:///(sc_server)/./node_modules/next-auth/jwt/index.js:44:26)
      ' +
      ' at async Object.session (webpack-internal:///(sc_server)/./node_modules/next-auth/core/routes/session.js:25:34)
      ' +
      ' at async AuthHandler (webpack-internal:///(sc_server)/./node_modules/next-auth/core/index.js:161:37)
      ' +
      ' at async getServerSession (webpack-internal:///(sc_server)/./node_modules/next-auth/next/index.js:129:21)
      ' +
      ' at async ServerProtectedPage (webpack-internal:///(sc_server)/./app/protected/server/page.tsx:16:21)',
      name: 'JWEDecryptionFailed'
      }

    • @amershboul9107
      @amershboul9107 Рік тому

      to solve that
      Add a secret key in the NextAuth configuration file. You can generate a random secret key using OpenSSL or another tool
      export const authOptions: NextAuthOptions = {
      ⚠⚠ secret: process.env.SECRET_KEY ,
      providers: [
      GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
      }),
      ],
      pages: {
      signIn: "/sign-in",
      },
      };

  • @buraxta_
    @buraxta_ Рік тому +1

    This was awesome 🎉

  • @kakuthakur-e6g
    @kakuthakur-e6g Рік тому +2

    Sir i have a question when we try to access a protected page we still get redirected there for a second or two after that we redirect to the login page is there a way to resolve this issue?

    • @hamedbahram
      @hamedbahram  Рік тому

      This happens when you're protecting a page on the client side using the `useSession` hook. To avoid this, you must either change the page to a server page and use `getServerSession` to check the session or use middleware to protect your page. You can watch this video where I show how to use middleware: ua-cam.com/video/SFQwto0rvps/v-deo.html

  • @reportpoison.shark.1326
    @reportpoison.shark.1326 Рік тому +1

    if both getserversession() and usesession() gives info about current session so can we use.......getserversession() in client component also for login check???? and if yes then why is usesession() created

    • @hamedbahram
      @hamedbahram  Рік тому

      You can't use the `getServerSession` client side since it required access to the `req` object. You can only use it on the server. You can use the `useSession` hook on the client-side to hook into the session provided by the React context.

  • @SachinSomia
    @SachinSomia Рік тому

    Good video, I think you are seeing redirect fail at 14:35 because it's a server function being used in client component, I think you have to use the useRouter hook with router.push()

    • @SachinSomia
      @SachinSomia Рік тому

      You may still need the CallbacKURL though

    • @hamedbahram
      @hamedbahram  Рік тому +1

      Thanks for the feedback. The redirect does not fail. It redirects but it doesn't set the search params correctly.

  • @ayushjain7023
    @ayushjain7023 Рік тому

    It's a great video, just have a question
    in
    const Provider = ({ children }) => {
    return {children}
    }
    why you haven't provided a session as mentioned in the docs

    • @hamedbahram
      @hamedbahram  Рік тому

      Providing the `session` prop to the `SessionProvider` helps to avoid fetching the session twice if we've already fetched it before. If you want to you can fetch the session in your root layout and pass it to the `Provider` component and from there to the `SessionProvider` component.

    • @ayushjain7023
      @ayushjain7023 Рік тому

      @@hamedbahram great I thought the same to use getserversession in rootlayout and pass it to the session provider ! Is there any reason you didn’t use it in your video ?

    • @ayushjain7023
      @ayushjain7023 Рік тому

      @@hamedbahram also if we don’t pass session to the provider then how useSession hook is able to get it, and does client and server sessions differ, can you plz clear my silly doubts 🥹

    • @hamedbahram
      @hamedbahram  Рік тому

      @@ayushjain7023 It wouldn't have made any difference in my case since I'm not fetching the session anywhere else.

  • @ayushgogna9732
    @ayushgogna9732 Рік тому +1

    Hi Hamed i am facing a issue i have create a custom signIn page and using credential provider how to i redirect to the previous page open before redirect to signIn. I want the behaviour like the next-auth custom signIn pages have callback searchparams which redirects to the page which was open before the redirect to signIn page ?

    • @hamedbahram
      @hamedbahram  Рік тому

      You need to set a `callbackUrl` when you're redirecting to the sign-in page, some like `/sign-in?callbackUrl=/the-path-to-redirect`

  • @gustavoseabra7495
    @gustavoseabra7495 Рік тому +1

    Ty so much this vídeo is better than the doc :p
    Only one thing, im having trouble with getServerSession, It only Works for me If i set at the .env file a nextauth secret, am i doing something wrong or is it really necessary? With client components its okay withouth the secret

    • @hamedbahram
      @hamedbahram  Рік тому +1

      I'm glad to hear that!
      You definitely need to set the `NEXTAUTH_SECRET`. It is used to encode your Jason Web Token. And you need to set it to a strong, long, random string.

    • @gustavoseabra7495
      @gustavoseabra7495 Рік тому +1

      @@hamedbahram Thank you very much for the information, would you know which environment variables are mandatory?

    • @hamedbahram
      @hamedbahram  Рік тому

      @@gustavoseabra7495 you're welcome. The NEXTAUTH_URL and the NEXTAUTH_SECRET are required, and obviously your credentials for any providers you want to add the NextAuth.

    • @gustavoseabra7495
      @gustavoseabra7495 Рік тому

      good evening hamed sorry to ask again. on localhost my sign in and signout function redirect correctly. however, in production they are trying to take the %27https route, do you know what it could be?

    • @hamedbahram
      @hamedbahram  Рік тому

      @@gustavoseabra7495 what do you mean by taking the HTTPS route?

  • @yantaosong
    @yantaosong Рік тому +1

    hi , great video , I am using next-auth , I don't know how to specify the expire time to user ?

    • @hamedbahram
      @hamedbahram  Рік тому

      When initializing NextAuth you can set `maxAge` on the `session` object which is the session expiry time in seconds. This works in the `pages` router; However, currently in server components we only have read access to cookies and the `expires` time defaults to 30 days.

    • @yantaosong
      @yantaosong Рік тому

      yes , it is server component ,can 't set it ? @@hamedbahram

  • @infinite4evr
    @infinite4evr Рік тому +1

    Hey, Thanks for this great video, I have a doubt tho, I am not able to get how do I authenticate a page that is Server side rendered and Client side rendered both? So if page is reloaded form browser refresh, it would be ssr, if it is navigated from the browser using link tag, it will be csr, how do I authenticate in that specific case, can you please lend me some help.

    • @hamedbahram
      @hamedbahram  Рік тому

      A client component will be pre-rendered on the server to generate the html but when it reaches the browser you can protect it with the `useSession` hook. If you want to authenticate on the server you should use a server component and use the `getServerSession` hook. Or you can eliminate all that and use a middleware to check the session before the response is sent to the browser. Does this answer your question?

    • @infinite4evr
      @infinite4evr Рік тому

      @@hamedbahram hey thanks for the response, Middleware is a good option, but I want to show an error page if the user is not authenticated and accesses the protected route, I don't see any way to modify the sign in url and redirect manually to error page

    • @hamedbahram
      @hamedbahram  Рік тому

      @@infinite4evr Is this from a client component or a server component?

  • @TheBenj30
    @TheBenj30 Рік тому +1

    For a while now I have been getting an issue with Next-Auth regarding it not working as I thought it would - in your example you have a protected API route that checks if there is a session and either responds that the users isn't logged in or their session name if they are - I get the same, it works as it does in your video, but if I do a get request with fetch to that endpoint, I get the response that I don't have a session - this means if I have a protected API endpoint where I want to check the users session and get relevant information out before doing an action, it will always return that the user doesn't have a session.
    Do you know what could be causing this - I have this idea that it could be related to cookies not being sent, but I can't find any information at all and I have set it up like you have.

    • @hamedbahram
      @hamedbahram  Рік тому

      From where are you sending the fetch request? Is it from a client component?

    • @TheBenj30
      @TheBenj30 Рік тому

      ​@@hamedbahram It's a server component, though I have tried as a client component as well - in both instances it returns the error message from the !session if check, however going directly to that api endpoint in the browser returns my email address.
      I don't know whether it's a technical issue I am having or whether I have just got the flow wrong, but I was thinking that because I am logged in and because I have a session cookie (which I guess is why it works by going directly to the endpoint in the browser) that it should work when doing a fetch, but no matter what way I seem to use it - I always get no session if I don't visit the api endpoint in the browser.

    • @hamedbahram
      @hamedbahram  Рік тому

      I'm not sure about your implementation on the client-side and what's causing the error. However, on the server-side, you don't need to call your API, you're already on the server, just do whatever it is you're doing in your API directly in your server component.

  • @favonix5697
    @favonix5697 Рік тому +1

    perfect

  • @cirdamih
    @cirdamih Рік тому +1

    Hi Hamed, great tutorial. Thanks! I am getting this error when building the app, "Type error: Route "app/api/auth/[...nextauth]/route.ts" does not match the required types of a Next.js Route.
    "authOptions" is not a valid Route export field.". Everything works in dev mode. I am wondering if you have seen it and resolved the issue.

    • @hamedbahram
      @hamedbahram  Рік тому +1

      Uhmm 🤔, I'll look into it, in the mean time, try exporting your auth options from a different file like `_options.js` and import in the `[...nextauth]/route.js` file and let me know if that solved the problem.

    • @cirdamih
      @cirdamih Рік тому +1

      @@hamedbahram wow, that resolved the issue!! Thanks so much!

    • @hamedbahram
      @hamedbahram  Рік тому +1

      @@cirdamih Awesome! glad hear that.

    • @Juaaanse
      @Juaaanse Рік тому +1

      @@hamedbahram I had a similar issue but I was getting this different error: "Property 'authOptions' is incompatible with index signature. Type 'AuthOptions' is not assignable to type 'never'." Your solution worked.
      But, I wonder why that happens? It's like it doesn't accept any other code than a "handler" variable being exported 🤔

    • @hamedbahram
      @hamedbahram  Рік тому

      That's right, it treats exports from `route.ts` as handlers.

  • @erfansormi4605
    @erfansormi4605 Рік тому +1

    سلام آقا حامد گل، وقتت بخیر
    آقا یه سوال داشتم
    این امکان وجود داره که توی next auth، توکن رو به صورت httpOnly ذخیره کنیم تا نشه از کلاینت به اون دسترسی داشت؟

    • @hamedbahram
      @hamedbahram  Рік тому +1

      Salam Erfan Jan,
      The session token is stored as HttpOnly cookie by default.

    • @erfansormi4605
      @erfansormi4605 Рік тому

      @@hamedbahram i asked this question because i see token cookie in application tab and with remove that, user logouting.
      i thought that we not access httpOnly cookie in client

    • @hamedbahram
      @hamedbahram  Рік тому +1

      @@erfansormi4605 HttpOnly means that they cannot access the cookie from JavaScript code. Users can always go to the application tab in their developer tools and see all the cookies.

    • @erfansormi4605
      @erfansormi4605 Рік тому

      @@hamedbahram thank you very much🙏🏼

  • @CaleMcCollough
    @CaleMcCollough Рік тому

    Thank you so much! You just got me unstuck!

  • @27sosite73
    @27sosite73 Рік тому +1

    damn
    4k!
    nice!

  • @MrAtomUniverse
    @MrAtomUniverse Рік тому +2

    I can’t use middleware to protect route when I use google login with nextauth and Prisma any idea why ?

    • @hamedbahram
      @hamedbahram  Рік тому +1

      Middleware runs on the edge runtime by default and Prisma can't run on the edge.

    • @MrAtomUniverse
      @MrAtomUniverse Рік тому +1

      @@hamedbahram hmm if i dont use prisma adapter but just google provider, can i start using middleware to protect routes then? Not sure how prisma affects how nextauth works

    • @hamedbahram
      @hamedbahram  Рік тому

      @@MrAtomUniverse Yes that should solve the problem. If you're using an adapter like prisma to connect NextAuth to your database it uses it to read user data, but as I mentioned prisma can't run on the edge for the time being.

  • @mustafayavas2173
    @mustafayavas2173 Рік тому +1

    Thanks for amazing videos!
    When I try to log in with google in the production, the application redirects the user to localhost. I get this error only if I use the api folder. The Pages folder does not have this error. What could be the reason?

    • @hamedbahram
      @hamedbahram  Рік тому

      Check your `NEXTAUTH_URL` env variable and the callback URL you set when creating your Google credentials. Here is some resources to the docs: next-auth.js.org/configuration/options#nextauth_url

  • @elijahonduso
    @elijahonduso Рік тому +1

    I want to prevent user from redirecting to login page if the session exists. How do I achieve this? Otherwise, this tutorial was so amazing❤

    • @hamedbahram
      @hamedbahram  Рік тому

      I've explained that thoroughly in the video. If it's a server component you can use the `getServerSession` function, and if it's in a client components you can use `useSession` hook to check the session.

    • @elijahonduso
      @elijahonduso Рік тому +1

      @@hamedbahram That's cool. But the challenge is a flash of the login screen before the redirection happens to the home page. Was wondering if there's a better alternative

    • @hamedbahram
      @hamedbahram  Рік тому

      You can use a middleware to intercept the request, authenticate, and redirect if not logged in. Watch this video: ua-cam.com/video/SFQwto0rvps/v-deo.html

  • @Fervillanuevas
    @Fervillanuevas Рік тому +1

    Thanks sir

  • @aritrabose8050
    @aritrabose8050 Рік тому

    Amazing video; I was literally waiting for this. BTW I am very curious to know what font you are using in your editor because I have seen this font many times UA-cam used by several other NextJS developers. And is it compatible with JetBrains Webstorm?

  • @MrNewaz
    @MrNewaz Рік тому +1

    So does wrapping the whole app in a client component make every component a client component?

    • @hamedbahram
      @hamedbahram  Рік тому

      Good question. No it does not. If you pass server components as children to client components, it doesn't turn them into client components. However if you import a server component into a client component, it will be considered a client component, and will potentially break your code if it is async.

  • @zabialy2919
    @zabialy2919 Рік тому +1

    Is there a way to access the sessions data in server-rendered pages? Currently when printing the session i can only see the users email, but all the data stored in the session during login isn't accessible. It would be useful to do some conditional rendering.

    • @hamedbahram
      @hamedbahram  Рік тому

      You can use the `jwt` callback together with the `session` callback to add more data to the session object. Read more about it here => next-auth.js.org/configuration/callbacks#jwt-callback

    • @zabialy2919
      @zabialy2919 Рік тому +1

      @@hamedbahram Thank you! I was already doing that but I realized the error was in the next-auth config itself! Comparing my config to yours and the docs fixed my problem. I really appreciate your answer!

    • @hamedbahram
      @hamedbahram  Рік тому

      @@zabialy2919 My pleasure!

  • @nabeelahmed8179
    @nabeelahmed8179 Рік тому +1

    So if I wrap the children in SessionProvider, wouldn't that make all the child components client based?

    • @hamedbahram
      @hamedbahram  Рік тому +1

      No it won't. You can pass server components as props or children to client components without effecting the server-client boundary.

    • @nabeelahmed8179
      @nabeelahmed8179 Рік тому

      @@hamedbahram This is the layout file:


      {children}
      Footer
      Now Header is in the client based component because of next auth using context api. The header contains an api call for the menu data. Now the api request shows up in the network tab. If I remove the session provider wrapper then it does not show up in the network tab. I also have a products listing page but that seems to work fine. its not showing the api call for the products page in the network tab.

  • @SSango-hk9sm
    @SSango-hk9sm Рік тому +1

    Thanks for the tut, helpful always. I have a question though. I have a users table and workspace table where each user can have one or many workspaces linked to his.her account. After the user is signed in successfully I would like to run a db query to check if the user has a workspace linked to his/her user_id. If not I would like to redirect that user to a page where they can create a workspace. I'm using Postgre and Prisma adapter by the way.

    • @hamedbahram
      @hamedbahram  Рік тому

      Thanks! you can do the lookup inside the `jwt` callback. If this should only happen once for new users, you can check the `isNewUser` argument passed to the `jwt` callback. See here for more: next-auth.js.org/configuration/callbacks#jwt-callback

    • @SSango-hk9sm
      @SSango-hk9sm Рік тому +1

      @@hamedbahram Thank you so much for the response let me try it that way.

    • @hamedbahram
      @hamedbahram  Рік тому

      @@SSango-hk9sm Anytime!

    • @SSango-hk9sm
      @SSango-hk9sm Рік тому

      @@hamedbahram So I looked into the `jwt` callback and all the data that is returned. And also I was able to run db queries. but what's left now is to be able to redirect from that callback. Is it possible? Something like this:
      async jwt({ token, user, account, profile, isNewUser }) {
      //get user details and perform db query.
      //Redirect user to different pages depending on the query results
      }
      I have tried to redirect using the NextResponse.redirect() but I get the `Invalid URL` error.

    • @hamedbahram
      @hamedbahram  Рік тому

      @@SSango-hk9sm Try the `redirect` function from `next/navigation` and pass the URL.
      import { redirect } from 'next/navigation';
      ...
      redirect(`/path`)
      ...
      You should be able to also use the `NextResonse` in the following format:
      import { NextResponse } from 'next/server'
      ...
      const destination = new URL('/new'', request.url)
      return NextResponse.redirect(destination)
      ...

  • @naveedalirehmani4135
    @naveedalirehmani4135 11 місяців тому +1

    what if I have my backend on node.js & I am handling Oauth on node.js server? how can I create protected routes in that case?
    can you please guide me through this or direct me to a good source? maybe a video of your own.

    • @hamedbahram
      @hamedbahram  11 місяців тому +1

      That's good question! I'm actually working on a video about creating a proxy on top of your backend API for rate limiting and authentication. So stay tuned.

    • @naveedalirehmani4135
      @naveedalirehmani4135 11 місяців тому

      @@hamedbahram your the best!

  • @juanbovier7458
    @juanbovier7458 Рік тому +1

    Hi Hamed, can you please make a video using refresh tokens whit this provider? I need to save it on MongoDB and most importantly, i need to use 2 providers at the same time, i am creating something like Calendly, i mean, the users create their accounts using credentials (email - password) and after that i need to sync their Google Calendar but i don't know how can i do that

    • @hamedbahram
      @hamedbahram  Рік тому

      Hi Juan! Interesting use case, I'll have that in mind for future videos.

  • @HaHoang-qk6ti
    @HaHoang-qk6ti Рік тому +1

    Assume I had a database where stored user data and there are two types of users: admin and normal user. Can I use "protected server-side" and "protected API routes" instead of JWT to protect some pages only allow admin access? Is it good and secure enough?

    • @hamedbahram
      @hamedbahram  Рік тому

      Trying to understand the question here, what do you mean by instead of JWT?

    • @HaHoang-qk6ti
      @HaHoang-qk6ti Рік тому

      ​@@hamedbahram JWT means JSON Web Tokens. I had watched some tutorials that used this approach to protect API. It was complex for me so I'm finding some easier ways.

    • @hamedbahram
      @hamedbahram  Рік тому

      ​@@HaHoang-qk6ti I know what JWT is but didn't understand what you're trying to do with it.
      Generally speaking, with next-auth you can use JWT to authenticate users instead of database sessions. You can also define different roles for your users and limit the access to some pages, only if they are "admin" users.
      Let me know if this answers your question.

    • @HaHoang-qk6ti
      @HaHoang-qk6ti Рік тому

      @@hamedbahram Sorry for my bad explanation. You're right, I did want to define different roles for users and limit the access to some pages. I want to do it in the simplest way - only use next-auth (I don't want to combine with JWT). Is it possible and good enough?

    • @hamedbahram
      @hamedbahram  Рік тому

      @@HaHoang-qk6ti Yes you can do that completely with next-auth. Just so you know next-auth also has JWT sessions, where instead of a database you store user data in Json web tokens. I have a video on the channel where I review all these options in next-auth. You can watch it here and let me know if you have any questions: ua-cam.com/video/AI9jExb5dDA/v-deo.html

  • @Shubham-yc6nz
    @Shubham-yc6nz Рік тому

    Thanks

  • @DnKZone
    @DnKZone 10 місяців тому +1

    How to fetch the data internally from the website? Cookies are not being sent with the request

    • @hamedbahram
      @hamedbahram  10 місяців тому

      What do you mean by fetch data internally from the website?

    • @DnKZone
      @DnKZone 10 місяців тому

      @@hamedbahram sorry, I mean to say, how to fetch data from the protected api routes in backend/page/server component using `fetch`?
      I did like
      let res = await fetch("https:/mywebsite/api/users", {...})
      let users = await res.json()
      return users
      but it gives me errors. Upon debugging (just a console.log), I found that `session` variable is null, so it's returning "SESSION NOT FOUND" error message from the api. Also there's no Cookie, I checked `req.cookies()`.
      How to fix?

  • @forwardtrack
    @forwardtrack Рік тому +2

    bro jump scared me at 15:31

  • @Shubham-yc6nz
    @Shubham-yc6nz Рік тому +1

    For SSR pages, can we get automatically pass the correctly callback without hardcoding? The way it works on Client Side with required=true `useSession({ required: true })` ?
    ```
    const session = await getServerSession(authOptions);
    if (!session) {
    redirect("/login?callbackUrl=/protected-server");
    }
    ```

    • @hamedbahram
      @hamedbahram  Рік тому

      There is currently not an easy way to get the current `path` in your server components. The only other way to protect a server-rendered path would be to use a middleware. See this video: ua-cam.com/video/SFQwto0rvps/v-deo.html

    • @Shubham-yc6nz
      @Shubham-yc6nz Рік тому +1

      @@hamedbahram Thanks for your reply. I was able to code it. Pasting here for other's reference.
      import { headers } from "next/headers";
      import { redirect } from "next/navigation";
      if (!session) {
      const headersList = headers();
      const currentPathName = headersList.get("x-invoke-path") || "";
      currentPathName
      ? redirect("/login?callbackUrl=" + currentPathName)
      : redirect("/login");
      }

    • @Shubham-yc6nz
      @Shubham-yc6nz Рік тому

      @@hamedbahram I had one more question. Is headless UI or mantine supported with app directory for SSR pages?

    • @hamedbahram
      @hamedbahram  Рік тому

      Sweet! Just keep in mind that `headers()` is a dynamic function and using it in a layout or page will opt the route into dynamic rendering at request time.
      As far as the UI libraries, you might need to wrap them in your own client components with the `use client` directive to work. I don't know of any that supports the App router yet, and since most of the use hooks and context, you won't be able to directly use them in server components.

  • @IjeomaEgwuenu
    @IjeomaEgwuenu Рік тому +1

    Thanks

  • @frln16
    @frln16 Рік тому +1

    I was looking such content and end it here. Its very helpful.
    Thank you very much and keep it up.
    I am getting error while deploying on windows IIS web server. Error: Please define a `secret` in production. MissingSecret [MissingSecretError]: Please define a `secret` in production.
    ====
    Please help me it could save my life.

    • @hamedbahram
      @hamedbahram  Рік тому

      Glad you found the video helpful. Regarding the error, you have to set the `NEXTAUTH_SECRET` environment variable. This is a random long string that'll be used to hash your tokens.

  • @SebastianBerg-y5i
    @SebastianBerg-y5i Рік тому

    Have you tryed and actually deploy this, basically trying to do the same, but when I run npm run build I get all sorts of problems.

    • @hamedbahram
      @hamedbahram  Рік тому

      Which branch are you trying to deploy?

  • @semajroyam3725
    @semajroyam3725 Рік тому +1

    can you make one for typescript sir?

    • @hamedbahram
      @hamedbahram  Рік тому +1

      You got it, should be pretty straight forward.

  • @udaym4204
    @udaym4204 Рік тому

    i publish my website with next js on vercel. what commpitetor spam my website and Google AdSense block my account so how to protect from spam bot and also not affect seo Thank you for your valuable knowledge and valuable time Thank you

    • @hamedbahram
      @hamedbahram  Рік тому

      You can look into solutions like DataDome or Botd, to protect against bots, here are links to sample code:
      vercel.com/templates/next.js/bot-protection-botd
      vercel.com/templates/next.js/bot-protection-datadome

    • @udaym4204
      @udaym4204 Рік тому

      @@hamedbahram thank you does it on google seo

  • @eliuddyn
    @eliuddyn Рік тому

    Amazing 🔥🔥

  • @codewithsam7300
    @codewithsam7300 Рік тому

    I have a suggestion sir. Please start the project from scratch. Thats helps alot rather then starting the half work already done and explain....

    • @hamedbahram
      @hamedbahram  Рік тому

      Thanks for your feedback. I'll do it in my future videos.

  • @TheNefelin
    @TheNefelin Рік тому

    THANKSSSSSSS!!!!!!!!!!!!!!!!!!

  • @codewithsam7300
    @codewithsam7300 Рік тому

    whenever i try to signin with google is say ->"You can’t sign in because this app sent an invalid request. You can try again later, or contact the developer about this issue. "

    • @hamedbahram
      @hamedbahram  Рік тому

      Make sure you've created your Google OAuth correctly, you can read more here: next-auth.js.org/providers/google
      You can also compare your code to mine and see if you've set everything up correctly.

  • @kavkavy
    @kavkavy Рік тому +1

    what about identity server

    • @hamedbahram
      @hamedbahram  Рік тому +1

      Can you expand on what you mean by identity server?

    • @kavkavy
      @kavkavy Рік тому

      @@hamedbahram next-auth/providers/duende-identity-server6

  • @run4ever102
    @run4ever102 Рік тому +1

    Go to 15:32 and watch closely for a surprise 😂

  • @rajaneeshg2583
    @rajaneeshg2583 Рік тому

    Failed to collect page data for /api/auth/[...nextauth] npm build

    • @hamedbahram
      @hamedbahram  Рік тому

      Did you include a `route.js` file inside the `/api/auth/[...nextauth]` folder?

    • @rajaneeshg2583
      @rajaneeshg2583 Рік тому +1

      @@hamedbahram yes

    • @rajaneeshg2583
      @rajaneeshg2583 Рік тому +1

      Thanks next-auth/next this getting issue after remove /next it started working

  • @alexiglesias3464
    @alexiglesias3464 Рік тому

    You even didn't explain how to set up the login and how we get the jwt token ...

    • @hamedbahram
      @hamedbahram  Рік тому

      Thanks for your feedback Alex. The login page is pretty straight forward if you look at the source code (link in the description) I'm using the `signin` function from `next-auth` to start the Google signin flow. You can watch this video where I dive deeper into next-auth:
      ua-cam.com/video/AI9jExb5dDA/v-deo.html
      Also if you use the token strategy, next-auth would handle your JWT token for you. You can access / modify your token inside `jwt` callback. You can read about it here:
      next-auth.js.org/configuration/callbacks#jwt-callback

  • @waleedsharif618
    @waleedsharif618 Рік тому

    Where are you from? my brothers name is also Hamed 🙂

    • @hamedbahram
      @hamedbahram  Рік тому +2

      Welcome to the channel Waleed! Say hi to your brother :)

    • @juanferrer5885
      @juanferrer5885 Рік тому +1

      Awesome videos! Could you talk about state management for nextjs? I don't know if i should use redux toolkit, zustand, jotai o something else

    • @hamedbahram
      @hamedbahram  Рік тому +1

      @@juanferrer5885 Thanks Juan, that sounds like a good topic for a future video.

  • @BrianCabrera-o7x
    @BrianCabrera-o7x Рік тому +1

    Esta bueno el tutorial porque se saltea 20 pasos...

  • @ggff2269
    @ggff2269 Рік тому +1

    Hey please make video on credentials instead of google auth😭😭😭. I wasted my 2 days just because of bad documentation and lack of non tyoescript tutorials for this shitty package

    • @hamedbahram
      @hamedbahram  Рік тому

      I'll definitely have that in mind for future next-auth videos.

  • @VivekChavan-ov3pl
    @VivekChavan-ov3pl Рік тому +1

    9:40

  • @web_knowledege
    @web_knowledege Рік тому

    سلطان ایرانی هستی؟

    • @hamedbahram
      @hamedbahram  Рік тому

      Bale ghorban. Mokhlesim.

    • @web_knowledege
      @web_knowledege Рік тому

      @@hamedbahram عزیز دلی
      باعث افتخارمون هستی

  • @oamarkanji3153
    @oamarkanji3153 Рік тому

    So helpful, thank you

  • @ALEXISKENALVAREZ
    @ALEXISKENALVAREZ Рік тому +1

    How do I fetch server side if my component has useState which requires the component to use 'use client' that makes it client component?

    • @hamedbahram
      @hamedbahram  Рік тому +1

      Different ways to do it:
      1. Use a server component to wrap your client component, and fetch the data and pass it to your client component.
      2. Move the `useState` hook further down to the actual end component that needs it, therefore you can turn your original client component into a server component.