Next.js protected routes & JWT verify (Updated video link in description)

Поделиться
HTML-код
  • Опубликовано: 15 ноя 2024

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

  • @VladimirAmosov
    @VladimirAmosov 2 года назад +7

    Thank you for good explanation. One thing - you don’t have to import React from “react” in NextJS pages.

  • @justfun591
    @justfun591 2 года назад +5

    After implementing all the code shown in the video I am getting this error:
    *You're using a Node.js module (crypto) which is not supported in the Edge Runtime.*

  • @yorkitca
    @yorkitca 2 года назад +1

    Great video!
    Not sure how I missed in a few days ago when I saw the previous video.
    Your videos are on point my friend!
    Keep up the great work.

  • @ranjmahmood2429
    @ranjmahmood2429 2 года назад +2

    Great tutorial. I have been looking for this for so long. Thanks

  • @dogemon2136
    @dogemon2136 2 года назад +3

    Simple and to the point . Respect 💯

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

    So good tutorial to the point not necessaritly long. and clear

  • @carefree_ladka
    @carefree_ladka 2 года назад +2

    This is amazing. Keep up the good work 🙂

  • @akhil0227
    @akhil0227 2 года назад +2

    Hey thanks a lot for this 👍. Straight to the point and well explained 👌

  • @eleganz4978
    @eleganz4978 2 года назад +4

    Great content bro, you explain things so good and easy. Thanks man.

  • @ivaxCVPraiaMoinho
    @ivaxCVPraiaMoinho 2 года назад +2

    Thank you. Great tutorial and simple explanation

  • @navpreetsingh3007
    @navpreetsingh3007 2 года назад +2

    This video deservers more view and likes. Great content

  • @mohithkumar1624
    @mohithkumar1624 2 года назад +1

    in _middlewar.js file am tying to us useSelector hook to get Redux state values ,then I got the error "Invalid hook call. Hooks can only be called inside of the body of a function component............ ". What can I do now..?

  • @matheusmendes357
    @matheusmendes357 2 года назад +1

    Quick and simple video. Good job 👏

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

    Hello, your tutorial is so good. I follow your tutorial but i got error 'Uncaught Error: The edge runtime does not support Node.js 'buffer' module' in middleware.js which is lead to import { verify } from "jsonwetoken" include buffer node.js api. How can i solve that

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

    Hello,_middleware.js is not working in version 120.4 in nextJS?..is it not supported?

  • @balduin_b4334
    @balduin_b4334 2 года назад +1

    sadly the jsonwebtoken isn´t able to run on the edge, so this isnt working anymore..
    -> you can use "jose" instead
    -> middleware must be a sibling of "/pages"

  • @keeganguitar
    @keeganguitar 2 года назад +1

    This was so great! 😃You really made the whole thing simple.

  • @willyhorizont8672
    @willyhorizont8672 2 года назад +1

    this is what im lookin for thanks🚀 I have jwt http-only cookie auth react app too.. and now I want to create another one with next but Im confuse how to role based protected routes in next

  • @waliullahkhan6862
    @waliullahkhan6862 2 года назад

    what a great video it was, just search and get understand everything. Thanks

  • @ФилипВасиловски-ь5ш
    @ФилипВасиловски-ь5ш 2 года назад +1

    Allright, you are awesome

  • @MarcelPirosca
    @MarcelPirosca 2 года назад

    Thanks a lot for this video, helped me set up my _middleware properly.

  • @oZnBaHaDiR
    @oZnBaHaDiR 2 года назад +1

    First of all, thank you for a great explanation.
    As a beginner, I have a few issues on my mind. How do I pass the logged in user's information to the next route? Is it a safe choice for me to host user id in jwt? Does it affect the performance that we are checking jwt over middleware every time? I will be glad if you can inform

    • @MarcelPirosca
      @MarcelPirosca 2 года назад +1

      I created an array of protected routes and checked the JWT only "if (protectedRoutes.includes(pathname))". That way you don't do it every single time.
      Unfortunately, I didn't find a solution on how to pass the user info to the next stage. I'm decoding it again there, but I don't think it's an expensive operation.
      Hope this helps.

    • @oZnBaHaDiR
      @oZnBaHaDiR 2 года назад

      @@MarcelPirosca Thank you for your answer and help. For now, I solved the solution with getSession logic. I will try the method you said

    • @alexandrecoma221
      @alexandrecoma221 2 года назад

      You can use the Context API

  • @stefanosalazar3329
    @stefanosalazar3329 2 года назад

    Thank you for the tutorial its helping me with a project, i have a question, can i access the cookie to grab information? like the user name of the loged user to use for example in a dashboard to show his name?

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

    this is an updated tutorial about this topic ruclips.net/video/zBbqrcvdJjQ/видео.html

  • @monarchgam3r
    @monarchgam3r 2 года назад +2

    Great content, learnt a thing or 2… please can you make a tutorial on deploying a nextjs application? Especially deploying on custom server

    • @tenacity_dev
      @tenacity_dev  2 года назад +1

      Thank you, I'll keep it in mind for my next video.

  • @mdassadujjaman771
    @mdassadujjaman771 2 года назад +1

    It was working with next.js 12.0.8 but not working with 12.1.6
    Does anybody facing this problem with new version ?

  • @farhadalamkawser7852
    @farhadalamkawser7852 2 года назад +1

    thank you so much SIR,,It helps a lot..❤️❤️

  • @RajeshKumar-sq2ji
    @RajeshKumar-sq2ji 2 года назад +1

    Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Middleware pages/_middleware
    When I used middleware in nextjs.... woked fine
    but build failed....
    plz let me get help if possible?
    Thanks For Great Tutorial.

    • @dqampire
      @dqampire 2 года назад

      Use this library to verify your token @tsndr/cloudflare-worker-jwt

    • @jampietri583
      @jampietri583 2 года назад

      Realized that after a while. That just doesn’t work. Still looking for the solution. Using next-connect and write the middleware with regular node.js sintax or using next-auth are my guesses.

  • @willsmith6496
    @willsmith6496 2 года назад

    Does it mean we have to write this code on every api route we want to protect? Isn’t there a central place where we can put this code so nextjs automatically triggers it for all the routes we want to protect? Seems like a bit redundant to me.

    • @anthonyezeh7511
      @anthonyezeh7511 2 года назад

      Oh, man! It is a middleware that triggers on every request. It then checks if the URL includes the path you want to protect.

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

    It is useful. Thank you.

  • @anthonyezeh7511
    @anthonyezeh7511 2 года назад

    There is a new update and I don't think JWT works this way with the new middleware logic. Please, could you make a new video to show the usage?

  • @Mike-xr1fk
    @Mike-xr1fk Год назад

    Thank you for making this amazing course man!
    I just have a question.
    I make a request to the login API and I receive the refresh token that is in the cookie and the access token that is in the response body. Now how should I handle the access token on the client side(next js)? If I store this in a global state like context API, then I don't have access to that state in the getServerSideProps function, and I can't set it in the request.header.authorization because getServerSideProps run on server side!

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

      You don't touch or handle the token on your side. Make a route for example '/me' in which you will get your user's data. Then place that date inside the context and you will know that you have authenticated the user. The request for '/me' is always sent at the beginning of the mount process.

  • @siamekanto
    @siamekanto 2 года назад

    Does it work with Static Export if I make API Request to my backend express server to check if user can access this page?

  • @mfion1
    @mfion1 2 года назад

    Best authentication in next js video

  • @DryHub
    @DryHub 2 года назад +1

    Thank again for a nice tutorial... I have a question... What if i have multiple route to protect...

    • @tenacity_dev
      @tenacity_dev  2 года назад

      In this example every route under "dashboard" is protected. So if there's "/dashboard/user" or "/dashboard/messages" it will be protected.
      If you for example just want "/user" and "/messages" to be protected, just check if the url is "messages' or url is "user" and then check the jwt.

    • @DryHub
      @DryHub 2 года назад +2

      @@tenacity_dev thanks i test it's work perfectly work... ❤️❤️

  • @AllahomAnsorGaza
    @AllahomAnsorGaza 2 года назад

    i think they changed the _middleware to middleware ?
    please verify to me because the both dont work with me

  • @AliAhsan1
    @AliAhsan1 2 года назад +1

    you made it look soo simple

  • @mikha2880
    @mikha2880 2 года назад

    great work! you just got new subscriber 🎉

  • @Wardret
    @Wardret 2 года назад +2

    Good tutorial, but I have a question. How does the verify method know, that it is a valid JWT? With what it compares? And is it possible to use the verify method if you receive JWT from outside ( you get it from loging in) ?

    • @tenacity_dev
      @tenacity_dev  2 года назад +2

      Hey, thank you. It takes the token that we sent as the first argument, and the secret key that we used on it when we called the "sign" function as the second. It knows because the secret key is the same as the one we signed the token with, because of that it can give you the payload of the token.
      You can use verify with whatever you want. Someone can place a jwt inside the body or headers of a request, you can still extract it from there and call verify.
      You can check out their docs here: self-issued.info/docs/draft-ietf-oauth-json-web-token.html

  • @carlossierra173
    @carlossierra173 2 года назад

    when i enter at mobile it doesn't work the route protected

  • @Owenimus
    @Owenimus 2 года назад

    how do you automaticly log the user back when the user refreshes the page via jwt?

  • @hitenjain4688
    @hitenjain4688 2 года назад +2

    nice tutorial , but i keep getting cannot resolve module crypto error, any help would be appreciated

    • @tenacity_dev
      @tenacity_dev  2 года назад

      Install crypto module if you don't have it. That might resolve the issue.

    • @hitenjain4688
      @hitenjain4688 2 года назад +1

      @@tenacity_dev no it says that crypto module is not allowed in edge runtime functions

    • @vraj2003
      @vraj2003 2 года назад

      @@hitenjain4688 same. You find any solution?

  • @turing4991
    @turing4991 2 года назад +1

    what if i have stored the token in LocalStorage?

    • @carlossierra173
      @carlossierra173 2 года назад

      but using localstorage you won't be able to do server side rendenring

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

    Excellent!

  • @AllahomAnsorGaza
    @AllahomAnsorGaza 2 года назад

    and how i can pass the payload to the next route or save it in somewhere to access from the next route

  • @anvui95
    @anvui95 2 года назад

    hello thanks for your video, can you show us with the new middleware of nextJS ? i am struggling to verify my token now

  • @waliullahkhan6862
    @waliullahkhan6862 2 года назад

    can i use this logic in my project?

  • @deepakbhatt7494
    @deepakbhatt7494 2 года назад

    Great work Jonas, could you please make one video that is for custom login form

  • @piusijachi2763
    @piusijachi2763 2 года назад +1

    Hello, please how would I get used data in the client side like logged in users name and all if I can't access cookie and get token

    • @tenacity_dev
      @tenacity_dev  2 года назад

      You will send a request to get the users data each time you reload the page and then you can do whatever you want with the user data response.

    • @piusijachi2763
      @piusijachi2763 2 года назад

      @@tenacity_dev OK thanks alot

    • @piusijachi2763
      @piusijachi2763 2 года назад +1

      @@tenacity_dev since middle ware came out everyone uses it to protect api routes you are the only tutorial that actually did protected routes, small subscribes now but I'm sure that will change soon

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

    Is there a way to clear cookies and redirect at the same time? I was only able to do one of them by returning either NextResponse.next() or NextResponse.rewrite() (new redirect) but not both.

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

    in auth folder you did't show the login file plz show that file

  • @rizqyfahmi8343
    @rizqyfahmi8343 2 года назад

    Hi... it's such as great video.
    I use the same way as you but I try to make a little modification. I call an API for cookie verification instead of directly do it inside middleware but I can't get the cookie on API Auth. It's always undefined in the log. In other hand, API can get the cookie when I call API Auth from HOC. Do you know about it?
    Anyway I have separate project for the API. I don't use API of NextJS. Thanks a lot.

    • @garbjorn1757
      @garbjorn1757 2 года назад

      Try console.log the cookie and see what does it give.
      I have a slight same problem a while back when I'm trying to retrieve the token from cookie and it cant be verified as it returns undefined after passing the verify block. So I tried logging it in the console and found out that it returns token=abcd instead of abcd when retrieving it from cookie.

  • @digvijayrana340
    @digvijayrana340 2 года назад

    can you please provide full code for this ?????

  • @gatocode316
    @gatocode316 2 года назад

    this was helpful, thanks!

  • @baibarsrajput1848
    @baibarsrajput1848 2 года назад

    thanks for saving my day

  • @ahmedakermi
    @ahmedakermi 2 года назад

    ICAN DECODE TOKEN IN NEXT JS (front)AND RETRIVE INFORMATION OR NOT
    ?

    • @tenacity_dev
      @tenacity_dev  2 года назад

      You're not decoding it in the frontend, the _middleware.js file is a middleware. getServerSideProps and getStaticProps are also not on the frontend but you write them like they are.

  • @abdullahmalik7346
    @abdullahmalik7346 2 года назад

    bro, when deployed the vercel he is not working ?plz help me about this

    • @tenacity_dev
      @tenacity_dev  2 года назад

      Check if your env variables are good. You can also solve this problem by calling next(); when you see a token and then verify the token with getServerSideProps function.
      middleware.js
      {
      check for token
      if i have a token
      call NextResponse.next() function
      if i don't have a token
      call NextResponse.redirect() function
      }
      then let's say you went to '/dashboard/user'
      {
      export async function getServerSideProps(context) {
      check for token here
      verify it
      if token is alright
      return the page
      if it isn't alright
      return unauthorized
      }
      }
      I made a mistake in the video by not saying that .env variables won't work in _middleware.js in production mode, but you can fix it with the way i gave you

  • @yudomaryanto1643
    @yudomaryanto1643 2 года назад +1

    broo, nice video. but you need to update your repo. thanks

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

    Tks bro !

  • @unicboyz8178
    @unicboyz8178 2 года назад

    Thank you so much!

  • @thegamingchannel8229
    @thegamingchannel8229 2 года назад

    I have a typeError says url.includes is not a function please help me

    • @tenacity_dev
      @tenacity_dev  2 года назад

      Check if you got the request object correctly. Url is a property of the request object (req).

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

    Tks sir :)

  • @amaurimdsantos
    @amaurimdsantos 2 года назад

    The tutorial is good, specially the previous video but unfortunately I'm getting the following error: Error: URLs is malformed. Please use only absolute URLs - Documentation is saying that we should use NextRequest, clone the url and then rewrite it. I'll try to fix this

    • @szerkan778
      @szerkan778 2 года назад

      did you figure it out how to do it? :(

    • @aquilesburlamaqui
      @aquilesburlamaqui 2 года назад

      const { pathname, origin } = req.nextUrl
      return NextResponse.rewrite(`${origin}/login`).

    • @aquilesburlamaqui
      @aquilesburlamaqui 2 года назад +1

      A better solution, i think is use:
      return NextResponse.redirect(new URL('/', req.url))

    • @carlossierra173
      @carlossierra173 2 года назад

      @@aquilesburlamaqui i also did it

  • @sahnounmohamed5871
    @sahnounmohamed5871 2 года назад

    i got this : Error: The edge runtime does not support Node.js 'buffer' module.

  • @daveglad3554
    @daveglad3554 2 года назад +1

    Top bro 🤗♥️

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

    How to protect route in next js 13?

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

      I'll make a video about it for next.js 13 using the app directory.

  • @ezrasenaputra8524
    @ezrasenaputra8524 2 года назад

    thanks for this great tutorial.
    but i have an issue on getting the cookies back.
    after i made the middleware, it always return "undefined" for the jwt cookies.
    also i try to hit /api/user with postman the cookies return undefined.
    anybody know why this is happening?

    • @dinahsaurrr_
      @dinahsaurrr_ 2 года назад

      Do you have a solution for this problem?

    • @ezrasenaputra8524
      @ezrasenaputra8524 2 года назад +1

      @@dinahsaurrr_ yess,
      using getServerSideProps and passing (context)
      get the jwt cookies from context.req.headers.cookie.

  • @tumon001
    @tumon001 2 года назад

    Awesome

  • @szerkan778
    @szerkan778 2 года назад +1

    Does anyone know how to solve this error? `Please use only absolute URLs`

    • @MrOogoo
      @MrOogoo 2 года назад

      Yes. Code below working.
      const url = req.nextUrl.clone();
      return NextResponse.redirect(`${url.origin}/login`);

  • @nicolaskondek5706
    @nicolaskondek5706 2 года назад

    crypto error dude

  • @idavidgeo
    @idavidgeo 2 года назад

    Hey man this is quite misleading. The routes are not protected. Only the pages in /dashboard are protected, in other words, only the client-side pages are protected. You need to verify the jwt in the api folder.

    • @idavidgeo
      @idavidgeo 2 года назад

      Also, process.env will be NULL in _middleware in production mode. It won't verify.

    • @tenacity_dev
      @tenacity_dev  2 года назад +2

      Yes of course token should also be verified when a request is sent, but that is kind of common thing done by everyone and i don't think i need to explain that. This video's focus is using the _middleware file.
      I already said it in the video i think, i'm not doing the full app, i'm just explaining concepts and ideas on how you can build things.

    • @tenacity_dev
      @tenacity_dev  2 года назад +2

      @@idavidgeo They can call next() when they see a token, and then verify it with getServerSideProps then. It's a pretty simple solution on how to verify it if they can't do it in _middleware.js file.

  • @bilalarain4632
    @bilalarain4632 2 года назад

    man you need to slow down speaking a little bit.

  • @dqampire
    @dqampire 2 года назад +1

    fix for absolute urls problem
    const domain = req.nextUrl.clone()
    domain.pathname = '/giris'
    return NextResponse.redirect(domain)

  • @ssj1260
    @ssj1260 2 года назад +2

    FIXING Node.js module (crypto) which is not supported in the Edge Runtime ERROR:
    Install jose (used instead of { verify } from jsonwebtoken, it doesnt work anymore)
    In _middleware:
    import * as jose from "jose";
    Replace his try with:
    try {
    console.log("trying to verify jwt");
    const verifying = await jose
    .jwtVerify(jwt, new TextEncoder().encode(`${secret}`))
    console.log("verifying", verifying);
    return NextResponse.next();
    }

    • @hectorsum8102
      @hectorsum8102 2 года назад

      Thanks bro. I encountered with this error now, how did you manage to fix it? I downgraded the version from 4.8.3 to 4.7.0, but still not working.
      I'm getting this response:
      { [JWSInvalid: Compact JWS must be a string or Uint8Array] code: 'ERR_JWS_INVALID', name: 'JWSInvalid' }

    • @ssj1260
      @ssj1260 2 года назад

      @@hectorsum8102 Hey man, never got that error, make sure you use TextEncoder().encode(`${secret}`)) and make sure your secret is a valid string. Make a temp variable for the secret (e.g. let temp = "hello" and use that in place of secret in TextEncoder().encode(`${temp}`)) and see if it works, and narrow it down from there.

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

    For anyone facing issues related to Edge-runtime try using *jose* or *jwt-decode* instead of *jsonwebtoken* for decoding the JWT.

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

      do you mean verify?

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

      @@CemretheFangirl *jwt-decode* is a small library and can only decode, can't validate JWT. Whereas if you have the secret, you will be able to validate the JWT using *jose* .

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

      No point in using middleware in next 13. It's way too slow, waiting for them to improve it in future versions.

  • @jonnyelbert6772
    @jonnyelbert6772 2 года назад

    Tools to get cc easy in yt leakfullz