Valkey module for NestJS
npm install @toxicoder/nestjs-valkeyA NestJS module for integrating with Valkey, a Redis-compatible database.
- Installation
- Description
- Environment Variables
- Configuration
- forRoot
- forRootAsync
- Usage
- Basic Usage
- Acquiring and Releasing Locks
- Cleanup
- API Reference
- License
``bash`
npm install @toxicoder/nestjs-valkey
The NestJS Valkey module provides a simple way to integrate Valkey (a Redis-compatible database) with your NestJS application. This module uses the iovalkey package to connect to Valkey servers and provides a service with methods for common operations.
- Support for both single-node and cluster configurations
- Easy integration with NestJS dependency injection
- Configuration through environment variables or programmatically
- Methods for common Redis operations (get, set, del, etc.)
- Distributed lock mechanism
| Variable | Type | Default | Description |
| --------------- | ------------ | ----------- | -------------------------------------------------------------------------------------- |
| VALKEY_MODE | string | 'single' | Connection mode: 'single' or 'cluster' |
| VALKEY_HOST | string/array | '127.0.0.1' | For single mode: host address. For cluster mode: comma-separated list of startup nodes |
| VALKEY_PORT | number | 6379 | Port number (single mode only) |
| VALKEY_DB | number | undefined | Database number (single mode only) |
| VALKEY_PASSWORD | string | undefined | Password for authentication |
| VALKEY_PREFIX | string | '' | Prefix for all keys |
If you prefer configuring via environment variables only, simply import the module without options. The module will read configuration from process.env using the variables listed in the Environment Variables section.
`typescript
import { Module } from '@nestjs/common';
import { ValkeyModule } from '@toxicoder/nestjs-valkey';
@Module({
imports: [ValkeyModule],
})
export class AppModule {}
`
Use forRoot to configure the module with direct options:
`typescript
import { Module } from '@nestjs/common';
import { ValkeyModule } from '@toxicoder/nestjs-valkey';
@Module({
imports: [
ValkeyModule.forRoot({
host: 'localhost',
port: 6379,
password: 'password',
keyPrefix: 'app:',
}),
],
})
export class AppModule {}
`
For cluster configuration:
`typescript
import { Module } from '@nestjs/common';
import { ValkeyModule } from '@toxicoder/nestjs-valkey';
@Module({
imports: [
ValkeyModule.forRoot({
startupNodes: ['redis://localhost:6379', 'redis://localhost:6380'],
clusterOptions: {
keyPrefix: 'app:',
redisOptions: {
password: 'password',
},
},
}),
],
})
export class AppModule {}
`
Use forRootAsync for dynamic configuration:
`typescript
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { ValkeyModule } from '@toxicoder/nestjs-valkey';
@Module({
imports: [
ConfigModule.forRoot(),
ValkeyModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
host: configService.get('VALKEY_HOST'),
port: configService.get('VALKEY_PORT'),
password: configService.get('VALKEY_PASSWORD'),
keyPrefix: configService.get('VALKEY_PREFIX'),
}),
}),
],
})
export class AppModule {}
`
Inject the ValkeyService into your service or controller:
`typescript
import { Injectable } from '@nestjs/common';
import { ValkeyService } from '@toxicoder/nestjs-valkey';
@Injectable()
export class AppService {
constructor(private readonly valkeyService: ValkeyService) {}
async setValue(key: string, value: string): Promise
// Plain set
return this.valkeyService.set(key, value);
}
async setWithTtlSeconds(key: string, value: string): Promise
// SET with EX (seconds)
return this.valkeyService.setEx(key, value, 30);
}
async setWithTtlMs(key: string, value: string): Promise
// SET with PX (milliseconds)
return this.valkeyService.setPx(key, value, 1500);
}
async setIfNotExists(key: string, value: string): Promise
// NX without TTL (returns true if key was set)
return this.valkeyService.setNx(key, value);
}
async setIfNotExistsWithTtl(key: string, value: string): Promise
// NX with EX (seconds)
return this.valkeyService.setNx(key, value, 60);
}
async getValue(key: string): Promise
return this.valkeyService.get(key);
}
}
`
The module provides methods for distributed locks:
`typescript
import { Injectable } from '@nestjs/common';
import { ValkeyService } from '@toxicoder/nestjs-valkey';
@Injectable()
export class LockService {
constructor(private readonly valkeyService: ValkeyService) {}
async performWithLock(
key: string,
operation: () => Promise
): Promise
const lockAcquired = await this.valkeyService.acquireLock(key, 30); // Lock for 30 seconds
if (!lockAcquired) {
throw new Error('Could not acquire lock');
}
try {
await operation();
} finally {
await this.valkeyService.releaseLock(key);
}
}
}
`
Implement the OnModuleDestroy interface to properly disconnect from Valkey when your application shuts down:
`typescript
import { Injectable, OnModuleDestroy } from '@nestjs/common';
import { ValkeyService } from '@toxicoder/nestjs-valkey';
@Injectable()
export class AppService implements OnModuleDestroy {
constructor(private readonly valkeyService: ValkeyService) {}
onModuleDestroy() {
this.valkeyService.disconnect();
}
}
`
- getClient(): Returns the underlying Valkey clientset(key, value)
- : Sets a key-value pairsetEx(key, value, ttlSec)
- : Sets a key with EX (seconds) TTLsetPx(key, value, ttlMs)
- : Sets a key with PX (milliseconds) TTLsetNx(key, value, ttlSec?)
- : Sets a key only if it does not exist; optionally with EX TTL. Returns boolean indicating if the key was setsetPnx(key, value, ttlMs?)
- : Sets a key only if it does not exist; optionally with PX TTL. Returns boolean indicating if the key was setget(key)
- : Gets the value for a keydel(key | string[])
- : Deletes a key or multiple keysexists(key | string[])
- : Checks if one or more keys exist. Returns the number of existing keysexpire(key, seconds)
- : Sets a key's time to live in secondsping()
- : Pings the Valkey serverdisconnect()
- : Disconnects from the Valkey serveracquireLock(key, ttlSec)
- : Acquires a distributed lockreleaseLock(...keys)`: Releases one or more locks
-
ISC