0

Is there a way to set env variables outside of a pages directory in NextJS? I have a util function that provides the base API route in one place. However, since this is a util function it's not defined on a page. I'd like to avoid having to create a getStaticProps on every page to get my private env variables if possible.

Any thoughts?

utils/index.ts (not on a nextJS page)

export const apiAddress =
  process.env.NEXT_PUBLIC_CURRENT_ENV === 'PRODUCTION'
    ? process.env.PROD_API
    : process.env.DEV_API;

... 
kevin
  • 2,707
  • 4
  • 26
  • 58
  • Yeah, you can create a util function outside of the pages directory and even call that function from child components deep inside the component tree. As long as the util function have access to the process, it works fine. – Junaid Faryad Sep 20 '21 at 19:36
  • You should probably define a `NEXT_PUBLIC_API` variable inside [both `.env.development` and `.env.production`](https://stackoverflow.com/a/61750672/1218980) with their respective values. – Emile Bergeron Sep 20 '21 at 19:53
  • @EmileBergeron I was using them that way previously but I couldn't get them to play with with the env vars i was setting up heroku. For example, for the review, staging, and prod deploys I have a env value assigned to `NEXT_PUBLIC_CURRENT_ENV` on heroku – kevin Sep 20 '21 at 20:00
  • as of now, i can consume `NEXT_PUBLIC` paths just fine, but as far as I've seen, anything that's _not_ marked `NEXT_PUBLIC` is _only_ accessible in pages under getStatic/getServerSide props. So, I'm curious if there is a way to get around the getStatic/getServer pages restriction if I wanted private vars in my utils or something outside of `/pages` – kevin Sep 20 '21 at 20:01

1 Answers1

1

I had a similar issue where I couldn't access my env vars in the nextjs application.

The solution was to read them in the next.config.js and pass them implicitly.

My example loads the environment from /environments/env.development but you can use any location you want.

So my next next.config.js looks like this:

const path = require('path')
const { parsed: localEnv } = require('dotenv-safe').config({
   allowEmptyValues: false,
   path: path.resolve(__dirname, `environments/.env.development`),
})

const nextConfig = {
   env: localEnv,
}

module.exports = nextConfig

You should be able to access the ENV vars in your .env file like usually:

process.env.YOUR_VARIABLE

Additionally

Based on environment, you can use a predefined ENV var from your package.json as well which lets you load the right file for your environment.

In your package.json define sth. like that in scriptssection:

"dev:development": "ENV=development node server.js",
"dev:staging": "ENV=staging node server.js"
...

Then you have access to the ENV var and can use it directly for your purposes in next.config.js.

Based on example above:

path: path.resolve(__dirname, `environments/.env.${process.env.ENV}`),
monkey-0001
  • 442
  • 6
  • 14