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

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

Related

Variables in .env file is not updated. How to reset

Im building an app with Quasar (vue) where I am using .env file to store my keys to the database. I was going to switch to another instance but after I changed the keys in the env file it still calls the old values of the variables. They seemd to be cached in some way.
Im using dotenv to call the env file.
I have tried of course to reset the history in browser as well as running
npm cache clean --force
How can I reset the env files?
Quasar handles env variables through quasar.config.js file, not separate .env files. See the documentation.
quasar.config.js
module.exports = function (ctx) {
return {
// ...
build: {
// passing down to UI code from quasar.config.js
env: {
API: ctx.dev
? 'https://dev.api.com'
: 'https://prod.api.com'
}
}
}
}
As noted in the docs, if you do want to use .env files you'll have to add the dotenv package to your project and point quasar.config.js to use the env variables set with dotenv
build: {
env: require('dotenv').config().parsed
}

How put API key on env files in a Node.js app?

this is my first time im trying to handle " Web api ", so i took this project to get many call but after it running well, when i try to click to "search" it dosent work,
I guess the problem arises from api call because chrome inspector show me that :
I was able to understand on the different forums, for handling apis call with Node.js that must be encapsulated API calls behind "Environment variable".
That the config.js file
When i try to put on the terminal export env.API_KEY='000000000000000' it made me :
export: not valid in this context: env.API_KEY
I hope you can point me in the right direction, I very tried everything, to run it that.
I personally like to use a npm package called dotenv:
You can install it by running npm i dotenv within your api directory.
Have a file called .env within your api directory which contains all of your environment variables:
APP_ID="000000000000000"
API_KEY="000000000000000"
Then change config.js to load all environment variable files when it is executed by including require('dotenv').config():
require('dotenv').config()
module.exports = {
APP_ID: process.env.APP_ID,
API_KEY: process.env.API_KEY,
BASE_URL: 'https://api.adzuna.com/v1/api/jobs',
BASE_PARAMS: 'search/1?&results_per_page=20&content-type=application/json',
};
Note: you will also want to add .env to your .gitingore so that your sensitive API keys aren't included in your git repository

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

NestJS env variable undefined

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)

Setting default environment variables in Heroku

I'm working on an app that connects to third-party APIs which require the use of an APP ID and SECRET KEY.
I am storing these values as environment variables in heroku, so that I don't need to expose them in my code.
If I deploy to heroku, it will use heroku's environment variables to resolve these API credentials.
If I'm working on it locally, I want to use my config.js module, and lookup the API credentials there. NOTE: This config.js file is included in my .gitignore so that these credentials never end up in the cloud.
The problematic code is this:
var api_secret = process.env.API_SECRET || require('../../config.js').secret;
When I run this locally, I've got no issues. Meaning, it is unable to resolve the environment variable, so instead it uses the secret from within config.js.
When I run it on heroku, it DOES throw an error telling me that module 'config.js' could not be found. This makes sense, because it was never pushed up with the rest of the repo, by virtue that it is in my .gitignore.
Because heroku is parsing through my code before it ever runs, the require('../../config.js') is problematic. It is trying to lookup a file that doesn't exist.
How can I solve the issue of using environment variables when deployed, and the config.js module when running locally?
On the Heroku dashboard for your application, you can set config variables. If you have the Heroku Toolbelt set up on your machine, you can also use:
heroku config:set API_SECRET=secret
See this article for more.
Edit: Think I may have misunderstood the question. I would suggest, if possible, using the dotenv npm package to set your config variables locally.
If not, another thing to check would be that the config.js package is in your package.json file, because Heroku will use this to build your dependencies.
If you do not want to push your config.js to heroky at all, you can just follow the following to determine whether the config file exists or not with a try catch and the file system module:
Check synchronously if file/directory exists in Node.js
In your case:
var fs = require('fs'),
api_secret,
config;
try {
// Check whether config.js exists
config = fs.lstatSync('../../config.js');
// If we reach this line then config.js exists, yay!
api_secret = process.env.API_SECRET || require('../../config.js').secret;
// or alternatively api_secret = require('../../config.js').secret;
// depending on your logic
}
catch (e) {
// else config.js does not exist
api_secret = process.env.API_SECRET
}
To run Heroku commands programmatically, you can set up a free Ruby app and make it do what you want through API calls. Use Heroku-api. See https://github.com/heroku/heroku.rb
If you want to set Heroku commands manually, you can set env variables on Heroku either with the command heroku config:set MYVAR=MYVALUE or through the Heroku dashboard (Click on your app > settings > reveal config vars > edit).

Categories

Resources