The Complete Guide To Building A REST API With Node, Express, TypeScript & MongoDB + Authentication

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
my name is Antonio and in this video I'm going to show you how to create a rest API using node typescript and mongodb we'll be covering the basics of creating a rest API including setting up our environment creating our routes and handling errors a lot of people don't know how to do this or where to start so I'm going to break it down All For You by the end of this video you'll be able to create your own apis that will power your next big project alright so let's get started first of all we are going to open a new folder and inside I'm going to write npm init Dash Why this is going to set up our project accepting all the default options and now we will have a new file here called package.json next step is to set up typescript so let's go ahead and let's run and pin install Dash D atscript along with typescript we are also going to need ts-node so let's go ahead and install and install Dash DPS Dash node foreign which is going to keep our project running during all the changes so npm install batch d oldmon perfect just like that we have our initial dependencies next thing we are going to config typescript so create a new file called Dot yes config.json in this config.json we are going to open a new object and write compiler options we're going to set a module the node next we're going to set the module resolution node we're going to set the base URL The Source we're going to set the out directory to this we're gonna enable Source map and we're going to include no implicit any this is going to enforce our typescript rules by a bit which is what we want for now we're also going to add an include option which is going to be equal to Source slash Asterix Asterix slash another Asterix which means we are going to include all of the files in the source folder all the folders inside the source folder and all the files there as well perfect this is a great configuration next thing we are going to configure is node mode so open a new file called nullmon.json inside nodeman.json we are going to open an object and say watch and the folder we want to watch is the same as in typescript configuration called source the extensions for which we are going to look for are that DS and Dot JS make sure there is a comma in between and the execute function is going to be TS node dot slash Source slash index at the s great now let's structure our project just a little bit by creating a new folder called source and inside create a file called index.ds here we're just going to say console log hello right script so let's go ahead the package.json and let's add a script called start which is going to be node 1. just like that so now go ahead and run npm start and just like that we have a working typescript saying hello typescript thanks to node mode looking for changes if we change this to hello node it's going to restart and it's going to be here for us great next thing we want to do is set up our Express server so let's say start by importing Express from Express importing HTTP from http import the body parser cookie parser let's import compression and lastly let's import ports we are going to need all of this to make a to make sure our project is running correctly so next let's initially initiate our app so once the app is equal to the express [Music] our app is going to use course so right course like this credentials true this is going to be important because of how we're going to implement our Authentication next make sure the app uses compression make sure it uses cookie button because we will be working with cookies and make sure it uses body browser in a form of Json great now we can create our server cons server is equal to http.create server and we're going to pass our newly created before we go forward let's go ahead and install all of these packages right here so I'm just good for now I'm going to stop what's running in the terminal here and I'm going to install npm install press body dash parser cookie that's parser compression and of course once that is installed we need to install their types so go ahead and write npm install Dash D types Express types money person types cookie pasta and types Russian tags course just like that our errors are gone great now let's add a listener to our server so server let me listen we're going to be running our server on port 8080 so open back and call that and say console log server running on http Dash Dash loaded host a080 great now if we try and run our node man again so npm start you're going to see a new message saying server running on HTTP localhost 8080 if we visit this in our Google Chrome we're gonna get a cannot get route which means the server is initialized but we have no routes at the moment great now let's move on on creating a mongodb database and connecting mongodb in our project so for that we're gonna go ahead and we're gonna write mongodb Atlas pick the first result and click on sign in depending on whether you've done this before you might have an account but you can just sign up using Google it's what I'm going to do for now once you've logged in you're gonna see a dashboard similar to this go ahead and click build database or use the create button make sure you select a shared free database you don't have to look at all the options here for now just click create cluster and confirm one more time it's free here and free here for our database authentication we are going to need to create an admin for tutorial purposes I'm going to use Antonio as username and Antonio as password I highly recommend you using Auto generated secure password or use a service like LastPass one password something like that once you've created our user we want to make sure that we can connect from our local environment and for that just click add my current IP address click finish and close click go to databases and you will be able to see your cluster right here next click on connect and say connect your application the second option here we will be provided with some options such as node.js and our version we didn't have to change that we can just use this string they've created for us so let's go back to our code now and let's create a new constant called const URL and I'm going to paste the string what we need to change here is this password section remember I used Antonio as username and Antonio as password so what I have to write here is Antonio and this is going to be my Axis next we have to do is close this terminal for now and say npm install on Goods we are also going to need to install npm Dash D types slash numbers go ahead and import the Mongoose at the top and right here we're going to initiate our Mongoose so right on good step promise it's going to equal the global JavaScript promise mongoose.connect is going to be equal to underscore URL which we have created right here again make sure you have username and password set up correctly and last we're going to add an error catcher in case something goes wrong so write the following fingers the connection that on error and write a callback which is going to accept an error which is a type of error and all we're going to do is say uninstall.log Arrow because that's all we need for now perfect now let's go ahead and run our nodeman again so npm start as you can see we get some deprecation warning but Mongoose is successfully connected great now it's time to create our first database schema so inside source create a new folder called DB inside DB create a new file called users users.ts is going to be our user schema and user model so go ahead and import Mangus from mongoose and let's define our user schema once the user schema is going to be equal to new Mongoose without schema inside we're going to have a username which is a type string and it's going to be required next we're gonna have email which is also going to be a type of string it is also required we're now going to write the authentication model so go ahead and write Authentication it's going to be an object which is going to have a password which is a type of string which is required but it is not selected what select false means is that uh every time we use one of our controllers to fetch the user we want to avoid patching authentication object by accident meaning we don't want to fetch all users and provide the entire API with our authentication data next we're gonna add another field called salt which is going to be a type of string and again it's not going to be selected by default and looking at the same thing for session token type string select pause excellent we can build our first schema congratulations next we have to turn this schema into a model so go ahead and write expert const user model which is equal to Mongoose dot model we're going to call the model user and we're going to use user schema perfect and now we're going to write some actions these actions are going to be used in controllers it is a practice to keep them abstracted for now I think this file is going to do just fine so go ahead and write const get users it is going to be a simple method which is going to use the user model to run simple find mongoose method next let's write get user by email we're going to use this in various authentications such as registrating so let's see if the exact user exists and stuff like that so the parameter we're going to accept is email which is the type of string and what we're going to do is run user model that point one by email perfect next a very important action get user by session token we're going to use this to confirm whether our user is logged in or not so go ahead and write session token as the parameter which is the type of string and we're gonna say user model okay find one very similar [Music] and what we're gonna search for is authentication that session token will be equal to session just like that next we're going to write expert const get user by ID which is self-explanatory but for this one we don't have to use find by one we can just use find by ID and passing user ID great and just a couple of more actions left we're gonna write const create user which is going to accept values and it's going to say user model new user model values dot save foreign user user to object so we can get it in an adjustable form two more functions left actually const [Music] delete user by ID which is going to be ID string user model that find one and delete and we're going to use underscore ID is equal to ID and the last method we're going to use is going to be called update user by ID it's going to accept the ID and it's also going to accept values which are going to be of the same type as create user so string I name it's going to say user model find by ID and update and we're just going to say ID and values and just like that you've finished the entire user model and user schema perfect now we're going to move on into creating some helpers for authentication before we move on to routing so in our source folder create another folder called helpers and inside a file called index.ts here we're going to use authentication helpers which are going to help us either to encrypt the password or to create a random token so import crypto and crypto and first let's create the randomizer so expert const random is going to be a method which is simply going to return crypto dot random bytes 128 that's this string base 64. so it's digestible for our database we're gonna create an authentication needle so expert cons Authentication it's going to accept sold which is a string and it's gonna accept password which is also going to be a string make sure it returns a crypto function crypto that create H and AC we're going to use the algorithm called sha 0.6 and we're going to use a combination of salt and password join Dash we're going to update that using our secret we're going to Define our secret up here cons Secret it's just going to be something unique for your project in my case this is going to be Antonio [Music] rest API just like that so make sure you update this with secret and then adjust into effects perfect we have created all the helpers we need um or our authentication module so let's close things a bit and let's create an authentication route so before we start with script an authentication controller so create a controllers folder and inside create Authentication authentication with PS first controller we're going to create is going to be the register controller so import Express expert const register which is going to be an asynchronous function which is going to create a request which is type of Express that requests and the response which is type of Express response open up a try and catch block and let's handle the error side first for now we're just gonna make sure we log the error we're not going to do anything else with it and then we're just gonna end the call by saying return response send status 400 because something went wrong in our trimeter we're gonna write an actual registration process so go ahead and let's extract the data we expect from our body in our case that is going to be email password and username if you're wondering why we know this is what we're gonna get is because we have defined that in our username and email just like that and password so first let's create a small check to see if any of these fields are missing so if we are missing an email or we are missing a password or if we are missing username we want to return response send status 400 because that's not something we can work with next let's check if the let's check if the email user has entered already exists so honest consistent user is going to be equal to a rate wait and then I'm gonna have to import the function get user by email [Music] from Delta DB users just like that so let's wait get user by email and let's just send in an email if existing user exists we're going to return response send status 400 there is nothing we can do about that if everything passes and we have email password and username and there is no existing user we want to create the authentication so we're going to clap first we're going to create soul and for that we're going to use our random util so I'm going to import and let's import random one markers and Outlets just like that [Music] next let's create our user constuder is going to be a way to create user email username and open up an Authentication object which is going to have the newly generated salt and password which is going to be and which is going to be a new deal we have created up there called Authentication authentication I'm going to say salt and password do it let's not forget to import the create user controller from here just like we have get user by email we need to remember to import create user as well just like that after we've done that we need to return a success message so return response status 200 Json user foreign just like that you have successfully created your first controller good job now we're going to focus on creating a route so create a new folder called router in this router create a file called index.ts going to import Express from Express and we're going to say const router Express router next we're going to export the default function expert equal which is type of Express router and from now on all we're going to do is say return just like that now in this router folder create a new file called authentication that's TS go ahead and run import Express from Express and let's import our register controller so register wrong dot dot controllers slash multiplication in expert default a router parameter which is type of express.row [Music] and right router that post dash out Dash register and pass in the controller or register perfect now go back to index in the router and let's import this newly created authentication route import authentication from Authentication just like that and looking to pass it into this function right here as authentication router before we test this we have to go back to index.ts and add app that use slash router and make sure we don't forget to import our router wrong just like that and now let's test out registration in postmap I have a predefined route here HTTP make sure it's not https it's HTTP localhost 8080 slash out slash register we have defined that right here slash out slash register and we're going to use the register controller we're going to write an email of Antonio codes.com a password of one to three and the username of Antonio and it's all going to be stored right here right now we have nothing in our database but if we go ahead and click Send we have successfully created our first user with Authentication and if we check it out you can see it appears right here good job now it's time for us to create our login controller so let's close stuff up let's go to controllers Authentication and let's create our login controller so expert cost login is going to be an asynchronous function it's going to accept Express at the request and the response open up a try and catch block [Music] we're gonna handle errors the same way so as a log [Music] and return response send status 400. just like that they're going to export the we're going to export the fields we will expect which in our case is email and password [Music] and request the body if there is no email or if there is no password we're gonna return response send status 400. next thing we need is to check whether there is a user with this email so so go ahead and write honest User it's going to be a wait get the user by email write in email if there isn't a user there is nothing we can log into so return response to send status 400. next we're going to learn how to authenticate our user without knowing their password we're going to use that using hash comparison so unexpected hash is going to be equal to Authentication user at authentication that's solve and password and then we're going to say if user that authentication that password is not equal if you expected expected hash we're going to return response send status 403. before we can continue doing this we need to add another function here called dot select open up a string and say plus multiplication with salt space plus multiplication dot password this is very important very important to have this otherwise you're not going to be able to access authentication and solve right so check if user authentication password is equal to expected hash we have created user newly typed invest if it's not we are going to send a 403 response if it is we're going to update user session token so go ahead and write on solve is equal to random [Music] and user that Authentication the session token is equal to Authentication so user underscore ID this string oh wait user save and now we have to set the cookie make sure you've write response that it could be my cookie name is going to be Antonio dash out and we're going to save the session token user Authentication building and we're gonna write a cookie option for the main localhost and attack slash what we want to do now is say return response status 100. Json user just like that we have created our login controller now we're getting ahead go ahead and go into our router Authentication and we're going to add router that post out login I'm going to use login controller which we will import from here as well if you go to postman now and try to log in using Antonio add codes with the password of one to three as if we set we have successfully logged in but if I try one two three four for example I'm gonna get forbidden nice and once I'm successfully logged in you would also see the cookie which is my session token perfect now we're going to focus on creating our users routes so we're going to start by creating a folder called middle layers [Music] in this middle verse we're going to create two middle words import Express Chrome Express and we're also going to import another package so open your terminal and now I'm just going to stop this and say npm install Dash also writing and then install of the right slide loadage don't forget to start your project again so npn start make sure your project is running and node one welcomes you with a message just like that I'm going to close this for now but keep it running I'm going to import get and merge from low Dash we're going to need later we're also going to need a method called get user by session token dot dot DB users so the first middleware we're going to create is is authenticated middleware so expert cons is authenticated it's going to be the same famous function which accepts request which is type of express. request the response which is type of Express response we are going to open up a try and catch Block it's very similar to our controllers and in here what you want to do is just write console log error miracle in response send status 400 as we've done many times before so first things first we want to extract the cookie honest section token is going to be request cookies and we're going to pick Antonio dash out why this cookie well we have set it in our controller's Authentication response that cookie Antonio out in our login controller let's go back into our middle layers first experience if there is no session token let's return responses and status 400 as there's nothing we can do about that sorry 403 would be a better place next we're going to see if the if there even is an existing user by this session token so go ahead and say const existing user oh wait yep user by session to open if there is an existing user return response send stages 403 as well because we are not authenticated to this next we're going to do a useful merge to our request object merge request identity this can use it just like that and return next if you forgot to add next import parameters so after response is ready next let me just type okay let's press next function just like that we have created our first middleware and we're going to use it in a moment for now go ahead and create users the DS controller inside of users controller first we're going to create a get all users controller so import let's press run Express looking forward get users from [Music] VB usage columnist get s it's going to be an asynchronous function which is going to accept the request which is expressed request in response which is expressed at the response [Music] we're going to open up a try and catch block as we did before and we are going to return one of the log here and we're gonna say return response sending status 400. here we're going to say I have a very simple function called users it's going to be a weight get users and we're going to say return response status 238 users just like that now let's go ahead and go back into our router and let's create a new router called users.ds import Express from Express and let's import get all users from Dash Dash controllers [Music] users expert defaults router I just type Express router [Music] and just write router yet flash users and write get all units it's like that don't forget we have to go back into our router index we have to import useless and we have to add them here just like that now if we go into Postman and go into users get function we are going to get the user's object if we're going to register and create another one another user and then try get again we're going to see this new user now we want to do something we want to remove our authentic authentication cookie right now we can see the users even if we are not authenticated we want to change that so we're going to go back into router users and we're going to import is authenticated from dot dot middlewares and we're going to add this after our route is authenticated comma get all users if we try again we're gonna get a forbidden but if we log in and try again we can successfully see all of our users good job now we're gonna go ahead and focus on creating the delete and update for our users so go back into users and say export const delete user it's gonna asynchronous function which accept request the response [Music] trying Edge block [Music] the arrow and the return status perfect instead of our body for the first time we're gonna accept parameters so extract a b from requested parents request phone parents now we are not going to check any authentication here because we're going to use a middleware for that so go ahead and say const ant delete the user is going to be wait delete user by ID make sure you import this okay I'll send in ID [Music] the current response person really producer just like that we have created a controller to delete users so copy delete user controller let's go back to a router and let's write router dot delete users Dash ID clearly user which is going to be imported in here if we try and delete for example we're going to copy the ID and click delete we're going to change this click Send we have successfully deleted full and if we try again you can see the foo no longer appears here but this is a mistake because we should not be able to delete another user so let's go ahead and create another middle layer this mineral is going to be called is owner [Music] [Music] open up a try catch block [Music] and inside we're going to check and check for parameters as well because this is where we're going to use it react with parents we're going to say comm's current user ID is going to be equal to get request identity ID as string we have the full typescript a little bit with this request identity because of this authentic edit middleware where we merge request identity but we don't tell typescript that that's where we merged it so that's what we have to tell it that it's going to be here as a string foreign if there isn't an user ID we're going to return phones send status for 100. actually 103. uh next we're going to say it burn user extreme isn't equal to ID we're going to return sponsored stages 43 and then we're gonna say next just like that now let's go back and let's go into user's Authentication now let's import our is owner middleware and let's write it right here before delete user let's go into register and let's create Foo again let's fetch all the users and let's try and remove full even though we're logged in as Antonio so one more time I'm going to fetch Foose ID and I'm going to try and delete pool now I'm gonna get a forbidden but if I go to login and login as Foo you can try to delete myself then what you forgot to put is authenticated right here so make sure it is authenticated make sure is authenticated is first make sure is authenticated is first so this authenticated right here and let's try again and just like that we have successfully removed oh and if we try again we cannot see because we removed ourselves but if we log in as Antonio and try again we can see that Foo no longer exists great we're moving on and creating our last controller which is gonna be the update controller so go ahead and write the expert const a bit User it's going to be a synchronous function it's gonna accept request Express request response Express response welcome to try and catch block [Music] log the error just follow just like that and here we're going to extract the only thing I want us to update for now which is going to be the username and I'm going to extract that and request it back so if there is no username and a return send status or 100 because it's not something we can work with next we can see if the existing user exists so we're also going to have an ID request Paramus right here something like that and just say const user await yeah user by ID and say user with username middle name user and wait user save during this status 200 hey Jason user dot end just like that now let's go back into our router users and that's right router dot patch users user ID is authenticated its owner update computer [Music] just like that now let's check if we can update Antonio's username so my current username is Antonia I'm gonna update this and there we go modified Antonio now let's just try and create a new user here Foo let's see if we can change through his name [Music] foreign good job thank you so much for watching this video If you enjoyed leave a like comment and subscribe see you in the next one
Info
Channel: Code With Antonio
Views: 94,516
Rating: undefined out of 5
Keywords: REST API, REST, API, MongoDB, NodeJS, Node, JavaScript, TypeScript, Tutorial, How to, express js, node js, ecmascript
Id: b8ZUb_Okxro
Channel Id: undefined
Length: 49min 47sec (2987 seconds)
Published: Wed Feb 15 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.