Attention: After Next 9.4 environment variables in Next.js become much easier than before. This video is accurate up to 9.3 only!! For new environment versions you can check: nextjs.org/docs/basic-features/environment-variables
Those new NEXT_PUBLIC_ variables are only build time variables, not runtime. So your video is still accurate about runtime variables I believe. And publicRuntime variables are only used when using serverSideProps or getInitialProps. At least, that's what I understand about them.
You are 100% correct, the NEXT_PUBLIC_MY_VAR, will only be set at build time and you can't "override" that one at build time :) Now in Next.js, your other environment variables (the ones that don't start by NEXT_PUBLIC_) you can set them at build time and "override" at runtime, without having to use the serverRuntimeConfig :) I started to code an example here on the youtube comment section, but youtube comments destroyed the code formatting completely, so I pushed into github: github.com/bmvantunes/nextjs-env-variables-youtube-comment-example/commit/0641758e198f0977d88f298959a779d56b8c3cf6 Let me know if you can see those 2 files in the commit. I'm setting 2 environment variables at build time, and then "overriding" them at runtime, one is NEXT_PUBLIC_, the other isn't. By running "npm run build && npm start" and navigating to your browser on localhost:3000/youtube-comment The result: ``` NEXT_PUBLIC_VAR1 = public-build-var1 FROM SERVER: NEXT_PUBLIC_VAR1 = public-build-var1 --------------------- VAR1 = ----- FROM SERVER: VAR1 = private-runtime-bruno ``` As you can see the NEXT_PUBLIC_ variables, we can't override at runtime, but all the others we can :) That means that we don't need to use serverRuntimeConfig anymore. Regarding publicRuntimeConfig we only need to use it if we don't wan't/can't pass those from the server like I did in this example. That being said, publicRuntimeConfig still has it's place, but we can overcome as I did on this example =) If you go the other page there using getStaticProps (localhost:3000/youtube-comment-getstaticprops) - the code is exactly the same, but replacing getServerSideProps by getStaticProps, the result will be: ``` NEXT_PUBLIC_VAR1 = public-build-var1 FROM SERVER: NEXT_PUBLIC_VAR1 = public-build-var1 --------------------- VAR1 = ----- FROM SERVER: VAR1 = private-build-bruno ``` In this page, as expected the only values are the ones set at build time =) I know I wrote a bit too much in this comment, but I hope this example helps, if it doesn't, please let me know and we can go in more detail =D
Great example! Let me explain my use-case (which might be a bit out-of-scope, but it describes my issues). First let me explain the architecture. I use DTAP, so I have different environments. Let's limit it to test and production. Both of those environments have a graphql server (not build in nextjs) and a nextjs app. I build using docker and deploy to kubernetes (doesn't matter where I deploy actually). Now let me explain the NextJs app I have an ApolloProvider in `_app.js` which is configured to use an url from env variables. Because this graphql server is not part of the NextJS app, but is hosted elsewhere on another domain, I need to configure this in my application, during runtime. Because I don't want to build a different image per environment. I want to have server side rendering using that graphql server, and client side rendering using that same graphql server. Which means I can not use static pre-generation, because then the variables are unset in the browser. I always need server side rendering. I think I have to setup some graphql http-proxy, or use schema stitching with a graphql server also built in the nextjs app. Because then the graphql proxy or server can use server side variables to determine, to which graphql backend server I need to proxy to.
I am already using Next.js in production for already 2 years and it's great. I viewed part 1 to part 10 in 2 days and I can say that your content is awesome and it's a pleasure to watch even if I don't know typescript and I use MongoDB (with Mongoose)
Thank you very much 😀😀 keep in mind that after next 9.4 you can have environment variables in a easier way 😀 check the url I have in the pinned comment 😍😍😍
I'm not too bad, but I can't say the same about my dell (computer) 😩 I think it will "die" sooner or later - I think I'm getting closer and closer to go back to apple after this 2 years using Windows 🤣🤣
Bruno digging deeper in the type of env var you described, there are some ones which are available at build time and some ones at run time. I'm not used to have var at build time, thinking a use case for them could be the database connection or api endpoint to be consumed when generating static content (getStaticProps / getStaticPaths) Otherwise what could be something like step useful? That being said, we need to build for each env we have, I was used to have the same bin and deploy with different configuration across different envs. Sorry if the question is out of scope but could you please clarify it?
Really good question Sergio =) Basically we need to differentiate what is front-end code and back-end code. For example, imagine you have a react application, most of the times that application is served from a CDN - where you don't have any environment variables at all (Your react code is not running there, only being served as static files from there). The same kinda applies if you are serving a static react app from your server (react will not be running on your server). In the scenario I described before, environment variables at build time are your only option - If you don't want to use environment variables at build time then when your react application runs the first time, it needs to make an HTTP call to your server to get the environment variables, which is a bit of a performance hit for your users - that being said a lot of companies do this =) For code that will run on your server (or anywhere you control), you can have runtime environment variables. Next.js itself, has SSR (server side rendering), so you can use runtime environment variables in those scenarios. But in scenarios where you use SSG (static site generation) and you deploy to a CDN or github pages (for example), you have no access/control to runtime environment variables after deployment. You can look at this example (from the video I'm editing today) - bmvantunes.github.io/microphone-store That example, is an application that we built using static site generation (SSG), so I can't access any runtime environment variables in github pages. If I deploy that application to multiple environments I would have to have a build system per environment and build that app multiple times, one per environment (for example, because the databases will be different for each environment) Sorry for the very long answer, I hope it helps you =D PS - I agree that the industry should call different names to build time environment variables and runtime environment variables, the similar names might confuse people =D
@@BrunoAntunesPT Thank you Bruno, for such complete explanation. I think I have a lot of questions now , but the main question and general idea is much more clear! Glad to hear you are working on new videos!
Thank you Sergio 😀 Yes, during the last 3 months without going outside as normal, not able to visit family and friends my brain has been a bit foggy and not that productive for RUclips videos 😔 I'm sorry for that - hopefully my brain will be able to get back to speed in the next few weeks 😉😉
@@BrunoAntunesPT Yes, I'm not an expert but I think that keeping active trying to do what we love can help to overcome these difficult moments. Take care!
I love this. It couldn't be explained better than this. Thanks Bruno... Just to mention: Since we are here customizing *next.config.js* I think we could use the opportunity to get rid of the anoying *relative path* imports for our custom files. that way we do not have to worry about correct path referencing... Just incase anyone is interested, here is a gist in which I customize the *webpack config* and *tsconfig* to allow for *absolute paths* imports: gist.github.com/jermsam/073c717f98d8a32c063daba96b9a3294
I think you'll love to know that you no longer need to do anything inside next.config.js in order for that to work (since next 9.4) 😍😍 Just add a baseUrl in your tsconfig.json (or jsconfig.json if not using typescript). You can read more at: nextjs.org/blog/next-9-4#absolute-imports-and-aliases I love the work the next.js team is doing, absolutely amazing ♥️♥️♥️
Thank you =) Please read the pinned comment in this video =D You'll understand why I didn't talk about .env.local - Basically it was not launched yet at the time =D
After version 9.4 of next.js you don't need any of that, which is fantastic (I think I have a pinned comment in this video with the URL for the docs) =D
@@BrunoAntunesPT Hello Bruno, base on the next docs i think using environment variables in .env.local is much better than next.config.js. for example in .env.local: DB_PASS=mypassword (good for secrets) This loads process.env.DB_PASS into the Node.js environment . NEXT_PUBLIC_ANALYTICS_ID=abcdefghijk here the process.env.NEXT_PUBLIC_ANALYTICS_ID will be inlined into JavaScript sent to the browser because of the NEXT_PUBLIC_ prefix.
This video was recorded during next 9.3 days 😊 The feature you are talking about (next public) is quite new - next 9.4 - you can read more at nextjs.org/blog/next-9-4#new-environment-variables-support
Next.js is moving at a very rapid pace at this stage, which is great news Sadly, at the same time it is a bit frustrating for people learning it now because it's always changing 😅
:c Hope u can make a video how to connect to mongode use mongoose in future. Still watching your series, but stuck on connect to db now. Don't understand this error: ReferenceError: Cannot access 'mongoose' before initialization.
I'm sorry to hear that my friend :( At the moment I don't have any video planned using MongoDB - even tho, I'm sure I'll do one video about it, sooner or later :) In the meantime, I found a really nice guide using MongoDB and Next.js in the MongoDB website. I read though it and looks really really good - it even teaches you how to create a MongoDB instance in Atlas (their cloud service with a free tier). This is the URL to the article: developer.mongodb.com/how-to/nextjs-building-modern-applications Let me know if the article helped you out =)
If I understood correctly your question, yes. All your environment variables will be available via process.env.YourVarName 🙂 but not sure if that was your question 🙂
I'm hosting everything I have in vercel and azure at the moment 😊 In vercel it is super super easy 😍😍😍 I can make a video for azure, but I'm not working enough with aws at this moment 😅
@@BrunoAntunesPT Whatever you are using, show us. I get very confused when it comes to hosting React Next.js apps. Also, how we can update our site code after it's uploaded to azure/aws if we want to change anything.
You are great how can make log out and use privileges like when I have index page: app.com home page: app.com => but content will change after login How can do that? I hope you understand my words and this situation
Thank you Ahmed 😊 Regarding logout you'll need to store some kind of state in your backend (for example in a database). With that you'll know which tokens are valid and which ones are not. With that you can also do what applications like Facebook do - having the possibility to "logout" specific devices that you own. Regarding the other question a simple if else for your logged in state does the trick. You check if you are logged in, if you are show A if not show B. I hope this is helpful ☺️☺️
Imagine someone has your previous valid jwt token they can still enter the application as you 😊 So deleting only from your browser is not enough - if we are talking about jwt tokens 😅
That's amazing!!! Congratulations my friend 😀😀 I'm really happy I could play a little part on it. It is amazing to know this stories ❤️❤️❤️ BTW, I added a pinned comment for new viewers of the video with the url to the new env variables documentation. I may create a video to replace this one 😃😃
Attention: After Next 9.4 environment variables in Next.js become much easier than before. This video is accurate up to 9.3 only!!
For new environment versions you can check: nextjs.org/docs/basic-features/environment-variables
Those new NEXT_PUBLIC_ variables are only build time variables, not runtime. So your video is still accurate about runtime variables I believe. And publicRuntime variables are only used when using serverSideProps or getInitialProps. At least, that's what I understand about them.
You are 100% correct, the NEXT_PUBLIC_MY_VAR, will only be set at build time and you can't "override" that one at build time :)
Now in Next.js, your other environment variables (the ones that don't start by NEXT_PUBLIC_) you can set them at build time and "override" at runtime, without having to use the serverRuntimeConfig :)
I started to code an example here on the youtube comment section, but youtube comments destroyed the code formatting completely, so I pushed into github: github.com/bmvantunes/nextjs-env-variables-youtube-comment-example/commit/0641758e198f0977d88f298959a779d56b8c3cf6
Let me know if you can see those 2 files in the commit.
I'm setting 2 environment variables at build time, and then "overriding" them at runtime, one is NEXT_PUBLIC_, the other isn't.
By running "npm run build && npm start" and navigating to your browser on localhost:3000/youtube-comment
The result:
```
NEXT_PUBLIC_VAR1 = public-build-var1
FROM SERVER: NEXT_PUBLIC_VAR1 = public-build-var1
---------------------
VAR1 = -----
FROM SERVER: VAR1 = private-runtime-bruno
```
As you can see the NEXT_PUBLIC_ variables, we can't override at runtime, but all the others we can :)
That means that we don't need to use serverRuntimeConfig anymore. Regarding publicRuntimeConfig we only need to use it if we don't wan't/can't pass those from the server like I did in this example. That being said, publicRuntimeConfig still has it's place, but we can overcome as I did on this example =)
If you go the other page there using getStaticProps (localhost:3000/youtube-comment-getstaticprops) - the code is exactly the same, but replacing getServerSideProps by getStaticProps, the result will be:
```
NEXT_PUBLIC_VAR1 = public-build-var1
FROM SERVER: NEXT_PUBLIC_VAR1 = public-build-var1
---------------------
VAR1 = -----
FROM SERVER: VAR1 = private-build-bruno
```
In this page, as expected the only values are the ones set at build time =)
I know I wrote a bit too much in this comment, but I hope this example helps, if it doesn't, please let me know and we can go in more detail =D
Great example! Let me explain my use-case (which might be a bit out-of-scope, but it describes my issues).
First let me explain the architecture.
I use DTAP, so I have different environments. Let's limit it to test and production. Both of those environments have a graphql server (not build in nextjs) and a nextjs app.
I build using docker and deploy to kubernetes (doesn't matter where I deploy actually).
Now let me explain the NextJs app
I have an ApolloProvider in `_app.js` which is configured to use an url from env variables. Because this graphql server is not part of the NextJS app, but is hosted elsewhere on another domain, I need to configure this in my application, during runtime. Because I don't want to build a different image per environment.
I want to have server side rendering using that graphql server, and client side rendering using that same graphql server. Which means I can not use static pre-generation, because then the variables are unset in the browser. I always need server side rendering.
I think I have to setup some graphql http-proxy, or use schema stitching with a graphql server also built in the nextjs app. Because then the graphql proxy or server can use server side variables to determine, to which graphql backend server I need to proxy to.
I am already using Next.js in production for already 2 years and it's great. I viewed part 1 to part 10 in 2 days and I can say that your content is awesome and it's a pleasure to watch even if I don't know typescript and I use MongoDB (with Mongoose)
Thank you my friend, it's great to hear! =)
I hope you enjoy the next 6 videos I'm doing with Next.js in the series "Building a Car Trader App" =)
The whole series made me to like your video first, then watch. Great playlist Bruno. Blessings for you to get more success. Really helpfull👏
Thank you very much =D
I really really appreciate your comments Amit!
Wow... I was waiting for this kind of tutorial for a long time. Thank you.
Thank you Prince 😊
Glad it was helpful!
First, thanks for the index! I loved that i can just go ahead to what i needed. Very clear explanations and to the point. Keep em comin!
Thank you Jorge 😃😃
Love the content you're producing. Keep up the good work!
Thank you very much 😀😀
keep in mind that after next 9.4 you can have environment variables in a easier way 😀 check the url I have in the pinned comment 😍😍😍
@@BrunoAntunesPT Moderately embarrassed I didn't check the doc's first, thanks for the quick heads up ❤️
No need to be embarrassed, we are not robots ❤️❤️😀
As always the best NextJS video, thank you!
Thank you my dear friend 😍😍😍
You deserve way more subscribers. Amazing series!
Thank you soo much Tanmay 😍😍 I'm very happy you enjoyed the series 🙂😊
Thank you very much for your efforts 🙏 . I get superb information about Next.js with every new video ✨.
Thank you Kasim 😊 that's great to read my friend 😁😁
I am waiting for your next video. I am super excited about that.
Glad to hear that :)
Looking forward to the next series
❤️
Me too ❤️❤️ 😍😍
I love your laugh and your explanation
you are awesome
😅😅😅 Thank you my friend 😊
Thank you so much for this awesome series
Thank you for the support Abesse 😊 ☺️☺️
Thank you so much Bruno. awesome video.
Thank you Sina 😊😊
@@BrunoAntunesPT hey Bruno what's up ?
are you ok?
I'm not too bad, but I can't say the same about my dell (computer) 😩 I think it will "die" sooner or later - I think I'm getting closer and closer to go back to apple after this 2 years using Windows 🤣🤣
Thank you so much, you are awesome :)
Thank you very much Oros 😀😀😀 you are awesome as well, never forget it ❤️❤️
Thank you 🙌
You're welcome 😊
Bruno digging deeper in the type of env var you described, there are some ones which are available at build time and some ones at run time.
I'm not used to have var at build time, thinking a use case for them could be the database connection or api endpoint to be consumed when generating static content (getStaticProps / getStaticPaths) Otherwise what could be something like step useful?
That being said, we need to build for each env we have, I was used to have the same bin and deploy with different configuration across different envs.
Sorry if the question is out of scope but could you please clarify it?
Really good question Sergio =)
Basically we need to differentiate what is front-end code and back-end code.
For example, imagine you have a react application, most of the times that application is served from a CDN - where you don't have any environment variables at all (Your react code is not running there, only being served as static files from there). The same kinda applies if you are serving a static react app from your server (react will not be running on your server).
In the scenario I described before, environment variables at build time are your only option - If you don't want to use environment variables at build time then when your react application runs the first time, it needs to make an HTTP call to your server to get the environment variables, which is a bit of a performance hit for your users - that being said a lot of companies do this =)
For code that will run on your server (or anywhere you control), you can have runtime environment variables.
Next.js itself, has SSR (server side rendering), so you can use runtime environment variables in those scenarios. But in scenarios where you use SSG (static site generation) and you deploy to a CDN or github pages (for example), you have no access/control to runtime environment variables after deployment. You can look at this example (from the video I'm editing today) - bmvantunes.github.io/microphone-store
That example, is an application that we built using static site generation (SSG), so I can't access any runtime environment variables in github pages. If I deploy that application to multiple environments I would have to have a build system per environment and build that app multiple times, one per environment (for example, because the databases will be different for each environment)
Sorry for the very long answer, I hope it helps you =D
PS - I agree that the industry should call different names to build time environment variables and runtime environment variables, the similar names might confuse people =D
@@BrunoAntunesPT Thank you Bruno, for such complete explanation. I think I have a lot of questions now , but the main question and general idea is much more clear!
Glad to hear you are working on new videos!
Thank you Sergio 😀
Yes, during the last 3 months without going outside as normal, not able to visit family and friends my brain has been a bit foggy and not that productive for RUclips videos 😔
I'm sorry for that - hopefully my brain will be able to get back to speed in the next few weeks 😉😉
@@BrunoAntunesPT Yes, I'm not an expert but I think that keeping active trying to do what we love can help to overcome these difficult moments.
Take care!
I have always used dotenv. Never knew something like crossenv existed. Still, I'd prefer dotenv. But thanks for teaching crossenv.
In the newer versions of next you don't need half of this complication. I need to re-do a video about env variables 😄
@@BrunoAntunesPT ya I read the docs from your comment. Thanks for updating in the comment
Yes I always put comments in the videos if something changes, even if it's very minor 😀in this case it's not minor 😅😅
I love this. It couldn't be explained better than this. Thanks Bruno... Just to mention: Since we are here customizing *next.config.js* I think we could use the opportunity to get rid of the anoying *relative path* imports for our custom files. that way we do not have to worry about correct path referencing... Just incase anyone is interested, here is a gist in which I customize the *webpack config* and *tsconfig* to allow for *absolute paths* imports:
gist.github.com/jermsam/073c717f98d8a32c063daba96b9a3294
I think you'll love to know that you no longer need to do anything inside next.config.js in order for that to work (since next 9.4) 😍😍
Just add a baseUrl in your tsconfig.json (or jsconfig.json if not using typescript). You can read more at: nextjs.org/blog/next-9-4#absolute-imports-and-aliases
I love the work the next.js team is doing, absolutely amazing ♥️♥️♥️
but what about .env.local next js docs says it comes with it by defualt and thanks for the video as always good stuff!
Thank you =)
Please read the pinned comment in this video =D You'll understand why I didn't talk about .env.local - Basically it was not launched yet at the time =D
@@BrunoAntunesPT oh ok 👍
@@ruggeddog3103 no problem my friend 😅😅
Could anyone please tell me how can I change .env file values after build without performing rebuild
May i confirm that, is it publicRuntimeConfig key value will not export in build file?
After version 9.4 of next.js you don't need any of that, which is fantastic (I think I have a pinned comment in this video with the URL for the docs) =D
Can you please make a video on how to setup ApolloServer and ApolloClient?
Thank for the suggestion Adam. It will not be part of this series, but in the future we can look into it, for sure! 😁
@@BrunoAntunesPT Awesome thanks.
Thanks for another great tutorial.... i think the repository link in the description is pointing to part-9.
Thank you very much my friend :)
I updated the URL to point to part 10 :D
What is the difference between next.config.js and .env.local in next?
In next.config.js you can configure "everything" related with next.js - including Webpack.
The .env file is only to set environment variables 😊
@@BrunoAntunesPT Hello Bruno, base on the next docs i think using environment variables in .env.local is much better than next.config.js.
for example in .env.local:
DB_PASS=mypassword (good for secrets)
This loads process.env.DB_PASS into the Node.js environment
.
NEXT_PUBLIC_ANALYTICS_ID=abcdefghijk
here the process.env.NEXT_PUBLIC_ANALYTICS_ID will be inlined into JavaScript sent to the browser because of the NEXT_PUBLIC_ prefix.
This video was recorded during next 9.3 days 😊
The feature you are talking about (next public) is quite new - next 9.4 - you can read more at nextjs.org/blog/next-9-4#new-environment-variables-support
@@BrunoAntunesPT Oh No, so a video you made 4 months ago is not the best 'practice' any more. what a mess.
Next.js is moving at a very rapid pace at this stage, which is great news
Sadly, at the same time it is a bit frustrating for people learning it now because it's always changing 😅
:c Hope u can make a video how to connect to mongode use mongoose in future. Still watching your series, but stuck on connect to db now.
Don't understand this error: ReferenceError: Cannot access 'mongoose' before initialization.
I'm sorry to hear that my friend :(
At the moment I don't have any video planned using MongoDB - even tho, I'm sure I'll do one video about it, sooner or later :)
In the meantime, I found a really nice guide using MongoDB and Next.js in the MongoDB website. I read though it and looks really really good - it even teaches you how to create a MongoDB instance in Atlas (their cloud service with a free tier).
This is the URL to the article: developer.mongodb.com/how-to/nextjs-building-modern-applications
Let me know if the article helped you out =)
If you want to grab something from your environment, you can grab something from your environment?
If I understood correctly your question, yes. All your environment variables will be available via process.env.YourVarName 🙂 but not sure if that was your question 🙂
Bruh, is it possible that you create a tutorial on hosting such react next.js app on aws or similar platform.
I'm hosting everything I have in vercel and azure at the moment 😊
In vercel it is super super easy 😍😍😍
I can make a video for azure, but I'm not working enough with aws at this moment 😅
@@BrunoAntunesPT Whatever you are using, show us. I get very confused when it comes to hosting React Next.js apps. Also, how we can update our site code after it's uploaded to azure/aws if we want to change anything.
@@BrunoAntunesPT I will really appreciate 😍😅😅
It sounds good. Now I have my plate a bit full... but as soon as I find a bit of time, I'll prepare a video about deployment 😊😊😊
@@BrunoAntunesPT sure, anytime. Until then I'm going to finish car trader series. :D
How can I do this in development? gives me a defined
Which specific part Juan?
9:32 next config dot J aaass :D
😂😂😂 RUclips automatic captions with file names and technologies gets a bit lost 😂😂😂
You are great
how can make log out and use privileges like when I have
index page: app.com
home page: app.com => but content will change after login
How can do that?
I hope you understand my words and this situation
Thank you Ahmed 😊
Regarding logout you'll need to store some kind of state in your backend (for example in a database). With that you'll know which tokens are valid and which ones are not. With that you can also do what applications like Facebook do - having the possibility to "logout" specific devices that you own.
Regarding the other question a simple if else for your logged in state does the trick. You check if you are logged in, if you are show A if not show B.
I hope this is helpful ☺️☺️
@@BrunoAntunesPT
Thank you for replying ❤️
I will do it
If I have a problem I will let you know 😆
We are looking for next video
Thank you for help 💚
@@BrunoAntunesPT Isn't it possible just to remove the cookie when the user click logout? to have a simpler implementation...
Imagine someone has your previous valid jwt token they can still enter the application as you 😊
So deleting only from your browser is not enough - if we are talking about jwt tokens 😅
@@BrunoAntunesPT Sure, I understand the scenario you describe.
Just to add, the new version made working with environment variables easy...nextjs.org/docs/basic-features/environment-variables
Yes, after 9.4 it is much easier. This video was recorded before 9.4 was out 😊
@@BrunoAntunesPT Ohh to add, you really saved my life, passed an interview because of you. I really appreciate it.
That's amazing!!! Congratulations my friend 😀😀 I'm really happy I could play a little part on it. It is amazing to know this stories ❤️❤️❤️
BTW, I added a pinned comment for new viewers of the video with the url to the new env variables documentation. I may create a video to replace this one 😃😃
@@BrunoAntunesPT Thank you !!!!!