Setting Environment Variables for Client and Server in Next.js
With SSR the concept of an environment variable gets a bit more complex
With server side rendering we need to consider where the variable is readable
-
on server
-
on client
-
on both
Also, there are three ways we can get environment varialbes in NextJS without installing other packages:
-
"directly" via process.env
-
with next.config.js at build time
-
with next.config.js at run time
Additionally, it's possible to pass a process.env environment variable through either of the next.config.js mechanisms.
A demonstration of these four methods
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