husayt
husayt

Reputation: 15139

Server side singleton injection in Nuxt

I need a shared object (e.g.cache/logger/service) instance (singleton) on serverside accessible to SS middleware/plugins/nuxtserverinit.

I have tried a local module which tries to inject $cache in serverside context during render:done hook (see below), but no matter what I tried it still was not available during SS request processing.

// modules/myCache.js
export default function(_moduleOptions,config) {

  this.nuxt.hook("render:before", context => {
     const cache=new myExoticCache()

// I tried all the below combinations
     context.nuxt.$cache1=cache
     context.serverContext.$cache2=cache
     context.options.$cache3=cache
     context.globals.$cache4=cache

  });

  this.nuxt.hook("render:done", context => {

// tried the above here too     

  });
}

// plugins/myplug.js
export default ({serverContext,nuxt}, inject) => {
//all of the below are undefined
//nuxt.$cache
//serverContext.$cache

}

Seems like I am missing something. Would be great to find out what. How can I pass value from route:done hook to any server-side middleware/plugin/nuxtserverinit.

Upvotes: 4

Views: 3419

Answers (1)

TenshiGoan
TenshiGoan

Reputation: 506

You can extend ssrContext from 'vue-renderer:ssr:prepareContext' hook.

// modules/myCache.js
export default function(_moduleOptions) {
    const $cache = 'CACHE';
    this.nuxt.hook('vue-renderer:ssr:prepareContext', ssrContext => {
        ssrContext.$cache = $cache;
    })
}

// plugins/myplug.js
export default function ({ ssrContext }) {
    if (process.server) {
        console.log(ssrContext.$cache)
    }
}

Upvotes: 7

Related Questions