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

  Рет қаралды 28,414

ByteGrad

ByteGrad

Күн бұрын

Пікірлер: 96
@nasko235679
@nasko235679 13 күн бұрын
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 13 күн бұрын
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 13 күн бұрын
Not a modern form… just an new „name“ for a service or controller..
@cloudsss83
@cloudsss83 13 күн бұрын
@@TheKaosTux modern form
@AlexanderBelov-y8o
@AlexanderBelov-y8o 12 күн бұрын
MVC never left.
@69k_gold
@69k_gold 11 күн бұрын
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...
@simonmaluleka
@simonmaluleka 12 күн бұрын
Layered Architecture right here. Uncle Bob’s clean architecture also addresses this very problem with solid principles and the separation of concerns 👌
@devinlauderdale9635
@devinlauderdale9635 3 күн бұрын
Clean architecture is very good, view layer being separate from domain layer and separate from infrastructure layer is a must
@rawarg
@rawarg 2 күн бұрын
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.
@universebot2363
@universebot2363 13 күн бұрын
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.
@ByteGrad
@ByteGrad 13 күн бұрын
Good point
@ADHDOCD
@ADHDOCD 13 күн бұрын
Hands down the best Next/React KZbinr! 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!
@ByteGrad
@ByteGrad 13 күн бұрын
Thanks
@AlexanderBelov-y8o
@AlexanderBelov-y8o 12 күн бұрын
You are a true professional. Can you cover API route best practices? It has not yet been covered on your channel.
@ByteGrad
@ByteGrad 11 күн бұрын
Thanks and good idea
@sagecoder8802
@sagecoder8802 12 күн бұрын
Please do a nextjs caching deep dive.
@shahrozahmed9746
@shahrozahmed9746 13 күн бұрын
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
@tonyg_nerd
@tonyg_nerd 9 күн бұрын
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 8 күн бұрын
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.
@Devlicious-m3r
@Devlicious-m3r 13 күн бұрын
Your tutorials are amazing I watched Prisma with next js and now this ❤
@zenious
@zenious 13 күн бұрын
Awesome video ! Simple and crisp explanation 🔥
@shumaslaghari7503
@shumaslaghari7503 13 күн бұрын
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 13 күн бұрын
Thanks! Good idea
@sulavbaral9972
@sulavbaral9972 13 күн бұрын
Yeah more like a real world application where the backend is separate
@finetopethiopia4095
@finetopethiopia4095 13 күн бұрын
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 13 күн бұрын
why not use hono or the inbuilt nextjs apui routes
@tomich20
@tomich20 13 күн бұрын
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 😅
@davidbates3353
@davidbates3353 12 күн бұрын
How would you handle the split between server-side queries and client-side queries? Separate file for each (article.ts and articleSSR.ts)?
@itsfarookmayne
@itsfarookmayne 12 күн бұрын
This channel needs an extra million subscribers
@GonçalojoséMoura
@GonçalojoséMoura 12 күн бұрын
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?
@kyngcytro
@kyngcytro 13 күн бұрын
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 13 күн бұрын
If you need data more than two layers from the call just use zustand and use state
@manojpudasaini1565
@manojpudasaini1565 12 күн бұрын
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. 🙇
@chriseagle1889
@chriseagle1889 8 күн бұрын
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.
@ozgursar5386
@ozgursar5386 12 күн бұрын
Thanks for the helpful video 💯
@aymenbachiri-yh2hd
@aymenbachiri-yh2hd 12 күн бұрын
Thank you
@podobayka
@podobayka 13 күн бұрын
Thanks! That was very helpful
@thebocksters2756
@thebocksters2756 13 күн бұрын
very useful video, I love your videos!
@victorbiasibetti
@victorbiasibetti 12 күн бұрын
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!
@dinhkhanh
@dinhkhanh 12 күн бұрын
Just in time I need it.
@ahmedbadran.
@ahmedbadran. 21 сағат бұрын
Is a DAL the walkaround for issues of this type?
@nogafouz2174
@nogafouz2174 12 күн бұрын
thanks alot ,i want to know if i can use this concept in React?
@mmmhbarcelona4560
@mmmhbarcelona4560 13 күн бұрын
Another helpful tutorial by you ❤
@modiddymo
@modiddymo 12 күн бұрын
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?
@mywaycoding6413
@mywaycoding6413 13 күн бұрын
Love from Pakistan ❤ good work sir
@aqbgaming7656
@aqbgaming7656 13 күн бұрын
❤❤❤ Love from IOK bro.
@estebanmurcia8451
@estebanmurcia8451 12 күн бұрын
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
@ohskynyrdlynyrd
@ohskynyrdlynyrd 13 күн бұрын
Or you could add a subroute like /private (could be any name) and protect the whole route in the middleware
@wealthassistant
@wealthassistant 13 күн бұрын
Sounds like tRPC would be nice here. Its most recent version supports server actions.
@mihailobush946
@mihailobush946 19 сағат бұрын
So are data access layer functions actions?
@2gbeh
@2gbeh 12 күн бұрын
So, basically Controllers and Guards..
@jawyor-k3t
@jawyor-k3t 7 күн бұрын
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
@praja.gautam
@praja.gautam 13 күн бұрын
Excellent explanation❤
@liu-river
@liu-river 13 күн бұрын
I'd just stick with TRPC since I can easy control access by defining procedures.
@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.
@user-xs4th5rm6w
@user-xs4th5rm6w 13 күн бұрын
the best solution i think for this case is t3 stack with next-auth and trpc
@zmr-vn5hx
@zmr-vn5hx 23 сағат бұрын
What vs code theme are you using ?
@mrpx77
@mrpx77 8 күн бұрын
Have you tried next-safe-action?
@IkraamDev
@IkraamDev 13 күн бұрын
Supabase has Row Level Security.
@atharvmishra884
@atharvmishra884 13 күн бұрын
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?
@therealsharat
@therealsharat 13 күн бұрын
How is this different from the /api routes?
@investneur8232
@investneur8232 8 күн бұрын
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
@insensibility
@insensibility 13 күн бұрын
I love you, man. You're amazing!
@hehe3323
@hehe3323 13 күн бұрын
great video!
@moritz759
@moritz759 13 күн бұрын
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?
@htk0002
@htk0002 12 күн бұрын
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 12 күн бұрын
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.
@jagdish1o1
@jagdish1o1 13 күн бұрын
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 13 күн бұрын
Should be soon
@Monstermash355
@Monstermash355 13 күн бұрын
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
@VincentFulco
@VincentFulco 11 күн бұрын
Caching in production has become incredibly annoying from version 14 onwards
@ssygon2
@ssygon2 13 күн бұрын
Is there a difference using 'server-only' vs 'use server' ? 18:00
@remiguillard3773
@remiguillard3773 12 күн бұрын
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 9 күн бұрын
@@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.
@MerthanMerter
@MerthanMerter 13 күн бұрын
OR, you can just use next-safe-actions and its middleware method
@richienguyen2703
@richienguyen2703 13 күн бұрын
So now NextJS is just Express + React on steroid?
@naranyala_dev
@naranyala_dev 12 күн бұрын
tanstack, tanstack, tanstack
@TripHawkPilot
@TripHawkPilot 13 күн бұрын
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 13 күн бұрын
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.
@aaronseaton7320
@aaronseaton7320 10 күн бұрын
Repository pattern.
@anantjoshi2269
@anantjoshi2269 13 күн бұрын
Good work byte GRAD ❤
@dae2530
@dae2530 10 күн бұрын
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
@lohitnimbagal4653
@lohitnimbagal4653 13 күн бұрын
Is it safe to use isAuthenticated inside cache or any protection inside cache 19:03 ?
@ByteGrad
@ByteGrad 13 күн бұрын
Good question actually
@aqbgaming7656
@aqbgaming7656 13 күн бұрын
Is there any way of deploying a next js app to some server with proper middleware for auth, other than vercel?
@Innesb
@Innesb 11 күн бұрын
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.
@justin9494
@justin9494 13 күн бұрын
solid ka idol
@cant_sleeeep
@cant_sleeeep 13 күн бұрын
OR WE CAN JUST RETURN A MINIMAL RESPONSE WITH THE THINGS ONLY WE NEED FROM THE BACKEND
@madatbay
@madatbay 13 күн бұрын
What about fetching data in client component?
@jagdish1o1
@jagdish1o1 13 күн бұрын
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 12 күн бұрын
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
@SachinKumar-qv8fj
@SachinKumar-qv8fj 10 күн бұрын
this is just reusability in the name of DAL
@oksdoksaodkad
@oksdoksaodkad 13 күн бұрын
Too much.
@anuragkush831
@anuragkush831 8 күн бұрын
Smells like php
This might change how we build UI forever
15:14
Theo - t3․gg
Рет қаралды 109 М.
Why I don't use React-Query and tRPC in Next.js
18:58
ByteGrad
Рет қаралды 88 М.
Or is Harriet Quinn good? #cosplay#joker #Harriet Quinn
00:20
佐助与鸣人
Рет қаралды 53 МЛН
Je peux le faire
00:13
Daniil le Russe
Рет қаралды 18 МЛН
Node.js Doesn’t Suck Anymore
16:59
Web Dev Simplified
Рет қаралды 87 М.
10 common mistakes with the Next.js App Router
20:37
Vercel
Рет қаралды 212 М.
Setting up a production ready VPS is a lot easier than I thought.
29:50
The BEST way to host Next.js websites
17:37
ByteGrad
Рет қаралды 43 М.
React's most dangerous feature
26:37
Theo - t3․gg
Рет қаралды 53 М.
Why did OpenAI move from Next.js to Remix?
10:41
Wes Bos
Рет қаралды 118 М.
Multi-Tenant SaaS Architecture (Next.js Auth)
22:57
ByteGrad
Рет қаралды 20 М.
All 17 React Best Practices (IMPORTANT!)
1:46:11
ByteGrad
Рет қаралды 133 М.
You don't need a frontend framework
15:45
Andrew Schmelyun
Рет қаралды 122 М.