Trying to connect to redis client from nuxt 3 middleware but connection is undefined
P粉512526720
P粉512526720 2023-08-30 13:36:47
0
1
483

I'm trying to connect to a Redis server to get session data from the nuxt 3 DefineNuxtRouteMiddleware middleware without success. I created a connection to redis in the server side plugin and it works for all my api endpoints, but it doesn't seem to work for my rout-guards middleware. I try to get the connection in the code below but the connection is not defined. Am I wrong in assuming that the middleware server side execution should have access to the Redis connection

if (process.server) { let session = await RedisUtil.getConnection.get(sessionID); }

The following is redisUtil

class RedisUtil{ static get getConnection(){ return this.connection; } static set setConnection(connection){ this.connection = connection; } static async connect(config) { let redis = createClient({ url: 'redis://' config.redis.user ':' config.redis.password '@' config.redis.host ':' config.redis.port }); redis.on('error', err => console.log('Redis Client Error', err)); await redis.connect(); RedisUtil.setConnection = redis; console.log("Connected to redis"); } }

The redis plugin has been loaded into the nitro configuration

import RedisUtil from '../utils/RedisUtil'; import config from "~/server.config" export default async (NuxtApp) => { await RedisUtil.connect(config); };
nitro: { plugins: [ "~/server/plugins/redis.js" ], },

As mentioned above, I can access the redis connection in all other server-side executions, but not in the middleware. Any help on this would be greatly appreciated.

P粉512526720
P粉512526720

reply all (1)
P粉098979048

It seems that you are only running the Redis request on the server side part. Causes client-side routing to lose context when it occurs.

export default defineNuxtRouteMiddleware(async (to, from) => { let session = ''; if (process.server) { session = 'has some context'; } // server: session = 'has some context' // client: session = '' })
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!