Next.js Fetch Data the Right Way (with a Data Access Layer!) (Security, Auth, DTO)

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

КОМЕНТАРІ • 123

  • @nasko235679
    @nasko235679 4 місяці тому +85

    It's funny that the more things change, the more they stay the same. This is pretty much the MVC structure only in modern form.

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

      Reliable and trusted patterns in engineering work, no matter your stack. The easier the technology can be misused, the more often they eventually realize their design mistakes as well. I'd advise anyone to build a data access layer and enforce with static analysis that the DB can only be queried from there.

    • @TheKaosTux
      @TheKaosTux 4 місяці тому +7

      Not a modern form… just an new „name“ for a service or controller..

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

      @@TheKaosTux modern form

    • @AlexanderBelov-y8o
      @AlexanderBelov-y8o 4 місяці тому

      MVC never left.

    • @69k_gold
      @69k_gold 4 місяці тому

      Can you explain how this is MVC? In MVC architecture the controller, model and view are independent entities, view layer isn't supposed to even have the option to access the database, the data transfer only happens from view to controller and controller to model. But right now, he's just accessing the data from the db into his view layer directly, and just implementing a "recommendation" where he needs to tell every collaborator on the team to use the functions in the file instead of using the db directly. And the functions aren't even their own entity, they run within the view, which already breaks the MVC principle. I'm already disappointed by the stupid content I wasted my time on...

  • @universebot2363
    @universebot2363 4 місяці тому +36

    I would recommend throwing error if unauthenticated rather than handling the redirection in the DAL. The DAL does not really know where you are and where it makes sense to push the user to.

  • @simonmaluleka
    @simonmaluleka 4 місяці тому +13

    Layered Architecture right here. Uncle Bob’s clean architecture also addresses this very problem with solid principles and the separation of concerns 👌

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

      Clean architecture is very good, view layer being separate from domain layer and separate from infrastructure layer is a must

  • @zenious
    @zenious 4 місяці тому +3

    Awesome video ! Simple and crisp explanation 🔥

  • @rawarg
    @rawarg 4 місяці тому +7

    This is good approach for data security but for architecture you should also take consideration of DRY principle. You can create a custom hook for auth check or create an index for all your CRUD functions but there will be a helper for auth check that applies for all functions automatically. This will keep your code cleaner and maintainable in bigger size projects.

    • @makelebanon1
      @makelebanon1 29 днів тому

      hooks do not work on server side

    • @rawarg
      @rawarg 29 днів тому

      @makelebanon1 While that's true for React hooks, as they are specifically client-side concepts, what I meant by 'custom hook' here can also be seen as a reusable function or utility that can be shared across your server-side or backend codebase. It doesn't have to rely on React's use* pattern. The idea is to keep things DRY and centralize the auth logic in one place for maintainability. For example, on the server-side, you could create a helper function or middleware for authentication checks.

  • @kyngcytro
    @kyngcytro 4 місяці тому +2

    One of the many reasons why I love Vue/Nuxt is that there's a soft rule to not fetch data inside a component rather pass them as props. I know doing that opens the codebase to prop drilling but still feels better than having components making their own API calls.

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

      If you need data more than two layers from the call just use zustand and use state

  • @adel.dev.account
    @adel.dev.account 4 місяці тому +1

    Your tutorials are amazing
    I watched Prisma with next js and now this ❤

  • @sagecoder8802
    @sagecoder8802 4 місяці тому +7

    Please do a nextjs caching deep dive.

  • @GonçalojoséMoura
    @GonçalojoséMoura 4 місяці тому +1

    This might be a stretch but i love the way you explain things! Could you make a video on solid + clean architecture on a nextjs app?

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

    Request to make a videos on
    1. Fetch on render and Render on fetch. With examples
    2. Pagination on SSR pages with loading UI on page change

  • @ADHDOCD
    @ADHDOCD 4 місяці тому +11

    Hands down the best Next/React UA-camr! Unlike others, Wes goes over all the relevant details and takes no shortcuts in his pedagogical approach!
    In that you describe the problem in detail before using the solution makes it easy for a beginner like me to follow! God bless!

  • @AlexanderBelov-y8o
    @AlexanderBelov-y8o 4 місяці тому +2

    You are a true professional. Can you cover API route best practices? It has not yet been covered on your channel.

    • @ByteGrad
      @ByteGrad  4 місяці тому +2

      Thanks and good idea

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

    nice, i was doing much of that stuff allready, but without knowing their correct names, i like that DTO and DAL are real and common concepts 😅

  • @shumaslaghari7503
    @shumaslaghari7503 4 місяці тому +12

    Your tutorials are very useful. If possible, can we have a tutorial for express + next js with custom auth (access and refresh token)

    • @ByteGrad
      @ByteGrad  4 місяці тому +6

      Thanks! Good idea

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

      Yeah more like a real world application where the backend is separate

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

      I'm currently working on a Next.js + express project with custom auth and for some reason the http-only cookie will not be send the backend and I couldn't access the protected routes. If anyone knows a resource written on this topic, would be immensely helpful.

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

      why not use hono or the inbuilt nextjs apui routes

    • @DanielAzubuine
      @DanielAzubuine 3 місяці тому

      ​@@sulavbaral9972The trick around this is to build a custom fetch wrapper that sends along your access token

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

    Thinking about introducing the BAL? Business rules don't belong in the UI any more than data access, but noobs put all kinds of calcs and rules in their components. A Business Access Layer isolates rules so that they are consistent no matter the UI or API. Make a change in one place and the entire application uses it. This is the way we wrote backend systems in the first place and now that we're coming full circle again with server components it's appropriate to pull business logic out of the client interfaces and closer to the DAL.

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

      We build our Next/Node apps with both a "Data Layer" and a "Service Layer", the data layer contains the raw clients required for interaction with DBs, and the Service layer scales horizontally with modules linked to domain specific business requirements. The chief aim is to provide only a single API for retrieving specific data.

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

    Thanks for the helpful video 💯

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

    Thanks! That was very helpful

  • @davidbates3353
    @davidbates3353 4 місяці тому +5

    How would you handle the split between server-side queries and client-side queries? Separate file for each (article.ts and articleSSR.ts)?

    • @jenroot7875
      @jenroot7875 3 місяці тому

      I second this question.

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

    very useful video, I love your videos!

  • @FroggevPvp
    @FroggevPvp 3 місяці тому +1

    interesting stuff. will keep this in mind for when i get there.

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

    Thank you, very interesting and useful

  • @StanislausKatczinsky
    @StanislausKatczinsky 3 місяці тому +2

    Something that I don't understand in this video. DAL is supposed to deal only with data access and manipulation, why are we mixing authentication/authorization in this layer. This is going to add a lot of headache when it comes to authorization, you will have to mix all the access levels in in DAL which supposedly should not change that much unless your schema is changing. It seems like technical debt to me. Correct me if I am understanding this wrong.

  • @michaelkhalsa
    @michaelkhalsa Місяць тому +1

    If you are going to properly structure an application, then you have the data repository only accept and return DTO’s
    No business logic,such as creating a full name out of first and last, slug generation, etc. optimized joins are best done in this layer as well, as long as returns dtos.
    The data repository also has your lowest level of caching and invalidation, and checks permissions from the process caller, not the end user.
    It also abstracts the actual data stores used.
    Then you have a services layer which consumes the data repository’s, often from multiple sources. It shapes the data if needed, does user permission checks, and applies business logic where needed such as constructing a full name and returns models which might just be the same fields as the dtos, but might also be html, etc. You can also do language translation on this layer for messages.
    Finally, the front end consumes the services.

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

    Another helpful tutorial by you ❤

  • @paperC_CSGO
    @paperC_CSGO 2 місяці тому

    Have you considered creating a nextjs start template video like CJ did for Syntax? Would be interesting to compare the differences, for example I would think you would choose Prisma over Drizzle. Would love a 2-3 hour video of that!

  • @kovs-game
    @kovs-game 2 місяці тому

    Great Video ! You could also use NextSafeAction to call a server action and put the authentication in each call so you won't need to duplicate the check to each method in your DB access.

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

    Just in time I need it.

  • @praja.gautam
    @praja.gautam 4 місяці тому

    Excellent explanation❤

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

    This channel needs an extra million subscribers

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

    So are data access layer functions actions?

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

    How is this different from server actions?

  • @starlord7526
    @starlord7526 3 місяці тому +1

    Hello mate, I really like this video. Could you also make a video on how to stream data from back to front? meaning from API route to the frontend?

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

    thanks alot ,i want to know if i can use this concept in React?

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

    I love you, man. You're amazing!

  • @kevl7129
    @kevl7129 3 місяці тому

    As you mention, make the data access functions static methods on an (e.g.) 'Article' class and also make the auth check a static method, then you don't even need to repaste the auth logic in each function, it can be as short as this.checkAuth(). And accessing data in components looks neater..... Article.get(), Article.create()...

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

    At this point wouldn’t it make sense for Next to embrace the fact that it’s fully full stack and provide some built-in structure for this?

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

    Is there a difference using 'server-only' vs 'use server' ?
    18:00

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

      Hi, "use server"' is used in a react component for specify this is a component we will render on server, but where the server-only run is when your not in a react component but only in a ts/js file, so it's protected your method to be used in a client component, or used from the client

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

      @@remiguillard3773thats incorrect, use serve is a directive that tells next all exported asynchronous functions on that files to be trested as server actions. Each Server action functions basically can be threated as an api endpoint. If you calm a server action in tour code you will be making a post request to that endpoint.
      If you want a componenet to be rendered on the server you should only not put the use client directive and make sure the componenet is not imported by another componenet with use client.

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

    Thank you for the explanation. Can you please explain some ways to protect the POST requests as well using react query with nextjs 14. ? It would be of a great help. 🙇

  • @VthePeople4156
    @VthePeople4156 3 місяці тому

    Please do master class on complete JavaScript & react js in one hour

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

    I wasn't aware that it's called data access layer - kinda fancy term. I already do this for each schema and write my CRUD in that file only with kinde auth check.
    btw, do you know when kinde is gonna launch their payment solution?

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

      Should be soon

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

    why we don't use the auth check in server actions instead of creating data access separate file?

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

    This could be improved further by providing a withAuth() function that wraps those DB calls and throws if auth fails, that throw can then trigger the redirect(), this aids in providing only a single function to handle this aspect, and cuts down on the duplication.

  • @imkeyi
    @imkeyi 3 місяці тому

    would you recommand to learn remix

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

    Sounds like tRPC would be nice here. Its most recent version supports server actions.

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

    Or you could add a subroute like /private (could be any name) and protect the whole route in the middleware

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

    Is it safe to use isAuthenticated inside cache or any protection inside cache 19:03 ?

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

      Good question actually

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

    Have you tried next-safe-action?

  • @aymenbachiri-yh2hd
    @aymenbachiri-yh2hd 4 місяці тому +1

    Thank you

  • @mywaycoding6413
    @mywaycoding6413 4 місяці тому +2

    Love from Pakistan ❤ good work sir

  • @zmr-vn5hx
    @zmr-vn5hx 4 місяці тому

    What vs code theme are you using ?

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

    great video!

  • @UzielBueno-xd2ud
    @UzielBueno-xd2ud Місяць тому

    Hmm, I'm not convinced of mixing concerns in the data layer approach. By mixing concerns I mean that the code that fetches data from the store needs to know about authentication and routing, this couples the data layer to those other concerns

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

    why you create data-layer and implement a rule of access inside that?
    coupling prismaORM to your access data, what you think is a good deal?
    good pattern to create a DTO!

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

    Good work byte GRAD ❤

  • @toDev
    @toDev 3 місяці тому

    Is this the architecture I should aim for in Nextjs. I often use React and intend to learn NextJs. I just don't understand why access the database directly from the View instead of using the server for authentication and data access?

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

    How is this different from the /api routes?

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

    This is more about Auth than "why use fetch instead of Dal"

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

    After a point of time, as you keep adding more and more functionalities to your data-access layer, it just becomes another prisma. That's when you realize prisma itself is a data-access layer :) Inception much?

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

    the best solution i think for this case is t3 stack with next-auth and trpc

  • @John-eq5cd
    @John-eq5cd 4 місяці тому

    Any tips on libraries/tools to log who is accessing the database (17m 33s) ?

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

    Supabase has Row Level Security.

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

    So now instead of repeating the auth check in your components you are repeating it in functions? I feel that check should be done just once in the middleware

  • @HDSRosa
    @HDSRosa 3 місяці тому

    Your videos helped me a lot! but i have problems when i want to debug complex things. I find debugging more difficult in react than js vanilla because of the states and re-renders, so using debugger statement doesn't help much, maybe debugging using VS code debugger and checkpoints is more efficent for react?

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

    Is there any way of deploying a next js app to some server with proper middleware for auth, other than vercel?

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

      Middleware is not a feature unique to Vercel hosting; you can host Next JS on your own server / VPS and middleware will work for auth.

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

    What about fetching data in client component?

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

      We can use the server action functions inside client components too.
      Instead of API call simply get the data from sever action functions.

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

      Yes that’s possible but in next.js docs and many more articles its been said that use actions only for mutations, not for data fetching. Few reasons for these, first server actions use POST method for getting a data which doesn’t make sense. And also server actions executed sequentially

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

    Hey man, I don’t really know a lot about Next, so I have a question: Why not handle the authentication in the backend and only use a session cookie or jwt in the frontend? Also, what are some good sources to learn Next js as someone who is already familiar with react?

    • @matrinoxtm
      @matrinoxtm 3 місяці тому

      This is rendered on the server

  • @Lapatate-s1l
    @Lapatate-s1l 2 місяці тому +1

    We need new videoo mate !!!

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

    So, basically Controllers and Guards..

    • @jawyor-k3t
      @jawyor-k3t 4 місяці тому

      javascript community really loves to reinvent the wheel and market it as some kind of revolution/invention/innovation. Just circling around web standards and tons of marketing

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

    Isn't rest APIs designed to solve this DAL issue with a middleware at the route level? This looks like a new solution to and already solved problem coming with it's own problems.

  • @kim92se64
    @kim92se64 2 місяці тому +1

    Awesome !

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

    Why not put auth in layouts? I have an (auth) (public) and (main) folders in each project. Layout for main protects everything in main. (main)/api and (main)/actions for data fetching is also protected by auth in the root layout of the (main) folder.

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

      It’s a bad idea vercel says not to do that in their docs. Also in the same note don’t forget to secure server actions even you you protected their page.

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

    OR, you can just use next-safe-actions and its middleware method

  • @dolessaymore
    @dolessaymore 3 місяці тому

    We have come full circle. Inb4 everyone goes back to Java

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

    genuine question here, what's your personal preference for authentication / authorization? i recently decided to start a new project with keycloak and only do the role verification for routes on nextjs but i'm not completely sure about it, i should add that my backend is on a different service and not part of nextjs

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

    Can we video on how to generate reusable custom ui library using nextjs n mui ? Nextjs must bcoz want to take advantage of ssr ,,,, but use client directive making it hard as we end up writing csr n ssr ui components

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

    Caching in production has become incredibly annoying from version 14 onwards

  • @liu-river
    @liu-river 4 місяці тому

    I'd just stick with TRPC since I can easy control access by defining procedures.

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

    Repository pattern.

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

    So now NextJS is just Express + React on steroid?

  • @razorjhon2622
    @razorjhon2622 3 місяці тому

    there is a better way of doing this , by doing a layout component and wrap the whole components into this single layout page that contains /articles or dashboard

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

    This abstraction actually opens up a lot more questions than answers. Example: How to correctly identify types if you're using DTO's cuz u cannot take it from prisma now. How to do custom where, or other sql filters since the ORM is not directly accessible.

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

      I would say that this abstraction is good to have but would most likely affect your time to market a lot. So if you are just doing a side project just use the direct ORM access if you have to. You can always get a team and even rewrite the whole app if your product really gets traction.

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

    solid ka idol

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

    tanstack, tanstack, tanstack

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

    how to set http status after data fetch in next?
    const { data } = await fetch(...)
    if (condition) {
    // set http status
    }
    if the status can't be set then i think next is pretty useless framework

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

    OR WE CAN JUST RETURN A MINIMAL RESPONSE WITH THE THINGS ONLY WE NEED FROM THE BACKEND

  • @SachinKumar-qv8fj
    @SachinKumar-qv8fj 4 місяці тому

    this is just reusability in the name of DAL

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

    Smells like php

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

    Too much.