Check the Environment
- Make sure that your code is running in the right environment. The "process" variable is only available in Node.js and should not be used in client-side code in Next.js.
- Use conditional checks to ensure code using "process" is only executed on the server side, such as by checking
typeof window === 'undefined'
.
Use Environment Variables in Next.js
- Define environment variables using Next.js's built-in mechanisms. Create a
.env.local
file at the root of your project to define your variables.
- Prefix the names of these variables with
NEXT_PUBLIC_
if they are needed on the client side. For example:
# .env.local
NEXT_PUBLIC_API_URL=http://example.com/api
- Use these variables in your components or pages by accessing them via
process.env
. For example:
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
Modify Next.js Webpack Configuration
- Adjust Webpack configurations in
next.config.js
. Set up environment-specific constants using Webpack's DefinePlugin, which can replace process
with necessary substitutes during the build.
- Modify the
webpack
key in next.config.js
:
module.exports = {
webpack: (config) => {
config.plugins.push(
new webpack.DefinePlugin({
'process.env.CUSTOM_VARIABLE': JSON.stringify(process.env.CUSTOM_VARIABLE),
})
);
return config;
},
};
- This approach allows you to bind certain environment variables during build time, thus sidestepping runtime access issues.
Server-Side Configuration
- For server-exclusive configurations or checks, place the code within the
getServerSideProps
or getStaticProps
methods, where the Node.js environment is guaranteed. For example:
export async function getServerSideProps() {
const secret = process.env.SECRET_KEY;
return {
props: {
secret,
},
};
}
- This ensures that your Node.js-specific code doesn't leak to the client side, preventing any reference errors related to "process".
Reevaluate Global Overwrites
- If a library or part of your codebase inadvertently overwrites the global
process
object, it would lead to a reference error. Check for any code that may modify or mock process
globally.
- Ensure that such libraries have been correctly configured to only mock
process
when necessary, e.g., during testing.
Upgrade Packages
- Dependencies could sometimes conflict with the latest version of Next.js, causing unexpected environmental access issues. Ensure all packages are up-to-date by using:
npm update
- Review release notes of Next.js updates for any breaking changes related to environmental variables or build-time access to
process
.