nestjsx / nestjs-config

Config module for nestjs using dotenv :key:
MIT License
698 stars 44 forks source link

Unable to app.get(ConfigService) in main.ts with node lts (12.16.0) #275

Open arvinsingla opened 4 years ago

arvinsingla commented 4 years ago

Issue type:

nestjs-config version v1.4.5

@nestjs/common+core or other package versions

├─┬ @nestjs/common@6.11.7
├─┬ @nestjs/core@6.11.7
├─┬ @nestjs/microservices@6.11.7
├─┬ @nestjs/platform-express@6.11.7
├─┬ @nestjs/swagger@3.1.0
├─┬ @nestjs/testing@6.11.7
├─┬ @nestjs/typeorm@6.3.1

Excepted behavior

ConfigService as available in main.ts by leveraging app.get('ConfigService')

Actual behavior or outcome (for issue)

Application fails to start with the following error.

[Nest] 80230   - 2020-02-18, 1:58:04 p.m.   [ExceptionHandler] Nest could not find ConfigService element (this provider does not exist in the current context)
Error: Nest could not find ConfigService element (this provider does not exist in the current context)
[0]     at ContainerScanner.getWrapperCollectionPairByHost (/Users/arvins/Sites/service/node_modules/@nestjs/core/injector/container-scanner.js:34:19)
[0]     at ContainerScanner.findInstanceByToken (/Users/arvins/Sites/service/node_modules/@nestjs/core/injector/container-scanner.js:20:40)
[0]     at ContainerScanner.find (/Users/arvins/Sites/service/node_modules/@nestjs/core/injector/container-scanner.js:13:21)
[0]     at NestApplication.find (/Users/arvins/Sites/service/node_modules/@nestjs/core/nest-application-context.js:197:38)
[0]     at NestApplication.get (/Users/arvins/Sites/service/node_modules/@nestjs/core/nest-application-context.js:43:25)
[0]     at /Users/arvins/Sites/service/node_modules/@nestjs/core/nest-factory.js:111:40
[0]     at Function.run (/Users/arvins/Sites/service/node_modules/@nestjs/core/errors/exceptions-zone.js:8:13)
[0]     at Proxy.<anonymous> (/Users/arvins/Sites/service/node_modules/@nestjs/core/nest-factory.js:110:46)
[0]     at /Users/arvins/Sites/service/dist/src/main.js:59:30
[0]     at Generator.next (<anonymous>)

Replication/Example

Works perfectly fine for all node LTS versions prior to 12.16.0.

app.module.ts

import { Module } from '@nestjs/common'
import { ConfigModule, ConfigService } from 'nestjs-config'
import { HealthModule } from './health/health.module'
import * as path from 'path'

@Module({
    imports: [
        HealthModule,
        ConfigModule.load(path.resolve(__dirname, 'config', '**/!(*.d).{ts,js}')),
    ],
})
export class AppModule {}

main.ts

async function bootstrap() {
  const app = await NestFactory.create(AppModule)
  const config = app.get('ConfigService')
  await app.listen(config.get('express.port'))
}
bootstrap()
dmitrirussu commented 4 years ago

got same problem, seams ConfigModule.load is not reached

bashleigh commented 4 years ago

Have you tried awaiting the container before the get? Like so?

const app = await NestFactory.create(AppModule);
await app.init();
const config = app.get(ConfigService);
dmitrirussu commented 4 years ago

@bashleigh ConfigService load works fine for node version <=12.13.0... for the upper versions does not work... and reason is not in awaiting for.... in my case I'm waiting... no any config provided... Missing ConfigService Module provider...

bashleigh commented 4 years ago

@dmitrirussu I'm currently using 13.6.0. Can you share with me your setup?

arvinsingla commented 4 years ago

@bashleigh Unfortunately await app.init() did not help. The example I put in the description is a toy example. We've got three nest services in production and this issue first started rearing it's head in CI last week coinciding with the release of node 12.6.0 LTS. After a bunch of investigation the only way the issue was mitigated was by reverting back to node 12.5.0.

I put together a very simple repo with a clean install of nest using nest-cli and nestjs-config as the only dependency. The issue is present on all node versions I have tested > 12.6.0 including 13.x.

https://github.com/arvinsingla/nestjs-config-node-lts/

alexk4 commented 4 years ago

I'm experiencing the same issue with Node 12.6.1 and NestJS 6.11.x. Nest could not find ConfigService element (this provider does not exist in the current context) No issues with Node 12.14.0.

bashleigh commented 4 years ago

hmmm ok, thanks guys @arvinsingla @alexk4. I'll take a look into it. Strange it's this version only.

bashleigh commented 4 years ago

@arvinsingla ok so I cloned your repo, installed with npm, ran node with version 12.6.0, used both npm run start and npm run start:dev and this was my result

Screenshot 2020-02-20 at 08 58 50

What OS are you running?

arvinsingla commented 4 years ago

@bashleigh I'm running macOS Mojave, but we're also experiencing the issue in CI where the application is run in Linux docker containers.

I've added a dockerfile to my sample repo if you want to try seeing if you can reproduce.

  1. npm run build
  2. docker image build -t nestjs-config-node-lts .
  3. docker container run --publish 3000:3000 nestjs-config-node-lts

If you aren't able to reproduce my suspicion is there must be something happening at the build level that's different on your machine than ours.

bashleigh commented 4 years ago

The only difference I could find was with nest. Globally I have nest 6.6.3, in your project you have 6.14.2. However! Running node_modules/.bin/nest start --watch it works locally! I tried running node_modules/.bin/ts-node src/main.ts from the container but I couldn't find ./node_modules. I'll have another try at seeing what the issue is. I thought I'd just let you know my findings thus far.

mirono commented 4 years ago

I also have the same issue:

const app = await NestFactory.create<NestExpressApplication>(AppModule);
await app.init();
const configService = app.get(ConfigService);
console.log(configService);
const port = configService.get('app.config').port;
console.log('Binding server to port ' + port);

ConfigService { internalConfig: {} }
(node:61637) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'port' of undefined
    at bootstrap (/Users/mo39119/Dev/Familia/Server/node/nest-api/api/dist/main.js:13:49)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:61637) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:61637) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.```

Node v10.15.3 on MacOS
bashleigh commented 4 years ago

Sorry for taking ages guys. I've just resigned from the stressful job that I had so I now have all the time in the world! Will release the fix now!

bashleigh commented 4 years ago

1.4.6 has been released wih @romamd changes! Thanks for taking the time and solving the issue!

mirono commented 4 years ago

Unfortunately, the problem still persist with 1.4.6.

romamd commented 4 years ago

@mirono It works for me with node v12.16.1. What node version do you have?

mirono commented 4 years ago

On production I have 10.19.0. On dev 10.0.0. I'll check if I can upgrade.

mirono commented 4 years ago

Still doesn't work with v12.16.2.

romamd commented 4 years ago

@mirono

On production I have 10.19.0. On dev 10.0.0. I'll check if I can upgrade.

It's probably some other issue, because this one is reproducing only on node >= 12.16.0

mirono commented 4 years ago

Is there a working example that would work also in production (i.e. using the dist folder)?

dcyrillo commented 4 years ago

I had this problem. I did downgrade 12.16 to 12.13, it works

FrencisAlreadyInUse commented 3 years ago

This fixed it for me

const config = app.get<ConfigService>(ConfigService);
const secret = config['env'].EXAMPLE_SECRET;

Let me know if this helped 🤘

H256 commented 3 years ago

I had the same problem and solved it by first importing the ConfigModule in app.module.ts like mentioned in the documentation.

After that, I could use it in the main.ts without problems (example main.ts):

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NestExpressApplication } from '@nestjs/platform-express';

async function bootstrap() {
  const logger = new Logger('Bootstrapper');

  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  const config = app.get<ConfigService>(ConfigService);

  const port = config.get('API_PORT');
  await app.listen(Number(port));

  logger.log(`App listening on port ${port}`);
}
bootstrap();
rteano commented 3 years ago

I am currently having this issue when I upgrade the version of my NestJS packages to v8, I was trying to implement versioning so I have to upgrade to v8. But this error is happening when calling config service in main.ts with node v14.7.6

MGough commented 3 years ago

I am currently having this issue when I upgrade the version of my NestJS packages to v8, I was trying to implement versioning so I have to upgrade to v8. But this error is happening when calling config service in main.ts with node v14.7.6

I'm not actually sure if I'm in the right repo here, but I ended up here and may have a solution...

In main.ts async function bootstrap() I was doing this before NestJS v8:

  const configService = app.get<ConfigService>("ConfigService");

I had to change it to:

  const configService = app.get<ConfigService>(ConfigService);
mirono commented 3 years ago

@MGough this works also with Nest 6.

rteano commented 3 years ago

I am currently having this issue when I upgrade the version of my NestJS packages to v8, I was trying to implement versioning so I have to upgrade to v8. But this error is happening when calling config service in main.ts with node v14.7.6

I'm not actually sure if I'm in the right repo here, but I ended up here and may have a solution...

In main.ts async function bootstrap() I was doing this before NestJS v8:

  const configService = app.get<ConfigService>("ConfigService");

I had to change it to:

  const configService = app.get<ConfigService>(ConfigService);

Great catch! it worked, guess, they should improved with the typings for this one. :+1:

hnviradiya commented 2 years ago

Is there any solution to this. I am still having this issue.

jerembdn commented 2 years ago

I am currently having this issue when I upgrade the version of my NestJS packages to v8, I was trying to implement versioning so I have to upgrade to v8. But this error is happening when calling config service in main.ts with node v14.7.6

I'm not actually sure if I'm in the right repo here, but I ended up here and may have a solution...

In main.ts async function bootstrap() I was doing this before NestJS v8:

  const configService = app.get<ConfigService>("ConfigService");

I had to change it to:

  const configService = app.get<ConfigService>(ConfigService);

THANKSSS, worked for me too! (I had this error after upgrading @nestjs/core, @nestjs/common, ... to latest version (in case 8.2.6))

anirudhsaligram commented 2 years ago

you the man @MGough !

amir-khoshbakht commented 1 year ago

add this to your "app.module.ts" in the imports array:

ConfigModule.forRoot({ isGlobal: true }),