Home  >  Q&A  >  body text

Trying to connect to redis client from nuxt 3 middleware but connection is undefined

<p>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</p> <pre class="brush:php;toolbar:false;">if (process.server) { let session = await RedisUtil.getConnection.get(sessionID); }</pre> <p>The following is redisUtil</p> <pre class="brush:php;toolbar:false;">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"); } }</pre> <p>The redis plugin has been loaded into the nitro configuration</p> <pre class="brush:php;toolbar:false;">import RedisUtil from '../utils/RedisUtil'; import config from "~/server.config" export default async (NuxtApp) => { await RedisUtil.connect(config); };</pre> <pre class="brush:php;toolbar:false;">nitro: { plugins: [ "~/server/plugins/redis.js" ], },</pre> <p>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>
P粉512526720P粉512526720386 days ago535

reply all(1)I'll reply

  • P粉098979048

    P粉0989790482023-08-31 12:43:49

    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 = ''
    })
    

    reply
    0
  • Cancelreply