NestJs .env Reading Issue with ConfigService

58 views Asked by At

I've been working with NestJs recently and encountered an issue while attempting to read environment data from the .env file. The problem arises when I use the ConfigService within the NestJs service and module – it functions correctly. However, if I manually create an instance of ConfigService, it fails to work (got undefined).

Here's the relevant code snippet:

import KcAdminClient from '@keycloak/keycloak-admin-client';

import { Issuer } from 'openid-client';
import { ConfigService } from '@nestjs/config';

const config = new ConfigService();

export const kcAdminClient = new KcAdminClient({
  realmName: config.get('KC_REALM'),
  baseUrl: config.get('KC_BASE_URL'),
});

I've verified that the properties KC_REALM and KC_BASE_URL are present in the .env file.

Could someone provide assistance in resolving this issue?

1

There are 1 answers

0
Dmitrii Tkachenko On

You need to use ConfigService in a Nest module. It's being injected by the DI. If you want this setup to work, consider creating a Keycloak service that will have a config service injected into it. There is a nest keycloak module on npm, although I haven't used it.

Alternatively, you can access env variables directly via process.env.