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.
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...
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.
Layered Architecture right here. Uncle Bob’s clean architecture also addresses this very problem with solid principles and the separation of concerns 👌
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 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.
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.
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!
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.
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.
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.
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.
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.
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!
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.
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()...
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
@@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.
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. 🙇
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?
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.
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
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!
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?
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?
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
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?
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
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?
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
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.
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.
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.
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
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
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
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.
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.
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
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.
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.
Not a modern form… just an new „name“ for a service or controller..
@@TheKaosTux modern form
MVC never left.
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...
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.
Good point
Layered Architecture right here. Uncle Bob’s clean architecture also addresses this very problem with solid principles and the separation of concerns 👌
Clean architecture is very good, view layer being separate from domain layer and separate from infrastructure layer is a must
Awesome video ! Simple and crisp explanation 🔥
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.
hooks do not work on server side
@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.
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.
If you need data more than two layers from the call just use zustand and use state
Your tutorials are amazing
I watched Prisma with next js and now this ❤
Please do a nextjs caching deep dive.
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?
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
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!
Thanks
You are a true professional. Can you cover API route best practices? It has not yet been covered on your channel.
Thanks and good idea
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 😅
Your tutorials are very useful. If possible, can we have a tutorial for express + next js with custom auth (access and refresh token)
Thanks! Good idea
Yeah more like a real world application where the backend is separate
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.
why not use hono or the inbuilt nextjs apui routes
@@sulavbaral9972The trick around this is to build a custom fetch wrapper that sends along your access token
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.
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.
Thanks for the helpful video 💯
Thanks! That was very helpful
How would you handle the split between server-side queries and client-side queries? Separate file for each (article.ts and articleSSR.ts)?
I second this question.
very useful video, I love your videos!
interesting stuff. will keep this in mind for when i get there.
Thank you, very interesting and useful
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.
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.
Another helpful tutorial by you ❤
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!
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.
Just in time I need it.
Excellent explanation❤
This channel needs an extra million subscribers
So are data access layer functions actions?
How is this different from server actions?
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?
thanks alot ,i want to know if i can use this concept in React?
I love you, man. You're amazing!
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()...
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?
Is there a difference using 'server-only' vs 'use server' ?
18:00
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
@@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.
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. 🙇
Please do master class on complete JavaScript & react js in one hour
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?
Should be soon
why we don't use the auth check in server actions instead of creating data access separate file?
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.
would you recommand to learn remix
Sounds like tRPC would be nice here. Its most recent version supports server actions.
Or you could add a subroute like /private (could be any name) and protect the whole route in the middleware
Is it safe to use isAuthenticated inside cache or any protection inside cache 19:03 ?
Good question actually
Have you tried next-safe-action?
Thank you
Love from Pakistan ❤ good work sir
❤❤❤ Love from IOK bro.
What vs code theme are you using ?
great video!
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
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!
Good work byte GRAD ❤
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?
How is this different from the /api routes?
This is more about Auth than "why use fetch instead of Dal"
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?
the best solution i think for this case is t3 stack with next-auth and trpc
Any tips on libraries/tools to log who is accessing the database (17m 33s) ?
Supabase has Row Level Security.
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
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?
Is there any way of deploying a next js app to some server with proper middleware for auth, other than vercel?
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.
What about fetching data in client component?
We can use the server action functions inside client components too.
Instead of API call simply get the data from sever action functions.
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
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?
This is rendered on the server
We need new videoo mate !!!
So, basically Controllers and Guards..
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
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.
Awesome !
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.
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.
OR, you can just use next-safe-actions and its middleware method
We have come full circle. Inb4 everyone goes back to Java
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
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
Caching in production has become incredibly annoying from version 14 onwards
I'd just stick with TRPC since I can easy control access by defining procedures.
Repository pattern.
So now NextJS is just Express + React on steroid?
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
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.
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.
solid ka idol
tanstack, tanstack, tanstack
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
OR WE CAN JUST RETURN A MINIMAL RESPONSE WITH THE THINGS ONLY WE NEED FROM THE BACKEND
this is just reusability in the name of DAL
Smells like php
Too much.