With server side rendering we need to consider where the variable is readable
Also, there are three ways we can get environment varialbes in NextJS without installing other packages:
Additionally, it's possible to pass a process.env environment variable through either of the next.config.js mechanisms.
In package.json we add an environment variable (MYVAR) to our dev script.
{
"name": "somename",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"dev": "MYVAR=MyVar next",
"build": "next build",
"start": "next start"
},
....
}
We'll create a new file named 'next.config.js' in the project root.
//next.config.js
module.exports = {
serverRuntimeConfig: {
myvarpass: 'server-runtime ' + process.env.MYVAR,
},
publicRuntimeConfig: {
myvarpass: 'public-runtime ' + process.env.MYVAR,
},
env: {
myvarpass: 'build-time ' + process.env.MYVAR
}
}
To view results lets also create a page pages/index.js with console.logs.
//pages/index.js
import getConfig from 'next/config'
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig()
....
static async getInitialProps({req}) {
console.log('getInitialProps')
console.log('index: ' + serverRuntimeConfig.myvarpass) // Will only be available on the server side
console.log('index: ' + publicRuntimeConfig.myvarpass) // Will be available on both server and client
console.log('index: ' + process.env.myvarpass)
console.log('index direct: ' + process.env.MYVAR)
}
Now we can see how the pages/index.js logs differ between client and server.
Results on Server:
index: server-runtime MyVar
index: public-runtime MyVar
index: build-time MyVar
index direct: MyVar
Results on Client:
index: undefined
index: public-runtime MyVar
index: build-time MyVar
index direct: undefined
So far so good. We can see that using process.env is not available on the client. Which is why NextJS added these other possibilities.
Remember some of these variables are written at build time. Remember to do a build.
It may be because of where you set the environment variable
Shown below is incorrect. The environment where MYVAR is set is not the same as where 'next' was run:
$ MYVAR=MyVar
$ npm run dev
Instead, try setting the var in the package.json scripts:
// add the var to your script instead
"scripts": {
"dev": "MYVAR=MyVar next",