Search code examples
environment-variablesnrwl-nxlibs

how to use environment variables in nx monorepo libs, exporting to multiple Nextjs apps


I'd like to load some environment variables into functions within my libs, and then be able to re-export this to several different Nextjs applications. i.e.

Within libs/api

export const getDatabaseConnection = () => {
  const host = process.env.DB_HOST
  const username = process.env.DB_USERNAME
  ...
  return newDatabaseConnection
}

Within apps/myNextJSApp:

import { getDatabaseConnection } from '@myProject/api'

...
const databaseConnection = getDatabaseConnection()
...

When I run nx run myNextJSApp:serve it's unable to pull the environment variables from the .env within the root directory, however if I run nx run api:test it's completely happy. I think I could pull the environment variables from each app individually, and then pass them as params into my library functions, but this seems kind of tedious, and I was hoping theres a blanket solution to this where I could build my library modules with the environment variables, and export them to my NextJS apps.


Solution

  • Environment variables don't suppose to share by multiple apps. And it's better that you don't do it either. Every app you're creating should have its environment file. And don't read the environment from your libs directly. You must load the environment variable in your app and pass it to the lib.

    For example, pass the needed config to the libs function:

    
    // libs/api
    export const getDatabaseConnection = ({host, username}) => {
      const host = host
      const username = usename
      ...
      return newDatabaseConnection
    }
    
    // apps/nextjs
    import { getDatabaseConnection } from '@myProject/api'
    
    ...
    const databaseConnection = getDatabaseConnection({
      host: process.env.DB_HOST,
      username: process.env.DB_USERNAME
    })
    
    

    This way, your code is more reusable and maintainable.
    And as I said, don't ever share your environment variables between apps.