Next.js private environment variable

Hello everyone!

We are having issues using a secret environment variable in our next.js getStaticProps functions.

We created a set of public and private environment variables in each context of our application through the netlify.toml file as stated here

Public next.js variables are working as expected server and client side, but our secret variables are undefined by the time the on demand functions access them. Here is a sample code of our implementation:

  command = "npm run build"
  publish = "out"

  package = "@netlify/plugin-nextjs"

  directory = "functions/"

  SECRET = "prod-dummy-secret"
  NEXT_PUBLIC_VAR = "prod-example"

  SECRET = "staging-dummy-secret"
  NEXT_PUBLIC_VAR = "staging-example"

  SECRET = "preview-dummy-secret"
  NEXT_PUBLIC_VAR = "preview-example"

And then our page componente uses incremental static regeneration as follows:

export const getStaticPaths: GetStaticPaths<MyProps> = () => {
  return {
    paths: [],
    fallback: 'blocking',

export const getStaticProps: GetStaticProps<Partial<MyProps>, PathParams> = async ({ params }) => {
  const foo = myServiceMethod();

  return {
    props: { foo },
    revalidate: 300,

Finally here is the service trying to access the secret var

export function myServiceMethod(): string {
  try {
    console.log(process.env.SECRET) // undefined
  } catch (err) {
    throw err;

found this plugin in another topic. The plugin author states that functions can’t access netlify.toml env variables at runtime


This is when your function code is evaluated when a request was received. The following environment variables would be available at runtime:

  • Environment Variables you set at Netlify UI

no where in the docs I can find a reference to this information but I’m gonna try the plugin anyway

well apparently it is true that netlify functions can’t access env variables defined in the netlify.toml at runtime. This is something major that should be stated in netlify’s next.js or functions documentation, not sure why is not there but to everyone having similar issues be aware of it.

Unfortunately the plugin didn’t work for me, so to fix our critical issue we decided to use a global secret through netlify’s env variables UI, not quite what were looking for but it works for now

Hi there, @raczosala :wave:

Thanks so much for the detailed posts and for sharing the solution that you implemented, it will definitely be beneficial to future Forums members who encounter something similar. I have shared your feedback with our Documentation team so that they can look into this further. Thanks again :netlisparkles: