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.
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;
}
Injected header should be available as $headers in templates or lifecycle methods of components as this.$headers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With