PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 18, 2022

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

 August 18, 2022     environment-variables, libs, nrwl-nx     No comments   

Issue

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.



Answered By - Ali Shabani
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing