NestJS env variable undefined - javascript

I'm trying to set configuration variables on my project using the official documentation.
I added the following line to my app.module.ts imports:
ConfigModule.forRoot({
isGlobal: true
}),
I created a .env file at the root of my project with the following content:
MY_VARIABLE=myself
And I use dependecy injection to get access to the configuration service:
constructor(private configService: ConfigService) {}
However the following line logs 'Env variable: undefined'
console.log('Env variable: ', this.configService.get<any>('MY_VARIABLE'));

Several scenarios:
You don't have .env file
.env is incorrectly defined
You're trying to access environmental variables from .env located outside the server's root path
You need to install dotenv package
Deploying to Serverless and in the functions (or other deployable folder) the .env is missing (even though it's in the root location it has to be there too)

Related

Allowing access to process and process.env in Webpack 5

I'm using environment variables to set the basename of a react-router-dom BrowserRouter. However, Webpack 5 does not allow accessing environment variables.
From other stackoverflow questions, I've seen that using this:
new webpack.ProvidePlugin({
process: 'process/browser',
})
makes process available. However, process.env is empty ({}).
Also, if I use
const dotenv = require('dotenv')
dotenv.config();
console.log(process.env);
I can see the variables in my .env file are present in process.env in the config file but I can't find a way to make them accessible from process.env in the code.
I have tried:
new Dotenv({ systemvars: true })
And some other plugins suggested in Webpack: Bundle.js - Uncaught ReferenceError: process is not defined but adding any other plugin other than the 'process/browser' makes process not defined again.
I know there's a reason behind not allowing the use of process.env but I do need it.
Did you check this?
DotenvPlugin
The third-party DotenvPlugin (dotenv-webpack) allows you to expose (a subset of) dotenv variables:
new Dotenv({
path: './.env', // Path to .env file (this is the default)
safe: true, // load .env.example (defaults to "false" which does not use dotenv-safe)
});

How to avoid getting wrong data from process.env file?

I need to get some data from a .env.local file,however instead of getting the data of the file on the current folder i get the one from another project that i had made.
How can I make node recognise the right file to read?
example:
folder-structure:
folder:
file.js
.env.local
js file:
const envData ={
test1: process.env.TEST_1,
test2: process.env.TEST_2,
test3: process.env.TEST_3,
})
.env.local file:
TEST_1=test1-data
TEST_2=test2-data
TEST_3=test3-data
The problem is:I don't get the data from the env file in my folder but from another one,how do I fix this?
I'd recommend using dotenv to manage your environment variables -- it loades environment variables from a .env file into process.env. So you'll have your .env file within your project folder and then whichever folder you need to load your env variables in, you'll require and configure the package at the top of the file like so:
require('dotenv').config();
Which will allow you to call your env variables like process.env.XXX.

Can't pull sqs queue name from .env file in nestjs

When pulling the queue name through .env file I get the following error on the console:
Cannot read properties of undefined (reading 'meta').
How can I pass queue name from .env file to nestjs #SqsMessageHandler decorator?. I am using #ssut/nestjs-sqs library.
#SqsMessageHandler(process.env.QUEUE_NAME, false)
public async handleMessage(message: AWS.SQS.Message) {
console.log(message);
}
#SqsConsumerEventHandler(process.env.QUEUE_NAME,'processing_error',
)
public onProcessingError(error: Error, message: AWS.SQS.Message) {
// report errors here
console.error(error);
console.error(message);
}
The problem is that the process.env.QUEUE_NAME is not available at the time you're using it. You'll need invoke dotenv (or whatever package that read & parse the env file) by yourself if you want to use process.env. like this.
imports: [
...
ConfigModule.forRoot({
envFilePath: '.env',
}),
],
You can add env file import like this in your Sqs module, which is >the standard way of using .env files in a NestJS module.
I realized later that this doesn't work for registering the queue, or for the decorators. We ran into the same issue, the env vars are available inside the modules but not during build, and nest ignores
Depending on how you start your services you do these:
NPM Scripts
Inside your package.json add the env vars:
"start:dev": "QUEUE_NAME=your_queue_name nest start --watch"
Docker
Add your env var before the node build step inside your Dockerfile.
ENV QUEUE_NAME your_queue_name

How to make .env variables work inside JS class constructors?

I'm working on a Node/Express project. Most of the code is contained in files that are inside folders, so that a folder named 'controllers' contains all of the project's controllers, a folder named 'services' contains all of the project's services etc. The code that starts the server is inside a file called app.js which is directly in the project root.
All controllers and services are declared as JS classes and contain a constructor. Dotenv is loaded inside app.js and env variables work nicely everywhere BUT inside class constructors, as those seem to be loaded before dotenv is initialized.
An example of the class syntax used:
export default class exampleService {
constructor() {
console.log('This is not working', process.env.EXAMPLE); // process.env.EXAMPLE is undefined
}
myFunction() {
console.log('This works just fine', process.env.EXAMPLE); // process.env.EXAMPLE is exactly how it's defined in .env
}
// All other class methods are here.
}
Is there a way I could get dotenv variables to work inside class constructors without having to import and init dotenv in the beginning of each class file?
If I do resort to importing dotenv individually to each class file, will it have any other cons besides making the code less clean?
Try loading the application with preload on dotenv (copied from the source):
Preload
You can use the --require (-r) command line option to preload dotenv. By doing this, you do not need to require and load dotenv in your application code. This is the preferred approach when using import instead of require.
$ node -r dotenv/config your_script.js
The configuration options below are supported as command line arguments in the format dotenv_config_<option>=value
$ node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/your/env/vars
Additionally, you can use environment variables to set configuration options. Command line arguments will precede these.
$ DOTENV_CONFIG_<OPTION>=value node -r dotenv/config your_script.js
$ DOTENV_CONFIG_ENCODING=latin1 node -r dotenv/config your_script.js dotenv

Cannot specify url in .env file vue cli 3

I'm referring to the documentation about environment variables in vue cli 3.
I'm able to set it up and get simple variables to show up but my url in the .env file doesn't show up.
Contents of the .env file:
FOO=bar
VUE_APP_SECRET=secret
API_URL="https://staging.something.org"
Here is how I'm viewing the env:
console.log(process.env)
BASE_URL: "/"
NODE_ENV: "development"
VUE_APP_SECRET: "secret"
The API_URL is not visible, am I doing something wrong?
Refer to the documentation.
Only variables that start with VUE_APP_ will be statically embedded into the client bundle with webpack.DefinePlugin. You can access them in your application code:
Your VUE_APP_SECRET is accessible because it's prefixed with VUE_APP_. Use VUE_APP_API_URL instead of API_URL to access it in your frontend.
Since CLI 3, Vue recognizes variables in dotenv only when adding the prefix VUE_APP_
When making changes, restart CLI.

Categories

Resources