While working on my nextjs project, I have encountered an issue with setting environment variables that can be accessed at the browser level.
Whenever I use console.log(process.env)
, it always returns {}
in the javascript console, and any variable like process.env.<variable>
shows an undefined
value.
I have tried following the instructions for setting up environment variables using next.config.js and .env file with the NEXT_PUBLIC_
prefix. However, none of these methods have worked for me. I believe that most of the information I found does not apply in my case because I am using
"type": "module"
in my package.json
file:
{
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"test": "NODE_ENV=test mocha --require @babel/register --require ignore-styles",
"run": "--require @babel/register --require ignore-styles"
},
"dependencies": {
....
},
"devDependencies": {
"@babel/core": "^7.21.0",
"@babel/plugin-transform-modules-commonjs": "^7.21.2",
"@babel/register": "^7.21.0",
"babel-preset-react-app": "^10.0.1",
...
},
"type": "module"
}
Here is my next.config.js
file:
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
env: {
custom_key: 'test1234',
TEST: 'asd!!'
},
pageExtensions: ['mdx', 'md', 'jsx', 'js', 'tsx', 'ts'],
webpack: config => {
config.module.rules.push(
{
test: /\.html$/i,
loader: "html-loader",
}
);
config.resolve.extensions = ['.ts', '.tsx', '.js', '.jsx', ...config.resolve.extensions]
return config;
}
};
export default nextConfig;
However, when I try to access process.env.custom_key
or process.env.TEST
, I always receive undefined.
I have also attempted to define these variables (e.g. NEXT_PUBLIC_TEST
) in the .env
or .env.local
files, but in that case, I still get
process.env.NEXT_PUBLIC_TEST = undefined
.
Everywhere I look, the solution suggested involves using:
module.exports = {
env: {
customKey: 'my-value',
},
};
However, due to using
"type": "module"
, I am unable to use this. So, my question is, what am I missing here? Is my nextConfig incorrectly defined? What do I need to change in order to use environment variables at the browser level?
At the server level, process.env
seems to be working fine as it prints everything from my .env
and env.local
files, but does not reflect what I have in the next.config.js
file.