[SOLVED] In NestJS how can I associate a token with module registered using registerAsync?


I’m using NestJS CacheModule and register it using registerAsync in order to use useFactory and inject config module.

I want to provide a special token, because I intend to have multiple cache managers. Using provide is not supported with registerAsync. How can I achieve this?

Code example:

import { CacheModule } from '@nestjs/common';
import { ENVALID } from 'nestjs-envalid';
import * as redisStore from 'cache-manager-redis-store';

export const CacheManager1 = CacheModule.registerAsync({
  provide: "CACHE_MANAGER_1", //this is not possible
  useFactory: async (env: EnvironmentConfig) => {
    return {
      ttl: env.MANAGER_ONE_TTL_SEC,
      store: redisStore,
      host: env.MANAGER_ONE_REDIS_HOST,
      port: env.MANAGER_ONE_REDIS_PORT,
      password: env.MANAGER_ONE_REDIS_PASSWORD,
      db: env.MANAGER_ONE_REDIS_DB,
  inject: [ENVALID],


In a very similar vein as this question you can create a dedicated module for this CacheModule’s options and export the CACHE_MANAGER under a new token. This would look something like

  imports: [CacheModule.registerAsync(asynCacheManagerOptions)],
  providers: [
      provide: 'CustomCacheToken',
      useExisting: CACHE_MANAGER,
  exports: ['CustomCacheToken'],
export class CustomCacheModule {}

And now this cache manager can be injected with @Inject('CustomCacheToken')

Answered By – Jay McDoniel

Answer Checked By – Mary Flores (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *