Vue JS 3: Hide your API Key with Node.js, Express & Dotenv

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] in this video after i show you how to create this simple weather app using vue.js 3 the composition api and the open weather map api i'm going to show you how to hide your api key from your end users by using a nodejs and express backend and how to hide your api key from your git repository using dot end and environment variables if you're new here my name's danny i'm an indie app developer and creator of fudgit if you want to learn about vue.js web development app development and all that good stuff click subscribe and click the bell every subscription helps me to create more content for this channel so what we're going to do in this video is create a new view 3 project and create this simple weather app where we can enter a city and grab the weather and display the weather for that city by using the open weather map api and it's not the prettiest thing but if you want to learn how to create a beautiful weather app then check out my weather app video but at this point our api key is going to be exposed to the end user so we can see our request here if i click on that you can see our api key here so what we're going to do is set up a node.js and express backend which will store our api key and do the api call for us and at this point if i just do another request here i'll click on this at this point our api key will be hidden from the end user and we can't see it in this request here and to finish off in case we want to share our code with other developers i'm going to show you how to hide the api key from your source code from your git repository by using environment variables and package called dot n let's get started by creating a new view 3 project with the view cli so i'm just going to google view cli jump to the website get started and installation and if you don't have node.js installed you can install that from nodejs.org you probably want to install the one on the left and you should then be able to install the view cli with this command in your terminal once that's installed you should be able to create a new view project with the view create command so i'm going to jump to my terminal which is just running within vs code which is the editor i'm using i'm just going to run view create let's call it view dash node dash hide api dash key and you want to choose manually select features and using the spacebar i'm going to enable the router and enable css preprocessors i'm going to disable the linter although you might want to consider using the linter on your own projects especially if you're working in teams then i'm going to choose version three no to history mode and i'm going to use some sas in this so i'll choose sas with scss in dedicated config files save this as a preset i'm going to choose no okay it's finished creating our project and it tells us we can launch it by running npm run serve in that folder so i'm going to drag the folder it's created into vs code open up the terminal and just run npm run serve and the app is now running so we can just command and click on this link and it will open it up in the browser let's design a really basic weather app on this home page so i'm going to jump to source and views and home.view i'm just going to remove everything inside this div with a class of home so get rid of that i'll get rid of this hello world import don't need that and we don't need this components object and i'm going to jump into the components folder and delete the hello world component as well and i'll save this home dot view and we now just have an empty page okay so let's add some markup in this div here so i'm going to add a h1 and just put the text weather app and then i'm going to add a div with a class of enter city where we're going to put our input so i'll add an input here i'm going to split the attributes on that with the split html attributes extension and i'll add a placeholder and set that to enter a city and then after this div i'm going to add another div with a class of weather where we're going to display our weather information a lot of h1 where we can display the temperature so i'll just put six degrees for now so six and then and d e g semicolon to output a degree symbol and then under that i'll add a h2 where we can display the weather type so i'll just put cloudy and then under that i'll add a h3 where we can display the description so i'll just put lots of clouds for now and i'll save that i'm just going to add a little bit of css to style this up a bit so i'm going to add a style section and in fact let's use sass so i'm going to set the line equal to sass i'm going to target this input in this enter city div so i'll add dot enter city and a new line and an indentation and then we'll target the input i'll set the font size to 40 pixels save that and we now have a nice big input and let's dial up the text in this weather div so we'll target this weather div let's div with a class of weather we'll add a bit of top margin to this or set margin dash top to let's say 10 pixels and inside this weather div i'll target this h1 so i'll add h1 here and we'll set the font size to 80 pixels to make the temperature nice and big and i'm also going to remove the default margin on all of these headings so i'm going to target the h1 the h2 and the h3 and just set the margin to zero and this is looking good enough now okay let's set up some data and methods and i'm going to use the composition api and a reactive object for this and if you need to learn the basics of the composition api then check out my composition api video so i'm going to remove this name property in our export and add our setup method and i'm going to use a reactive object to store our data so we need somewhere to store our city and somewhere to store the weather data so i'm going to use a reactive object for this so i'm going to import reactive from view and i'm going to set up an object called data set that equal to a reactive object like this um we'll add a property for our city set that to an empty string um a lot of property for our weather data i'm just going to call this weather and i'll set that to null by default and to use this data object in our view we need to return it at the end of this setup method so i'll add a return statement and just pass in data let's bind this city property to our input here so i'll add a v model and i'll set that equal to data.city and save that and to see if that's working i'll just put a value in here for now and save that and yeah that seems to be hooked up okay so i'll set this back to an empty string okay so when the user hits enter in this field i want to trigger a method which will get some data from the open weather map api so i'm going to jump to this input and add a key up handler and add the dot enter modifier so this will be fired whenever we hit the enter key in this field and we'll fire a method called getweather uh let's create this method so i'll make this a const so const get weather and set this equal to a function for now we'll just log out get weather we need to add this function to this return statement so i'll add that here get weather and i'll save that and let's just see if this method is being fired so if i hit enter in this field we can see getweather in the console okay so when this getweather method is fired we want to grab some data from the open weather map api and display it down here so i'm going to jump to openweathermap.org and if you don't have an account just go to sign in and then create an account and create an account and then once you've created an account you should sign in and if you then go to this drop down and my api keys you should be able to find your api key here so i'm just going to copy this for later and then i'm going to jump to the api page and we're going to use this current weather data api so i'm going to click on api doc and it gives us an example api call here so i'm going to copy this and paste it into another tab i'm going to replace the app id with my api key which i just copied and i'll replace this city name here i'll just replace this with manchester for now and i'll hit enter and we can see some weather data for manchester so we can see the name of the weather and the weather description and we can see our temperature here and it's in kelvins by default and we can change this to metric or imperial so i'm going to jump back to the api page scroll down to parameters and we can use this units parameter and set that to metric or imperial so i'm just going to add that to our query string here so after this question mark i'll just add units equals metric or you can use imperial if you like then i'll just add an and symbol hit enter and these temperatures are now in metric so i'm going to use axios to reach out to this api so i'm going to jump back to our project and kill the dev process with control and c and just run npm install axios and that's now installed so i'm just going to launch our project again with npm run serve and that's now running again so i'm just going to refresh our page we need to import axios before we can use it so i'm going to import axios from axios and then in this get weather method we're going to use axios to reach out to this api url so i'm going to copy this and paste it in here as a string i'm just going to enable word wrap and after this we'll add a then block which should give us a response and i'll just log out that response and save that let's see if that's working so i'll just type in city name hit enter and if we look in the console we can see we have some data and all of the weather data is in this data property so we can see the temperature in this main object here and if we go into this weather property we can see the weather name and the weather description as well okay so now we want to display this weather data on the page down here and before we do that i'm just going to tidy this up a bit so i'm going to put the api url into a constant so i'm going to copy from weather here to the start copy that and set up a constant and we call this api url i'll paste that in there and then we'll interpolate that so i'll select up to slash weather delete that and just add dollar and then curly braces and we need to change this into a template string so i'll change these quotes to backticks here and here and inside these curly braces we'll just put api url and i'll also put our api key into a constant so i'll set up a constant called api key and we'll just copy that from here and paste it here and then we'll interpolate that so dollar curly braces and then api key and we're currently hard coding the query here the city so i'm just going to delete manchester and instead interpolate this city property from our reactive object so i'll just put data.city in here and i'll save that and reload and make sure it's still working so i'll type in manchester and yeah we can see some data for manchester or if i type in new york then we see some data from new york so once we've got this data we want to put this data property into this weather property in our reactive object so that we can display it in our template so what we want to do in this then block i'll get rid of this console log and we can just do data.weather equals response.data and then after that i'm just going to log out data.weather to make sure we got the right data in there so i'll reload search for city and we can see our data in here so let's display the temperature first so this is going to be at weather dot main dot temp so i'll scroll up to the template and replace this number six with double curly braces and weather dot main dot temp and i'll save that and let's see if that's working and we have an error here cannot read property main of undefined and that's because when we initially load the app we have nothing in this weather property so let's hide this weather div if we don't have any weather data so i'm going to split the attributes and add a v if directive and set that to data.weather so only display this div if we have some data in this weather property so i'll save that and reload search for a city and we're still seeing this error cannot read property main of undefined and that's because i should be putting data dot weather.main.temp here i think i was thinking in terms of the options api then so i'll save that and we can now see the temperature for manchester uh it doesn't look that great with a decimal place so let's round that up so i'll just fire math.round on this and save that and that looks better so now we want to output the name of the weather just open up this proxy object so this is going to be at weather and then first item in the array and then main so i'll replace this cloudy text with double curly braces and data.weather.weather and then first item in the array and then dot main save that and we can now see clouds here and let's get the description so this is going to be at the same again except dot description at the end so i'll just copy this and paste it in this h3 and change this last bit to description save that and we can now see the description on the page so we can now remove this console.log and i'll just save this and try a couple of different cities make sure it's working so manchester um london and sydney and yeah it all seems to be working so what's the problem here well if i just jump to the network panel in chrome dev tools and clear all of the requests and make a new request you can see our request here if we click on that i'll just drag this over we can see our api key here so anybody that's using this app can get our api key and maybe use it for their own devious purposes and this might not be a big issue when you're using a free api like this but if you're using an api that you're paying money for then you really don't want other people to get access to your api key because it could really cost you daily and as well as in the network panel they will also be able to grab it from your source code as well if we go to sources then js then app.js and if i just search for app id actually api key then we can see it there as well let's set up a node.js and express backend which can do our openweathermap api call for us so that this api key isn't exposed to our end users in the front end of our app so i'm going to jump back to my editor and show the sidebar and at the root of our project i'm going to create a new folder called backend and this is where i'm going to place my back end and you might want to place it in a completely separate project but just for simplicity i'm just going to place it here i'm just going to show the terminal and open up a new terminal by clicking on this plus symbol and i'm going to cd into that back end folder and to initialize a new node project i'm just going to run npm init and then i'm just going to hit enter on all of these options but you can fill some of them in if you want but i'm just going to hit enter on all of these and it's now initialized our node project if we go into this backend folder we can see a package.json file and we can see this is going to look for a file called index.js so let's create that file in this folder so index.js and i'm going to be using express to set up this back end so i'm just going to jump to expressjs.com and this is a really simple framework which makes it really easy to create node apps and especially to create apis and we do need to install this into our backend folder so make sure you're in the backend folder and just run npm install express and you don't need to add dash dash save on newer versions of node so i'm just going to run this and that's finished installing so i'm going to jump to getting started and hello world and we have this simple hello world example here so i'm just going to copy this code and paste it into this index.js file so i'll just briefly explain what's going on here so on this first line we're just requiring the express framework then we're just setting up a new express app so that we can do something with it and we're just setting the port that this app is going to run on and here we're just setting up an endpoint at the path slash which when we hit that endpoint it's just going to return the text hello world to the browser and this app.listen is basically just launching our app on the port that we're specifying here so i'm going to save this and we can launch this up by just running node and index.js but if we do it that way we won't have auto server restarting when we make changes to our code so instead i'm going to use a package called nodemon which will give us auto server restarting so i'm just going to run npm install nodemon and that's now installed so to launch our app with nodemon we can just run nodemon and then the name of our file index.js and that's now running and it says that it's running at localhost colon 3000 so if i command and click on that we can see hello world in the browser which is coming from this endpoint here and if we change this text to hello worlds and save that we could see node 1 has restarted the server so if we reload the page it now says hello worlds okay so let's use this endpoint here to make the request to the open weather map api for us so that we can hide our api key from our front end so back to our front end so home.view instead of reaching out to the open weather map api in the front end let's reach out to this endpoint here in our back end instead so this is going to be at localhost colon 3000 so i'll jump to home.view and we'll update this string here to localhost 3000. but before we do that i'm just going to copy this and paste it into our backend because we're going to need that later but i'll just comment it out for now we'll change this here to https slash localhost colon 3000 and slash and i'll just save that so we're now sending this query string to our back end to this endpoint instead of to the open weather map api and so this endpoint will receive that query string and that query string will be in this request object at request.query and in fact i'm just going to rename these to request response just to make it a bit clearer what's going on here and i'm going to remove this response.send and for now i'm just going to log out console.log request.query and i'll save that and if we jump back to our app and so if we make a request now manchester uh looks like we have an error here so ssl protocol error and i think that's because i've set this api url to https and i think it should just be http so i'll get rid of the s save that and reload and search for a city and if we look in our terminal here the terminal that's running the back end we can see our query data here so everything that we're sending in this query string here the units the queue parameter and the app id parameter is being received by our endpoint here and we're logging that out and it's being logged out as an object now we're still sending the api key from our front end here so let's move this to our back end so i'm going to cut this api key const from the front end and paste it into our back end here and then back to home.view i'm just going to remove this app id property from the query string and save that and save the back end as well and if we reload and search for something and we look in our back end terminal we can see it's logging out the query object again but now it doesn't have the app id parameter that we need it only has the units and the queue parameters so let's add the app id parameter to this query object and set it to this api key so that we have everything that we need to send to the open weather map api so in our endpoint here i'm going to set up a new object called query and set that equal to request.query and then we're going to add an app id property to this query and set it to our api key so we can just do query dot app id equals api key and now let's just log out this query object to make sure it's got everything we need so we'll just log out query and i'll get rid of this first console log and save that and reload the app and do a search and if we now look in the terminal we have everything we need to send to the open weather map api in this object so we've got the units we've got the query and we got the app id or the api key but before we can make the request to the open weather map api we need to convert this object into a query string so that it looks something like this and we can do this with a package called qs so i'm going to search for qs package and jump to the qs page and this package allows us to convert an object into a query string and vice versa so to convert an object into query string we can just use this stringify method so i'm going to jump back to our terminal the backend one and i'm going to kill the process with control and c i'm going to run npm install qs and that's now installed so we need to require this library so i'm going to copy this top line here and paste it up here and we should now have access to this stringify method so after we've finished setting up this query object i'm going to set up a new variable called query string and set that equal to q s dot stringify and then pass in this query object which we set up and then we'll log out this query string instead of logging out the query object and i'll save that and we need to launch the back end again with nodemon index.js and that's now running so if i jump back to our app and reload and do a search and we look in the terminal we can now see our query string being logged out with the three different parameters units q and app id so we now have everything we need to make our request to the open weather map api so let's use axios again to make our request so i'm going to kill the back end process and run npm install axios and that's now installed so i'll launch our project again with nodemon index.js and to use axios we need to require it so we can just do const axios equals require and then axios we should now be able to make our requests in this endpoint so what we want to do is axios and i'll use a template string for this so we want to reach out to the api url which we have in this const here i'll just uncomment that so we want to do dollar curly braces and then api url and then we need a question mark before we add the query string and then we can just interpolate our query string so dollar curly braces and query string and then i'll add a then block and by the way you can use async await if you prefer but i prefer using promises like this and this will return a response from the api for now we'll just log out the response so console.log response and i'll remove this other console log and i'll save that and reload the app and we'll do a search and if we look at our terminal now we can see all the weather data being logged out so this request to the api is now working but we want to send this response data back to our front end so that it can then add it to this data property and display the data in our view so i'll jump back to index.js and what we can do after we have this response is we can use the send method on this response object to send something back to the browser although i've just realized that we've also named this response here i might just change this to res and what we can do is response.send and we want to send the data object that's in this response so we can just do response.send res.data and i'll save that and let's see if this is working so i'll reload the app and do a search and we have an error here access to xml http request from origin local host has been blocked by cause policy no access control allow origin header is present on the requested resource and this is because our front end doesn't currently have permission to receive data from the back end and we can fix this by setting the access control allow origin header on this endpoint to any origin and to do this right at the top of our endpoint we can just do response set i don't know what's going on with my indentation there and we want to set this access control allow origin header so i'm going to copy this from this error paste that in here and for the second parameter we just want to add asterisk and this means that any front-end can have access to this endpoint here so i'll save that and reload the app again i'll do a search and the app now seems to be working again and i'll just do a couple more searches so london and sydney and it all seems to be working and if we jump back to our network panel and reload this i'll just clear all of the requests and do a search we can see our request to our back end here and if we click on that we can now no longer see the api key so our api key is now completely hidden from the end user if you found this video useful so far smash the like button and leave some love down in the comments so we've hidden our api key from our end users but what if we want to share this project on github well right now our api key is still in our source code in this index.js file so if we put this project on github then any developer can access our api key and potentially use it and abuse it so let's use environment variables and a package called dot end to remove our api key from our source code completely so i'm just going to google dot end and jump to the npn page and this is a package which allows us to create a file called dot m and place some variables in there and dot end will then grab those variables and make them available in our back end so first of all we need to install it with npm install dot end so i'm just going to copy this command kill the back end process and install dot and that's now installed so if we scroll down to usage says as early as possible in your application require and config dot end so i'm going to copy this line and i'll place this right at the top of our index.js file and then it says create a dot n file in the root directory of your project and add some variables like this so i'm just going to save index.js and then i'm going to create a new file in the backend folder called dot env i'm going to add our api key here as a variable like this so i'm just going to add api underscore key and set that equal to our api key so i'm going to copy that from our index.js file here and paste that here and i'll save that and it says here process.n now has the keys and values you defined in your env file so we can get access to these anywhere within our backend i just trigger in process.env and then the name of our environment variable which is api underscore key so here where we're hard coding the api key we can now just set this to process dot emv dot api underscore key and i'll save that and let's see if it's still working so i'll reload the app and search for a city and it's not working because the back end is not running so let's launch the back end with nodemon index.js and try that again i'll reload search for a city and yet still seems to be working but now our api key is in this dot emv file instead of in our index.js file however by default this env file will be added to our git repo if we add this to a git repo and we can see that because the name of the file is in green here which means that it will be added to the git repo whereas if we look at these node modules folders they have this dark gray color because they're not going to be committed to a git repo and that's because if we go to this git ignore file we can see node modules has been added to this git ignore file which is why those folders are going to be ignored by git so if you want this dot env file to also be ignored by git we can just add to the bottom of this file backend slash dot emv and if i save that we can now see the emv file has changed to dark gray so that will no longer be committed to a git repository alternatively we can cut this out and save that and instead create another git ignore file in our backend folder so dot git ignore and then in here we can just add dot env and i'll save that and again we see the emv file change to dark gray either way our emv file is going to be ignored by git and not added to our git repository however if we are putting our project into a git repo then we probably want other developers to be able to launch this project which they might not be able to do easily right now since they won't have this dot emv file so let's just take a few steps to make it easy for other developers to launch this project so what we could do is duplicate this env file so i'm just going to right click on that and click on duplicate by the way if you don't see this option you can use the duplicate extension which you can find in the extension store so i'm going to duplicate that let's call it dot emv dot sample and we're not going to add this to our git ignore list we're going to actually commit this to our project but we want to remove our api key here so i'm just going to replace that with your api key here and i'll save that and so when another developer downloads our project they can generate an api key and put it in here and rename this to just end and they should be able to launch the project however we should probably add some instructions telling them how to do this so you could if you want create a readme file in this backend folder a readme.md file but i'm just going to add some instructions to this readme.md file which is already here in the root so i'm going to open that up and jump to the bottom um we could add a heading here which just says something like back end setup we could put something like for this project you need both the front end and back end running at the same time you will also need an api key we can put some instructions here so we can put something like in the backend folder rename dot env.sample to dot env and i'll just put these in code blocks so it looks nice then we could put generate an api key at https slash open weathermap.org and then add your api key to backend dot emv just put that in backticks then we could add another heading here install dependencies and a code block with npm install and we should probably tell them to cd into the backend folder as well and then we could add another heading which says launch the back end and another code block with nodemon index.js i'll save that i'll just right click this to preview it make sure it looks okay and yeah this looks pretty good and now any developer that downloads our code should be able to launch the project and if you want to learn how to deploy an app like this deploy the front end to firebase hosting and deploy the backend to heroku then you might want to check out my instagram clone series also check out my weather app video if you want to make a more beautiful weather app also please hover my face and subscribe every subscription helps me to create more content for this channel thanks for watching and i'll see you in the next one
Info
Channel: Make Apps with Danny
Views: 5,551
Rating: 4.9504132 out of 5
Keywords: api, api keys, dotenv, dotenv tutorial, env file, env file in nodejs, environment variables, express, full stack web development, github, gitignore, hide api, hide api key, hide api key javascript, hide api keys github, how to hide api key, how to use the env file, javascript api key, javascript environment variable, javascript security, learn node.js, node, node js tutorial, node.js, nodejs, rest api, web security, vue, vue.js, vue 3, vue.js 3
Id: 47pHZYtciEs
Channel Id: undefined
Length: 37min 58sec (2278 seconds)
Published: Wed Mar 03 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.