Redis Server
Overview
The redis.server.ts plugin initializes and manages a Redis connection in a Nuxt 3 application. It uses the ioredis library for connecting to a Redis server, enabling efficient data storage and retrieval, pub/sub capabilities, and more. This plugin ensures that Redis is available globally across your app and handles clean connection management.
This plugin provides a centralized Redis connection, which can be accessed by all components, composables, and stores in your Nuxt 3 application.
Features
- Global Redis Connection: The Redis instance is made globally available throughout the Nuxt app.
- Graceful Connection Management: The Redis connection is established when needed and disconnected when the application is about to close.
- Debug Mode Integration: If the application is running in debug mode, Redis-related details are logged for easier debugging.
- Customizable Configuration: Redis connection details such as host, port, username, and password can be configured via the runtime configuration in the
nuxt.config.ts.
Installation
Dependencies
The plugin requires the ioredis package, which should be installed in your project.
npm install ioredis
Configuration
Ensure that the following configuration is included in your nuxt.config.ts file to define the Redis connection details:
export default defineNuxtConfig({
runtimeConfig: {
redisHost: process.env.REDIS_HOST, // Redis server host (e.g., localhost or a remote address)
redisPort: process.env.REDIS_PORT || 6379, // Redis server port (default is 6379)
redisUsername: process.env.REDIS_USERNAME, // Redis username (optional)
redisPassword: process.env.REDIS_PASSWORD, // Redis password (optional)
public: {
appDebug: process.env.APP_DEBUG || false, // Set to true to enable debug logging for Redis
},
},
});
File: redis.server.ts
import Redis from "ioredis";
let redis: Redis;
export default defineNuxtPlugin((nuxtApp) => {
const config = useRuntimeConfig();
// Initialize Redis connection if it's not already initialized
if (!redis && config.redisHost) {
redis = new Redis({
port: config.redisPort ?? 6379,
host: config.redisHost,
username: config.redisUsername,
password: config.redisPassword,
});
// Enable Redis debug logging if appDebug is true
if (useRuntimeConfig().public.appDebug) {
const debugStore = useDebugStore();
debugStore.services.redis.enabled = true;
debugStore.services.redis.host = config.redisHost;
}
}
// Clean up Redis connection before the app closes
nuxtApp.hook("app:beforeClose", () => {
redis.disconnect();
});
// Provide Redis globally to the app
return {
provide: {
redis,
},
};
});
Explanation
- Redis Connection Initialization:
- The Redis connection is created if it's not already initialized (
if (!redis && config.redisHost)). - The connection details are fetched from the runtime configuration (
useRuntimeConfig()).
- The Redis connection is created if it's not already initialized (
- Debug Mode Integration:
- If
appDebugis set totruein the configuration, debug information about the Redis connection is logged into thedebugStore.
- If
- Graceful Disconnection:
- The Redis connection is closed gracefully when the app is about to close by hooking into the
app:beforeCloseevent (nuxtApp.hook('app:beforeClose', ...)).
- The Redis connection is closed gracefully when the app is about to close by hooking into the
- Global Access:
- The Redis instance is made available globally to the application using the
providemethod, which allows you to access it anywhere in the app viauseNuxtApp().$redis.
- The Redis instance is made available globally to the application using the
Usage
Once the plugin is installed and configured, you can access the Redis connection anywhere in your application. For example, to interact with Redis in your composables, stores, or components, you can use:
const redis = useNuxtApp().$redis;
You can use this redis instance to perform various Redis operations like setting/getting keys, subscribing to channels, etc.
Example Usage in a Composable:
const setDataToRedis = async (key: string, value: string) => {
try {
await redis.set(key, value);
console.log("Data successfully set in Redis");
} catch (error) {
console.error("Error setting data to Redis", error);
}
};
Example Usage in a Store:
import { defineStore } from "pinia";
export const useCacheStore = defineStore("cache", {
state: () => ({
cachedData: null,
}),
actions: {
async fetchDataFromCache(key: string) {
const data = await redis.get(key);
this.cachedData = data;
},
},
});
Clean Up and Disconnection
The Redis connection is automatically closed when the app is about to close. This ensures there are no hanging Redis connections after the application stops.
nuxtApp.hook("app:beforeClose", () => {
redis.disconnect();
});
This prevents resource leakage and ensures a clean shutdown of the Redis connection.
Debugging
If you have enabled debug mode (appDebug: true in your configuration), Redis connection details are logged to the debugStore. You can access this information for troubleshooting or debugging purposes.
const debugStore = useDebugStore();
console.log(debugStore.services.redis); // Logs the Redis service status
Conclusion
The redis.server.ts plugin is a powerful tool that integrates Redis into your Nuxt 3 application, providing easy and scalable access to Redis functionality. It handles connection management, provides global access, and ensures that Redis is properly disconnected when the app shuts down.
By integrating Redis with your Nuxt app using this plugin, you can leverage caching, session management, real-time updates, and more.
Further Reading
This plugin offers a clean, scalable solution for using Redis in your Nuxt 3 application and provides flexibility to customize according to your needs.