Next.js Middleware Crash Course || App Router Protected Routes

Enjoy my videos & teaching? Join tapaScript as a member:
/ @tapasadhikary
Do you find Next.js Middleware difficult to understand, and challenging to use? Here is a crash course for you where you will learn:
- What is middleware?
- The app structure
- Create a middleware
- What is a matcher?
- Middleware and Route handlers
- Auth in middleware: The problem
- Auth Config - The solution
- Declaring private and protected routes
- Handling protected and public routes in middleware
- Protecting subroutes in middleware
- Oauth providers(Google, GitHub) and middleware
- Protecting API routes
Finally, a task for you to implement how an admin alone can access the dashboard after authentication. Let's GO 🚀
- Catch up with the previous video on Persisting Users to DB: • Next.js Authentication...
Hey, welcome back to another informative video from the "Full Stack With Next.js App Router" series. I hope you enjoy this one the same way you liked the previous videos from the series.
I take special care to provide you the best quality content. Please SUBSCRIBE to the channel to show your support. Also, could you like/comment on this video so that it reaches others? Thanks! 🫶
Timecodes
0:00 - We Will Learn These
01:26 - What is middleware?
05:58 - The app structure
16:51 - Create a middleware
20:10 - What is a matcher?
24:57 - Middleware and Route handlers
26:09 - Auth in middleware: The problem
31:13 - Auth Config - The solution
36:21 - Declaring private and protected routes
39:13 - Handling protected and public routes in middleware
47:40 - Protecting subroutes in middleware
50:30 - Oauth providers(Google, GitHub) and middleware
52:54 - Protecting API routes
59:46 - What's Next?
Videos mentioned:
- • JavaScript Object Dest...
- • Do We Need These JavaS...
Source Code on tapaScript GitHub:
- github.com/tapascript/learn-n... (If you like, please support the project with a ⭐)
Join tapaScript
- Join tapaScript as a member: / @tapasadhikary
- Join Discord: / discord
🤝 My Links:
- Blog: blog.greenroots.info/
- Follow on X(Twitter): / tapasadhikary
- Connect on LinkedIn: / tapasadhikary
- Follow My Work on GitHub: github.com/atapas
- Follow on Facebook: / tapasadhi
Special Links:
- If you are looking for the best content management system, here is something for FREE that you can rely on: app.caisy.io/app/signup/mwiyy...
👋 Like my work? Thank You. You can sponsor me from here:
- Sponsor Me: github.com/sponsors/atapas
- Sponsor my Blog: blog.greenroots.info/sponsor
About Me:
Tapas Adhikary is an Educator at tapaScript, Tech enthusiast, Writer, KZreadr, and Open Source projects maintainer/contributor. He is a full-stack developer with vast experience in building SaaS solutions. He is the founder of the ReactPlay platform, which is driven by open-source projects and a fast-growing community.
You can find more about him at tapasadhikary.com.
#nextjstutorial
#next
#nextjs14
#nextauth
#authentication
#nextjs
#nextjs13
#nextjsapprouter
#thinkinginnextjs
#nextjstutorial
#next-auth
#authjs
#middleware

Пікірлер: 59

  • @shadiflo
    @shadiflo9 күн бұрын

    I have been watching a lot of videos on how to setup properly auth , all of them are so overcomplicated for no reason , Your videos are so straightforward , Keep up the awesome work!

  • @tapasadhikary

    @tapasadhikary

    9 күн бұрын

    @@shadiflo super, thanks! ❤️

  • @suvasispatra6389
    @suvasispatra6389Ай бұрын

    Just loving your content

  • @tapasadhikary

    @tapasadhikary

    Ай бұрын

    Thanks a lot ❤️

  • @i_m_phoenix87
    @i_m_phoenix87Ай бұрын

    Sir your videos are GEM !! . I can't thank you enough , You made me learn about Next Auth and Middlewares in a very smooth way and I really look forward to follow your upcoming videos whether it is about Next JS concepts or Project Videos. I will do them all. I hope you grow fast and I expect a lot from you sir . Lots of love

  • @tapasadhikary

    @tapasadhikary

    Ай бұрын

    🙏🙏❤️❤️ thanks a lot for wishes and your comments made my day.

  • @steffenjusmann6276
    @steffenjusmann6276Ай бұрын

    Been waiting for this one hahaha - and hope the next video will come soon :)

  • @tapasadhikary

    @tapasadhikary

    Ай бұрын

    haha... now that's a pressure on me 😄

  • @steffenjusmann6276

    @steffenjusmann6276

    Ай бұрын

    @@tapasadhikary hahaha. After watching the video I wanted to give you some input. I would love to see this becoming a full project!! Especially using shadcn, role based authentification, some CRUD interactions with a DB collection and maybe Stripe, so that one could build out a SAAS and accept payments. Here is an idea on what this project could look like (if you don't already have something in mind): Scenario: We are building a service for book clubs where multiple book clubs can subscribe to different libraries, and each book club can have multiple members with different roles and permissions (e.g., admin, member). Each member can also be part of multiple book clubs. Explanation: 1. Book Clubs Collection: • Stores information about each book club, including their subscription details for different libraries and the members who belong to these book clubs. • Each book club has a unique ID, a name, and a Stripe customer ID for payment processing. It also includes a list of members with their assigned roles (e.g., admin, member). 2. Members Collection: • Stores information about each member, including their personal details and the book clubs they are associated with. • Each member has a unique ID, name, email, password, and a list of book clubs they manage or belong to, along with their roles in those book clubs. 3. Libraries Collection: • Stores information about each library available for subscription. • Each library has a unique ID, a name, address, contact details, and a Stripe product ID for the subscription. Only admins of book clubs can manage the subscriptions or change details for the specific subscriptions of their book clubs. There could be a "User Dashboard" for each user where they can see a list of all the book clubs they are part of and a "Book Club Dashboard" where one can see all the libraries this book club has access to (on this page we could also fetch a list of books from the library's API and display it). A person can register a new book club (where he will be the SuperAdmin), invite other people to his book club using e.g. their email and manage their roles. I hope you could somewhat follow this explanation and get the idea I am going for. (I just thought of that structure and don't know if it makes sense the way I described it hahaha)

  • @tapasadhikary

    @tapasadhikary

    Ай бұрын

    @@steffenjusmann6276 Thank you! It makes complete sense to me. In fact, I have a few similar ideas. I plan to start with smaller projects and then gradually bigger ones. I have now noted your project idea too 😀

  • @RABINGURUNG-em1yi
    @RABINGURUNG-em1yiАй бұрын

    thank you i learned a lot

  • @tapasadhikary

    @tapasadhikary

    Ай бұрын

    Excellent 🙏

  • @abdullahalmuzahid2473
    @abdullahalmuzahid2473Ай бұрын

    Very informative video, thanks for sharing with us..

  • @tapasadhikary

    @tapasadhikary

    Ай бұрын

    Thanks a lot ❤️

  • @MohiuddinMehedi-l7w
    @MohiuddinMehedi-l7w11 күн бұрын

    super

  • @tapasadhikary

    @tapasadhikary

    11 күн бұрын

    ❤️❤️

  • @ericsiddiq7634
    @ericsiddiq7634Ай бұрын

    Take love dada ❤️❤️❤️

  • @tapasadhikary

    @tapasadhikary

    Ай бұрын

    You too ❤️

  • @sohaibabdullah9073
    @sohaibabdullah9073Ай бұрын

    Cool dada

  • @tapasadhikary

    @tapasadhikary

    Ай бұрын

    Thanks vai

  • @mfmanca2006
    @mfmanca2006Ай бұрын

    A suggestion for a next video... The topic of i18n an app with auth v5 is quite interesting (you need to mix two middlewares into one...)

  • @tapasadhikary

    @tapasadhikary

    Ай бұрын

    Yep, it’s in my mind too… so why I gave an intro of middleware before doing an i18n video. Thanks a lot for your suggestions

  • @sogobamimore8933
    @sogobamimore893317 күн бұрын

    when splitting up the code sir, I understand that we need to pass in a shallow config inside the nextAuth. But how then do we get the legit session from auth() since we passed in a shallow config file that doesn't have the providers?

  • @harshkhasgiwale2709
    @harshkhasgiwale2709Ай бұрын

    Please make a video on Server and Client Components,along with Server actions🙏🙏

  • @tapasadhikary

    @tapasadhikary

    Ай бұрын

    In radar

  • @ProgrammerArif
    @ProgrammerArifАй бұрын

    ❤‍🔥❤💥

  • @tapasadhikary

    @tapasadhikary

    Ай бұрын

    ❤️❤️❤️

  • @mfmanca2006
    @mfmanca2006Ай бұрын

    Great content, thank you. In my app I don't have any public route and I'm using keycloak as a provider. I haven't understood how can I redirect to the keycloak login page everytime the auth.user is null. Do you know if we can build the keycloak login url to redirect to in our Middleware? The examples I've found online always show how to do it on the click of a Login button or url

  • @syketb

    @syketb

    Ай бұрын

    Hi there, I believe I have the solution to your queries. You have the Keycloak login URL, and there is an API to check if auth.user is null or not. It's simple: if your route is protected and auth.user is null, you can use a next redirect function to send users to the Keycloak login page. That's how you can achieve this behavior.

  • @mfmanca2006

    @mfmanca2006

    Ай бұрын

    It's not that simple. Since we are using openid-connect, the url contains several variables that are generated following the protocol. AuthV5 hides all this behind the code of the "signIn('keycloak')" function but I cannot call it in the middleware

  • @syketb

    @syketb

    Ай бұрын

    @@mfmanca2006 Okay, maybe in your case its bit different, cause when I worked on that, I had very straight forward signing link like: "localhost:8080/realms/master/protocol/openid-connect/auth?client_id=myclient" and I can use this link to redirect keycloak signing page, based on my user authentication.

  • @MrCakil99Sindycate-uv6do
    @MrCakil99Sindycate-uv6doАй бұрын

    please about refresh token if we have our own api 🙏

  • @tapasadhikary

    @tapasadhikary

    Ай бұрын

    I’m building that app

  • @evansensteen7000
    @evansensteen700011 күн бұрын

    lets hope this video will be able to explain this problem >> Error: Clerk: auth() was called but Clerk can't detect usage of clerkMiddlew are() (or the deprecated authMiddleware()). Please ensure the following: - clerkMiddleware() (or the deprecated authMiddleware()) is used in your Next. js Middleware. - Your Middleware matcher is configured to match this route or page.

  • @shahabulalam8803
    @shahabulalam8803Ай бұрын

    what if I want to make this route as public "/products/[productId]" how do we do that?

  • @tapasadhikary

    @tapasadhikary

    Ай бұрын

    That's already shown and taken care in the code using the startsWith function. Everything startsWith products will work.

  • @shahabulalam8803

    @shahabulalam8803

    Ай бұрын

    @@tapasadhikary thanks lot for nice tutorial

  • @sadhondas1512
    @sadhondas1512Ай бұрын

    can i write multiple middleware and multiple matcher?

  • @tapasadhikary

    @tapasadhikary

    Ай бұрын

    Replied above

  • @user-vf8bd3mm5n
    @user-vf8bd3mm5nАй бұрын

    Can you do a video about jwt access token and refresh token in nextauth credentials?

  • @tapasadhikary

    @tapasadhikary

    Ай бұрын

    I have started on it and stuck on one point to decrypt the access token.. the sooner I fix that, I will create a video. Stay tuned.

  • @user-vf8bd3mm5n

    @user-vf8bd3mm5n

    Ай бұрын

    @@tapasadhikary I'm looking forward for that video. Btw, do you think it is still okay to use credential providers without access token and refresh token even if it is only a portfolio project? I'm wondering if that would be an issue if I apply for a job and show them my fullstack project.

  • @tapasadhikary

    @tapasadhikary

    Ай бұрын

    Yeah yeah just encrypting password not enough for real life app… for portfolio it’s still ok IMO… what kind of interview you are planning? Years of experience?

  • @user-vf8bd3mm5n

    @user-vf8bd3mm5n

    Ай бұрын

    I don't have prior working experience related to web dev so my goal is to land a job as a jr. frontend dev or any entry level web dev job. I'm worried that my skills are not good enough to land a job.

  • @tapasadhikary

    @tapasadhikary

    Ай бұрын

    @user-vf8bd3mm5n the only tips I can give is do practice and do a planned one. Worrying about not having skills will not increase it. You need to practice and build things… as many as you can. That build skill.

  • @mahmudulhasannayeem6350
    @mahmudulhasannayeem6350Ай бұрын

    how user redirect to buy page after login? 49:16

  • @tapasadhikary

    @tapasadhikary

    Ай бұрын

    After login user can go to any pages without any restrictions… the restriction we are putting inside middleware only for non authenticated users for accessing protected(non public) routes. Hope it is clear 🙌

  • @najmulislamnaeem2688
    @najmulislamnaeem2688Ай бұрын

    Dada please a tutorial for Uploading image like Cloudinary with NextJs

  • @tapasadhikary

    @tapasadhikary

    Ай бұрын

    Yes, I want to do a project with cloudinary, not only upload but also to use their API functions.

  • @rationalindianguy
    @rationalindianguyАй бұрын

    Sir Please make React Js Course

  • @tapasadhikary

    @tapasadhikary

    Ай бұрын

    I already have a reactjs series, sir… please check

  • @Besaoct
    @BesaoctАй бұрын

    Not working in production.

  • @tapasadhikary

    @tapasadhikary

    Ай бұрын

    What error do you get and what doesn't work? Where do you deploy? Whats the edge configuration?

  • @UwU-dx5hu
    @UwU-dx5huАй бұрын

    caching please

  • @tapasadhikary

    @tapasadhikary

    Ай бұрын

    Do you want to learn caching?

  • @sadhondas1512
    @sadhondas1512Ай бұрын

    can i write multiple middleware and multiple matcher?

  • @tapasadhikary

    @tapasadhikary

    Ай бұрын

    Great question! It is advisable to have one middleware and export import the functionalities in the different files. This is what the Next.js documentation says: "While only one middleware.ts file is supported per project, you can still organize your middleware logic modularly. Break out middleware functionalities into separate .ts or .js files and import them into your main middleware.ts file. This allows for cleaner management of route-specific middleware, aggregated in the middleware.ts for centralized control. By enforcing a single middleware file, it simplifies configuration, prevents potential conflicts, and optimizes performance by avoiding multiple middleware layers."