Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

206
Vistas
Set environment variables outside of pages dir in nextjs?

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;

... 
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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}`),
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda