Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nuxt: pass data from server plugin to client

Tags:

nuxt.js

I have a nuxt behind an auth proxy. A request will get to nuxt (only if) it is authorized, in which case the X-auth-username (and other) headers will be set.

I have found that, using a server plugin, I can read this info on the request. However, the data is not send from the server to the client. How do I get the server to send information headers (in particular the user name) to the client?

My plugin so far:


import { Plugin } from '@nuxt/types'
import { IncomingHttpHeaders } from 'http'

declare module '@nuxt/types' {
  interface NuxtAppOptions {
    $headers: IncomingHttpHeaders
  }
}

const getAuth: Plugin = (context, inject) => {
  const headers = context.req.headers
  inject('headers', headers)
}

export default getAuth

NOTE I am using the nuxt-composition-api, and not vuex.

like image 243
shaunc Avatar asked Jul 09 '26 20:07

shaunc


2 Answers

You can use beforeNuxtRender nuxt hook to set properties on server which will be serialized in html and retrievable on client:

// in nuxt plugin
if (process.server) {
    // set property on server
    context.beforeNuxtRender(({ nuxtState }) => {
      nuxtState.headerValue = 'test';
    });
} else {
    // retrieve it on client
    let valueOnClient = context.nuxtState?.headerValue;
}
like image 129
Pavel Gurecki Avatar answered Jul 13 '26 21:07

Pavel Gurecki


Injected header should be available as $headers in templates or lifecycle methods of components as this.$headers.

like image 20
Oluwafemi Sule Avatar answered Jul 13 '26 21:07

Oluwafemi Sule



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!