How to add Environment Variables in Next.JS | Using dot-files(.env) and next.config.js

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys welcome to the video and today we'll be seeing how you can create and use environment variables properly in your next js applications we'll be discussing both of the methods of injecting environment variables namely your dot files and your next.config file and we'll also be seeing how you can avoid overriding your environment variables especially when you're using both of the methods or if you're using multiple dot files within the same project so without any further ado let's get straight into it so here we are on vs code where we have our starter nexus application it's the same starter application that we have been using for a past few tutorials now before we go on and integrate our application let's first take a minute to understand what environment variables are and why do we even need them so environment variable just like any other variable store values but these values are of a special kind which we do not want to hard code in our application code so we do not want to declare these variables inside the source code of our application but instead we want them to be present in the external running environment for example nxjs runs on the node.js environment and the node.js environment has a module called process which stores all of the environment variables here i'm on the official documentation of the process module of node.js and here if you notice there is something called process.env a process.env is just a simple object which stores all of our environment variables as key value pairs so here in this example things like user path password are all being stored as environment variables and accessing them on the node environment is really easy you just need to mention the environment variable name prefixed by the process.env object now you might ask the question what kind of values do we need to store as environment variables and the answer to that would be any value or configuration which is sensitive and is supposed to be protected and kept as a secret is the best candidate for being stored in the environment now in next year's starting version 9.4 adding more environment variables to your process.tnv has become really simple because now nextgs natively supports dot env files so the first point to keep in mind here is that you do not need any other third party library to load environment variables now a dot env file is just a simple dot file which would look something like this so here in our application in the root directory i'll be creating a new file called dot env normally dot env files are stored in the root directory itself and its contents are just key value pairs so for example i want to create a new environment variable called app name and its value is nextgs app now one thing to keep in mind here is that all of your environment variable values are parsed as string so if we save this file and start our nexus application in our current environment we'll have access to a new key under process dot env called app name now here in the documentation the dot file is called dot env dot local dot local just represents our current working environment other examples can be dot development for a development server or dot production for a production server and in this next line they've also mentioned one very nice feature that was recently added that if you want to expose environment variables to the browser which means that if you want to include a particular environment variable in your client bundle which will be accessible on a user's browser all we need to do is just prefix the environment variable with the key next public now i'll explain what this means any environment variable which does not have the next public prefix will only be available on the server side so as most of you know nextgs allows you to create apis and it also has server side rendered pages for example in our application our page is server side rendered and exposes a function called get server side props here we can write our code to fetch props using some api during the build time of the page and then pass it to our main index component here as props so if we don't add the prefix next public the environment variable will just be present whenever server side operations are happening so to prove this i've added two console log statements the first one is present inside the get server site props function here your environment variable will be printed with the message server side and then again in our main component i've added another log statement where the same environment variable will be printed with the message client side now let's save everything start our development server using npm run dev and we'll be checking if we are able to see the particular logs so if we go to the browser try to access our index page you will see that the client side environment variable is undefined but at the same time on the server side it's clearly defined so in the server logs you're able to see the value as next.js app which we have set in our dot env file now coming back to this prefix functionality let's create another environment variable which will be called next underscore public underscore app name and let's call this next.js starter and make some changes in our index.js file so instead of printing process.nv.app name this time we'll print next public app name save the changes run our development server again the environment variables are loaded let's go ahead and refresh our index page and here in the logs you'll be able to see that this time we can access the environment variable which was prefixed by next public key so as i said environment variables usually store secrets and you would not want these values to be exposed on the client side but in some cases there can be values which you would want to be accessible throughout the application as an environment variable and for that you can definitely just add the next public prefix to your environment variable name and it will also be accessible on the client side so this is how you can add environment variables by creating a dot env file and then access them inside your pages by simply mentioning the key name after process.env now one thing to remember here is that in order to keep server only secret safe next is mutates the process env object in a way that the object is not a javascript standard object anymore so you cannot use object d structuring on process dot env object so you can't maybe write something like this where you're trying to restructure a certain key value from process.nv this will throw an error you have to mention the names separately every time you're using environment variables in xjs now next chess also allows you to refer to the value of other environment variables in a different environment variable let me show you how so let's say i wanted to make an api call in our get server site props function and for that i'm making a fetch call something like this where i'm calling an endpoint using fetch and then storing the details and user details variable but i'd want this particular api host to be present as an environment variable so i can maybe store the root host name in a variable called hostname in our dot envy file so this environment variable will just store the root host name of the api endpoint and i can create another variable let's say user endpoint where i can refer to the hostname variable using the dollar sign and then append or prepend more data to it so we have stored the end point that we were calling under user endpoint so here instead of hard coding the api endpoint in our get server sitebox function what we'll do is we'll access the environment variable process dot env dot user endpoint since this is a api call we'll have to use await and make our function async and let's just console log the user details to see if our endpoint variable works we'll start the development server again let's refresh the index page and here you can see that the api data was fetched and we were able to use this environment variable which refers to the value of another environment variable successfully in our server side props function the dollar sign is a reserved character here in dot env so if your string let's say has an actual dollar sign value for example some passwords i've seen looking like this so to store such values you'll have to escape the dollar sign by adding the backslash character so i'll have to store the password like this just a little something to keep in mind if the value of your environment variables has a dollar sign now the last thing that i wanted to talk about dot files is that how you name your dot file actually matters especially when you're running a development server versus a production server so in our current example we were running the development server because we were using the command npm run dev to start our application what npm run dev does is it sets an environment variable called no dnv to the value of development and for a dot env file we have named the file as simple.env but if we notice here this is the last name that is taken into preference not to prove that the environment variables will be overridden depending on their name i'll be creating more dot env files right now there are three dot files called dot envy.development and dot unit.production now as per this particular preference when we run npm run dev our dot development file will be given more preference over the dot env file and when we run npm start our dot env dot production will be given more preference over dot env so let's quickly go ahead and prove this overriding preference structure so i'll be running the command npm run dev and since the node environment will be set to development the env file which should be getting preference is r dot env dot development and the password that will be printed will be dev password so i'll hit enter refresh our page and as you can see the password is dev password similarly let's run npm start we'll refresh our index page and since next start sets the node environment to production this time we'll be seeing the password that's being picked up from the dot env dot production file which is production password so in both our npm run dev and npm start cases the dot env was overridden by the respective environment dot files but prior to version 9.4 if you wanted to declare environment variables in next years you had to update them inside the next config.js file do not skip this part because this particular config file is still valid and i'll show you a very cool trick which you can also use while writing environment variables in this config file so to use nextconfig.js to inject environment variables all i need to do is create a file called nextconfig.js so i'll go back to our project in the root directory i'll create next.config.js and all this file needs to do is export an object with the key env and this env key stores an object with the actual environment variable key along with their values so following the standard naming convention i'll create an environment variable called secret and keep the values my secret let's say and then to test if this particular environment variable was created in our index file let's just try to log this one i'll remove the other logs for now and let's also console log this on the client side to check if this variable is being loaded in both server and client side let's start our development server you'll be able to see now the secret value is loaded in both the client side and the server side so whenever you load an environment variable using next.config.js it adds the environment variable both to your backend environment and also your client bundle so be aware of this fact but as i said one little cool thing that you can do here is that since this is a javascript file you can write javascript code to fetch the value of your environment variables for example i'll be creating a new environment variable called author now its value i'd like to keep as the author that's present in my package.json so i want this particular author key to be read and stored as an environment variable for that i'll be creating a function up here called fetch author and since i have to read a file i'll also import the file system module so i'll say constfs require the fs module here inside the function i'll just called fs dot read file sync and i want to read the package dot json file now since i only want the key author i'll pass this whole file as a javascript object and i'll restructure the author value from it so that's it and this function in the end just returns this author value now instead of having a hard coded string i can call my fetch author function store this and let's see if we can access this particular environment variable so in our index.js instead of printing secret i'll print the author environment variable save the changes start a development server again and we'll refresh our index page and as you can see both on the client side and server side the author name was fetched with the help of this little function here now this was the last little thing that i wanted to discuss if this video helped you in any way please hit on the like button and share it with someone else if you feel that it might help them also subscribe to the channel if you're not subscribed already i post new videos every week and i'll be seeing you guys in the next one
Info
Channel: Mayank Srivastava
Views: 8,676
Rating: undefined out of 5
Keywords: next.js, nextjs, next js, nextjs tutorial, nextjs pages, learn nextjs, environment variables, environment variables in nextjs, dotenv, .env, next config, next env var, envvar, env var, environment var, .env.local, .env.development, nextjs build, build, process.env, environment variable, next.config.js, nextjs config, runtime config
Id: WSjIeZ7y00U
Channel Id: undefined
Length: 14min 15sec (855 seconds)
Published: Sat Apr 23 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.