Why Angular, React & Vue shouldn't directly send Database Queries

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi everyone welcome to this video there is one question related to web applications built with angular react or vue or anything like that how do i connect such a application to a database be that a mysql or a nosql mongodb whatever database how do you connect your app to such a database to store data to fetch data and in this video i will answer exactly this question and as you will see you don't really directly connect your app to the database but instead there is something in the middle and we'll have a look at what this is and how you make sure that your data from these applications ends up in the database we'll have a look at all of that in this video i'll show that the concrete example of mongodb but what i show in this video will apply it will be correct for any type of database you're using so let's dive right in now for this video i prepared a little project little angular project which you find attached to this video of course below the video in the video description you find a link and in there we have a very simple angular app with only one component only the app component because it's not really about angle or building bigger apps there it's about the part of connecting angular to databases so here we got the app component in there we're rendering a form at the top and below that a list of to-do's so regarding that it's a default boring to-do app and i know everyone hates these to-do apps of course but it's not really about the to-do's or about angular it's about saving that stuff to the database and for that of course any app will do get some styles there a little bit of logic in the app component typescript file this is what gets rendered here we can enter a to do like do groceries or grocery shopping save that we can of course also delete our to-do's here so that's not too fancy of course now i got these two buttons here and i got another browser tab open already and that is mongodb but of course what i show you here would be valid for for any database not just for mongodb would be true for sql databases like mysql would be true for for any other solution any database you might want to connect so my goal is to make these two buttons work i want to be able to save my data here the list of to-do's we have to the database and upon pressing this button the data should be fetched from there and the big question regarding that of course is how does that work how do we connect angular to a database that's also a question i get a lot in my courses in the comments below videos and the simple answer is you don't directly connect your angular app like this to a database so even if you have a database let's say we're using mongodb here in the cloud but doesn't matter if it's running locally on your machine if it's running in the cloud either on a service like mongodb or if you're using aws and you spun up a database there what you don't do is you don't put your code to connect to a database right here into your your typescript files here right into your angular code you don't add your query statements your sql or nosql query statements here in that code and you might wonder why why are you not doing that because it would be highly insecure you would have to add two things to that code to really interact with the database for one that is the connection you need to establish the connection for that you need your credentials so you would have to put your credentials in here now let me show you what the problem with putting your credentials in there would be let me open up the developer tools here for this little application and let me bring up that server again that development server so that we can actually inspect that application let's do a reload here and now here we can of course debug our application one thing we can also do is here under the sources tab is we can have a look at the code somewhere in here you will find your code mike has here for example the webpack folder the dot folder source thanks to source maps i even find it in typescript format here that's a little feature provided by angular for debugging that gives us basically code with some source map files added to it which allows the browser to trace back the compiled javascript code to our typescript original code so here i can even read it like that but even if we would be running that in production you would be able to find your code as javascript somewhere because it is of course downloaded this is part of your application if you view the page source you have these imports here right you have all these imports here these javascript files and you also find those here under localhost in my case here in the sources tab there you also in the end find your different code files and you can of course look into these files now what's the problem with being able to look into these files here though what's uh what's the matter with that the big problem of course is that anyone can look into these files if your application is deployed somewhere anyone can inspect these javascript files because these files are not protected and i got another video on protecting or not protecting your javascript code on this channel so by default all the javascript code you right here and that's no difference for react or for the view or for vanilla javascript all this javascript code is always exposed that's how the web and how the browser works this front-end code which runs in your browser is fully viewable by your users that means if you put your database connection code in your credentials in here people can see that code in addition to that you would of course also have to put your queries in there so all your queries for interacting with database so your sql statements your nosql queries and even if your credentials were somehow hidden and you can't hide them but even if that would be the case of course people could start editing these queries or could view your queries to maybe get some insights in how your database is structured which might help them retrieve data with queries they write themselves which they can execute because in reality of course they do have access to your credentials too so it would be highly insecure if you would reach out to a database directly from inside your angular code here that's why you don't do that you don't directly connect to a database from inside your angular code because it would be highly insecure for that reason we also have no technical solutions for that so if you ever searched for a angle or package that helps you connect to your sql database or your to your nosql database you'll not find packages that packages that really do that in the direct connection form you find for the server side now what you will find though and what can be really confusing for newcomers is things like mongodb stitch if you go to mongodb and then under products go to mongodb stitch you'll actually find a solution which allows you to run queries from inside your browser so here we can import the mongodb stitch browser sdk and we'll use that in a second actually and there we can establish a connection to a database and then run our queries against that database so now we have these in browser queries and something similarly confusing is firebase for example whenever i use firebase as an example in my courses i often get the question if i can also show people how to connect to a backend instead of just to a database and the thing is firebase actually is a backup it's not just a database it's a backend with an attached database that's the thing but when you connect to firebase through the firebase sdk the javascript sdk for example whenever you're doing that you actually are connecting to a web service and on that web service the actual database connection the actual database queries are executed what you use in both cases so both here for firebase and the firebase sdk for the web as well as for solutions like mongodb stitch what you're using here is a browser side sdk which yes allows you to basically run queries against your database but it has one important extra step that part of the code where you connect to database is not in here instead sdks like these give you ways of authenticating users and you can also authenticate anonymously which means you get some some dummy token so to say which works for every user of your application which is of course insecure and you don't want to use that for your entire database but these apps give you ways of authenticating users and then only these authenticated users can actually run queries and all that is funneled through a web service provided by mongodb by firebase which does the user authentication validation and which then actually does the real database connection and the important building block in that picture are the access rules which you find both on mongodb stitch as well as on firebase in both cases you also learn about the rules you can set up which you set up on the web so in the firebase or in the mongodb web console so not in your browser site code which people could read or edit but in the code only you can add it on the server and there for example for firebase rules you can determine in detail who would be able to edit which part or which data in your database and with who i mean unauthenticated users authenticated users authenticated users with a certain id things like that and that means that whilst you can for both firebase as well as for mongodb also work with so-called anonymous unauthenticated users you can control on the server side so in the mongodb web setup or in the firebase web setup what these anonymous users will actually be able to do and of course there you should normally lock that down and only restrict it to being able to write or to read from one specific part of your database instead of your entire database and people would be able to work with your entire database if you would theoretically add your full credentials and your full eye work with my database code to your front-end code instead these sdks abstract that away from you give you a full web service behind the scenes to which they talk add user authentication and then give you detailed control on the server what these users they authenticate for you are able to do and that's an important part now let's actually have a look at that here with mongodb because it's really important to understand that so here i logged into my mongodb cluster and that's really just one example here of course not every database might give you a cloud service with an sdk like mongodb stitch or firebase and in such a case you simply have to create your own backend service which then talks to that database and exposes rest api endpoints to which your front end can talk because that is how it always works you're end just talks to a web service which then does the database connection and that ever can be done with the help of services and sdks like firebase or mongodb stitch or you build your own backend api to which you talk and of course i also got tutorials on that you never directly talk to a database in your angular app so here for mongodb for example i can go down to the services which already is an important hint to the services part here and click on stitch to basically learn how to or to set up a new connection and learn how to connect my front end here and therefore i click on create new application give it a name ng database demo whatever you want to name it link to a cluster i already created a cluster and this is the cluster to which i'll connect this leave the remaining setup here as it is and click create and now what this does is it does some back-end setup here on mongodb's servers to basically set up that web service to which i can then talk from my front end i just don't talk to it through the angular http service and by manually sending requests to endpoints but i can also use the sdk which in the end does that for me so that browser site sdk and it's the same for firebase in the end just sends ajax requests to some apis behind the scenes and gives you a more convenient api to work with that's all that's happening it's exactly the same as if you had your own backend web service your own rest api and you use the angular http client for sending requests and that's absolutely normal too by the way that's also why in my courses like in my angular course on udemy i actually do use the angular http client and i do use the firebase rest api so that you really see that there is no magic involved and that you don't directly talk to a database but that you instead talk to a backend api now with stitch setup here though i'll show you the sdk example go to the clients here and you learn how to add this to your browser side application now i'll use the npm approach here and simply run this command here so here i'll quit that dev server temporarily copied in npm install dash dash save mongodb stitch browser sdk that installs the wall sdk we can use on the browser and then here we actually got a demo snippet which we can start with to connect to our backend here and work with it let me actually grab this code snippet here and now in here in this application i'll add a simple service my db service and here exporter class db service and of course you can name this whatever you want and give this the add injectable decorator here and i'll add this object where i said provided into root to automatically set up um dependency injection here in my angular app and in here i'll copy in that code snippet with that import not with the required syntax though but with import from then use that code here or take that code and actually add a new method in here init db and in that method i want to execute that code now give that database here a name like ng db and actually store that in a variable which will be of type remote database which i also import from up there and then here i'll actually store this connection which i'm setting up here or this database access here in this property of the service now we can just call in a db when the app starts so here in the app component i'll actually implement my on init interface here on and it is imported from ant angular core and of course all the ad injection of the db service with by pointing at db service here which is imported from the well db service file i just added stored in a private property and then here in engion in it of my component i can call dbservicenhdb to initialize that database here right when the app starts so now we can add methods to add a to do for example so here the service i'll add the to do function or method and now we want to interact with that client here so i'll store this in a property of the service too actually and that will be a stitch app client so that's another import we have to add from the mongodb stitch browser sdk so store that client here as well and now here we of course also have to use this client and in add to do we can now use this client off login with credential and now we create a new anonymous credential you could also and for that you should check out the docs of mongodb stitch if you want to use that solution setup authentication with email and password to have real authenticated users here we're basically creating a dummy token for the current anonymous user of our app and once that authenticated connection is established we have a function here which will execute and in there we can reach out to our database handle and then there to your collection for example and that collection can now have any name you want to do this and in there i can insert one to do and for that i can now enter empty any document any javascript object i want here i expect to get my to do and that will in the end just be an object with a title which is a string it's as simple as that so here i'll get such an object and therefore here i'll just add that to do here to the database and if we now save this we can try using that here and on add to do so besides storing it here locally in that array we're also outputting in the component we can use this dbservice ad to do and forward this to do here which i'm in the end creating so here i have my new to do it's this object i add it to my local array here and then also i have forwarded to add to do in the service if we do that and we restarted service at that web server we should now have a setup where we can actually store our data here also on the mongodb servers but again by using that sdk which talks to that mongodb web service we set up with creating that application and which then therefore manages all the direct database access for you and allows us to lock down access as i'll also show you in a second so now here let's give that a try let's reload the application and we're now getting an error that global is not defined this is now a mongodb specific error here from that package we're using the polyfills ts file you can go to the bottom to application imports there at window as any global and pointed window so we have to add a global variable to our script which points at our window that's all we have to do here in the application imports with that the app restarts now it works and now if i add some to do here and i click save i get an error authentication why anon user is unsupported that's the part i meant with locking it down now if we go to the mongodb stitch clients here we actually have to control who is able to read and write to our database so here on the back end you have to go to the users part here and then here under providers you have to allow users to log in anonymously so that's already the first important thing you have to enable this otherwise no access is possible so the first security measure in place here you could also of course restrict this to email password users so that you need real users who sign up with email and password so now if this changed let's try that again let's try adding some to do now we're getting only that service not found mongodb one error and yeah my service name which i can find here under clusters is mongodb atlas actually a little mistake on my side let's make sure you use that here and now with that however if i add some to do now we get that error i actually want to see no rule exist for namespace ng db to do's and i'm showing these errors except for the one with the service name on purpose because that's the rule part i mentioned here under rules on the back end you now see that you can set up rules for your collections and in mongodb collections are just your database table so to say that allow or prevent access and now here we indeed have to set up a rule for example for ngdb which is our database we're connecting to and then for the collection which we want to write so here let's create ngdb and then there there's a collection to do's that's the collection to which i want to talk here and for the to-do's collection which i'll hear create in the rules setup we can now set a template for example allow users to only read and write their own data boom that's already some security we can put into place here and that's the part i meant we control access here because there's a web service in between which we don't write ourselves which you could write on your own of course if you want to write your own rest api but with here or also in the case of firebase you get out of the box and therefore there is no direct access to your database here i'll create no template and add a collection and now give read and write access by adding or by setting these two check marks here to everything in that collection which is of course highly insecure but as you saw you could have locked that down to a per user basis and now with that if i add another to do here and i hit save now this actually gets stored we get no more errors because now i added rules that allow anonymous users to read and write data and at the moment we are writing now to validate that this really happens if i go back here to my clusters and i have a look at my collections here to look into my database essentially i can go to ngdb to do's here and i see that element that was added so now we are talking to our database but always through the funnel of having a web service in between and now just for a completeness sake let me also add a get to do's method here which does also talk to stitch here to the same collection but there instead of insert one i use find and find like this finds me all entries i return this promise here overall and in there i return the result of find here and also call as array here on the end so that this will give me a promise which in the end returns an array and i'll also let typescript know what's in my collection here because collection actually is a generic method in my collection we have javascript objects which have a title property and a string property and since that's added automatically by mongodb they also have a underscore id property but i only care about this i'll only add this here so now this is getting returned here wrapped in a promise of course because it will take some time so now to actually make these buttons work here let me remove save to database because we're already saving whenever i add something but with fetch from database i want to fetch the data here with on fetch data new method that should be added to our app component of course so here on fetch data and in there i'll reach out to the db service and call get to do's that will give me a promise so we can add then here in the end here i get my to-do's array and i can then set this to-do's equal to the to-do's i'm fetching here and hopefully that should do the trick so if this restarts and click fetch from database yeah here the to do appears now one thing we can't do here you could of course implement it but it's not really the focus of this video deleting here only works locally if i fetch it it's there again if you wanted to delete it on the database too you would have to use that id which is automatically added for every item use that in the end here um add a remove to do's method to the service manage that id in the front end and use that for then deleting a to do with the help of the delete one method here on your collection but this video is not really about mongodb stitch i hope the addition of mongodb stitch wasn't too confusing the key takeaway i really want you to take away from this video is that you don't directly connect and talk to databases from inside your angular app instead you always talk to web services so to apis like rest apis which either are written by you or by other people like in this case by the mongodb team or firebase case by the firebase team these apis can be abstracted away when you're working with sdks like we're using it here then it might look like you're directly talking to databases but you actually are not in the end you're just using a browser site sdk which does send http requests behind the scenes you just don't see these requests they're hidden away from you nonetheless these requests do happen no direct database access is happening here instead requests are sent in this case here and all the firebase cases on two dedicated web services here our stitch service which we set up when we clicked that create app thing here under the stitch part of my mongodb backend and there in this application we had to enable authentication of anonymous users and we had to set up rules for our different collections regarding who may read or write from there and you can set up granular rules there you can force users to log in with email and password and that's exactly the part i meant you don't have your database credentials in your code instead these credentials are stored in the stitch web service here so to say they're not exposed to your front-end users and your front-end users can only send queries you enable here through your rules that's really important and that's why you don't directly connect to databases from inside your angular app you
Info
Channel: Academind
Views: 51,548
Rating: undefined out of 5
Keywords: angular, angular mysql, angular database, react, react.js, react mysql, reactjs mysql, react.js mysql, vue, vue.js, vue mysql, angular mongodb, react mongodb, react.js mongodb, how to connect angular to a database, tutorial, course, example
Id: dsAalk1NpVk
Channel Id: undefined
Length: 27min 6sec (1626 seconds)
Published: Wed Jun 19 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.