Home > Software engineering >  Set environment variables outside of pages dir in nextjs?
Set environment variables outside of pages dir in nextjs?

Time:09-21

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;

... 

CodePudding user response:

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}`),
  • Related