Blog>
Snippets

Adding Custom Environment Variables

Explain the process of adding custom environment variables in a Next.js application, including prefixing with NEXT_PUBLIC_ for client-side access.
// In next.config.js
module.exports = {
  env: {
    CUSTOM_VAR: process.env.CUSTOM_VAR
  }
};
In the next.config.js file, you can specify custom environment variables that should be available to the Next.js server-side code. Here, `CUSTOM_VAR` is an example of a server-side environment variable.
// Prefixing with NEXT_PUBLIC_ to expose the variable to the client-side
module.exports = {
  env: {
    NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL
  }
};
For an environment variable to be exposed to the client-side browser code, its name must be prefixed with `NEXT_PUBLIC_`. In this example, `NEXT_PUBLIC_API_URL` is a variable that will be accessible both server-side and client-side.
// Using the environment variable in a component
const Component = () => (
  <div>
    The API URL is {process.env.NEXT_PUBLIC_API_URL}.
  </div>
);
In a Next.js component, the environment variable prefixed with `NEXT_PUBLIC_` can be accessed directly using `process.env.NEXT_PUBLIC_API_URL`. This shows how to use the variable within JSX.