Alexander Kim
Alexander Kim

Reputation: 18410

How to use plugin's data in a nuxt.config.js file?

My plugin, env.js:

export default async (_ctx, inject) => {
  const resp = await fetch('/config.json')
  const result = await resp.json()
  inject('env', result)

  // eslint-disable-next-line no-console
  console.log('env injected', result)

  return result
}

Then an idea was to use it's data inside nuxt.config.js to inject into publicRuntimeConfig:

import env from './plugins/env.js'

publicRuntimeConfig: {
  test: env,
},

Then in a browser console i'm checking it:

this.$nuxt.$config

It shows me:

enter image description here

instead of a value, though this.$nuxt.$env shows the correct values:

enter image description here

What's wrong?

UPDATE 1

Tried Tony's suggestion:

// nuxt.config.js
import axios from 'axios'

export default async () => {
  const resp = await axios.get('/config.json')
  const config = resp.data

  return {
    publicRuntimeConfig: {
      config
    }
  }
}

It cannot fetch config.json, but if i point it to an external resource: "https://api.openbrewerydb.org/breweries" it does work.

Intention of this question, is to have config.json where a user could simply change variable values there (from a compiled code) and change endpoints without a re-build process.

Upvotes: 0

Views: 1933

Answers (1)

tony19
tony19

Reputation: 138696

In nuxt.config.js, your env variable is a JavaScript module, where the default export is the function intended to be automatically run by Nuxt in a plugin's context. Importing the plugin script does not automatically execute that function. Even if you manually ran that function, it wouldn't make sense to use an injected prop as a runtime config because the data is already available as an injected prop.

If you just want to expose config.json as a runtime config instead of an injected prop, move the code from the plugin into an async configuration:

// nuxt.config.js
export default async () => {
  const resp = await fetch('/config.json')
  const config = await resp.json()

  return {
    publicRuntimeConfig: {
      keycloak: config
    }
  }
}

Upvotes: 1

Related Questions