How to Protect Routes in Next.js 14 in 4 Ways - Private Routes - Authorization

Поділитися
Вставка
  • Опубліковано 3 лют 2025

КОМЕНТАРІ • 64

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

    man i just watched this video along with your other tutorials and all i can say is that you explain it very well and very informative. you have gain a subscriber in me, keep it up and thank you for sharing your knowledge

  • @aryank-b1t
    @aryank-b1t 11 місяців тому +1

    best video on youtube explaining public and private routing with next.js. Thank you brother. Great help!!

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

    Bro 😂 more than 10 tutorials without any solution , and you in one video fix my whole problem with authorization love you bro

  • @이민우-k4j
    @이민우-k4j Рік тому +1

    Thank you. I searched before writing the auth code and saw it and it was so beneficial!

  • @rajaravi1037
    @rajaravi1037 Місяць тому

    It is my bad that I didn't see this video earlier. Man you solved many problems in less than 30min..

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

    Best video about protected routes in nextjs on youtube! 👏👏

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

    thanks mate!! your examples has perfect to understand and very simple to apply.

  • @birkbirk1204
    @birkbirk1204 4 місяці тому

    that was my 15th video maybe, just wanted to use only server side, thanks a lot brother

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

    Thank you, man! This kind of content is very helpful, u know, showing many ways of doing the same thing, It's incredible, 'cause most of the time, we have to adapt our solution or one works very well but one doesn't, I hope for content like this. One more subscriber!

  • @AyanGhosh-vj7ui
    @AyanGhosh-vj7ui 10 місяців тому +1

    but in realword project session or logged in state in not stored in a file
    then how to do this? like I have stored jwt token in localstorage
    Can you help me?

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

    Very well explained. Thank you for this tutorial. Keep it up.

  • @LUAN-mw9tl
    @LUAN-mw9tl 4 місяці тому

    Muito bom seu tutorial, ensina vários modos de autenticação em 1 vídeo só e a didática perfeita...❤

  • @RitikRaj-we2sc
    @RitikRaj-we2sc 5 місяців тому

    isn't redirect() only used in server components ?
    Can you please explain this

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

    how would you protect a dynamic route using the middlware

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

    i have issue with the last one authentication . how do you manage to protect dynamic route eg 'user/id'

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

    And how to change the variable sessionStatus for example after successful login. Because I want to let user use these routes after login.

  • @sagarmusic0798
    @sagarmusic0798 7 місяців тому

    Hi, you are reading sessionStatus from a hardcoded variable from another file, could anyone please tell me how to read variable like sessionStatus from redux, though i know redux is client side store and middleware run on server, but is there any other way to check if user is already logged in in case of real authentication system

  • @trananh4894
    @trananh4894 7 місяців тому

    can i check token in middleware??

  • @sahilsaksena3199
    @sahilsaksena3199 7 місяців тому

    sir can we use middleware to protect client components as well

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

    Hello ! I have a question, i have a fetch that needs authorization headers for the backend, and when i try to build my next js project, it gives me an error because the api call fails. What can i do in this cases?

  • @mohammedfaris9196
    @mohammedfaris9196 6 місяців тому

    Nice video, Great job sir 🎉

  • @SouravSaha-u1b
    @SouravSaha-u1b Рік тому

    Thank you man, Great job.

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

    I have a question!
    In the withAuth hook, why did you return a function called WithAuth inside the withAuth hook !!?

    • @alexeyfedorovich9769
      @alexeyfedorovich9769 7 місяців тому

      because any HOC should return Component that wraps your target component. That's why we have WithAuth Component and its name starts with capital letter which is typical characteristic of all the components)

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

    tnku so much appreciate your content

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

    Very good tutorial, but how to link it with the next-auth i.e. how to get session details in a first place?

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

    Can I use this with redux toolkit and check if isAuth state set to false protect my route else not protect it like I do in react?

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

    example
    I access to localhost:3000/dashboard
    but the sessionStatus = false
    so it will redirect(localhost:3000/)
    but it try to render dashboard page before it check sessionStatus ? so is there any way around to check sessionStatus first if sessionStatus == false -> redirect back to ('/') else go to '/dashboard'

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

      Hi, as shown in the video.
      It won’t happen on server components. Or you can do it using HOC as shown in the video.

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

      I use server side@@ProgrammingwithUmair321

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

      I try to write url query to pass not click button like that@@ProgrammingwithUmair321

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

      I do something like this localhost:3000/dashboard -> it will display loading screen + my navbar before it redirect back to login screen @@ProgrammingwithUmair321

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

    how to protect all page routes without writing all routes one by one in middleware? like: const protectedRoutes = ["/", "/clientside","/middlewareside"] is that possible? and change root routes with /clientside when running npm run dev

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

    very good tutorial with simple and straight forward example. There are some tutorials around that the person put so many not important things around the theme he wants to teach that makes the understanding of the theme just too complex. Not you. Very straight forward.

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

    Many Thanks. Subscribed

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

    Thank you for this tutorial. Can I check if the session is available in the layout which automatically checks every time a page is called? is this a good practice?

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

    Can I make an api request in the middleware.ts file to get current user instead of getting it from next-auth

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

      you can do api requests inside middleware, but beware: they will slow down the rendering of all affected pages. You have to be sure you only affect necessary routes and only in cases when you can't do API calls from your client components.

  • @edgardejesusmendozaortegon7655

    great video, great explication!!!!

  • @lizard-wizard3205
    @lizard-wizard3205 10 місяців тому

    its good tut. its clear and strait forward. the only thing I find missing is the use of typescript. you use everywhere type any. thats a shame. good luck brother

  • @RassakVk
    @RassakVk 6 місяців тому

    Which one best?

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

    Amazing content

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

    I am following all your videos , it’s very informative ❤️. Can you also make one video about how to make a micro front ends with next 13.4+ . I haven’t seen any such videos anywhere .

  • @chi-mf1cx
    @chi-mf1cx Рік тому +1

    very nice bro, I want a tut on using middleware with next auth but I the catch is I want multiple middlewares like one for auth and one for something else, hope you understand

  • @muhammadshehroze6691
    @muhammadshehroze6691 5 місяців тому

    Good explanation! Can you share github repo?

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

    Thank you.

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

    implementation of middleware is nor 100% correct. NextJs provides a dedicated variable for comparing route names. Please use that

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

    hi dev this process is too god but if i using next auth this all methods are useless i cant use this please make a separate video about this using next auth its my humble request

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

    Congratulations on the video!
    I would like to ask a question, is it possible to protect a group of example routes (folder)?
    Let's say I have a group of routes like:
    (public)
    - Home
    - About
    (private)
    - Dashboard
    -Users
    If possible, what is the best approach? Using middleware?

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

      you can just pass the private routes in an array and check if the array includes the route you are visiting

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

      this is not the appropriate way to do it, you can create layout file where you pas all the children, you check if session is true if not redirect them, its simple just 4 lines of code,@@void_int

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

    I try to use with user login and get cookie can you help me

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

      Can you plz share some code? How are to storing cookie and using it for protecting routes?

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

      @@ProgrammingwithUmair321
      in login page
      const [email, setEmail] = useState("");
      const [password, setPassword] = useState("");
      const router = useRouter();
      const handleSubmit = async (e: React.FormEvent) => {
      e.preventDefault();
      try {
      const response = await fetch("api", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email, password }),
      });
      const data = await response.json();
      console.log(data.data.accessToken);
      if (data.data.accessToken) {
      Cookie.set("token", data.data.accessToken, {
      path: "/",
      expires: 7,
      });
      }
      if (response.ok) {
      router.push("/dashboard");
      }
      } catch (err) {
      console.log(err);
      }
      };
      in uitils/session.ts
      import Cookie from "js-cookie";
      export const sessionStatus = () => {
      return !!Cookie.get("token");
      };
      and I want to protect my dashboard
      import { sessionStatus } from "@/utils/session"
      import { redirect } from "next/navigation";
      const Dashboard = () => {
      const session = sessionStatus();
      if (!session) {
      redirect("/");
      }

      return Dashboard;
      };
      export default Dashboard;

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

      @@ProgrammingwithUmair321 I want to set if we have cookie so we can access dashboard page like that

  • @Sandeep-bx7rg
    @Sandeep-bx7rg Рік тому

    Thanks bro

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

    Hi Umair, can you please make some tutorials for Spring boot + React Project with Microservice Architecture. As there are not many end to end project tutorials on the internet , it will really be helpful.

  • @vijayverma.ameotech
    @vijayverma.ameotech 4 місяці тому

    👍👍👍