Skip to content

Is it possible to define an variable as base url on nuxt.js

what I trying to do is define a base url variable for my API which is able to be called everywhere on nuxt app. for example I’m trying to call an image from my API storage like bellow

<img :src="`${baseUrl}/****/****.png`">

Assuming I can define the variable, so I don’t need to change every img url when the API domain changed. or I would be very thankful for introduce any better way to calling image from API storage. btw I’m using Laravel as the API.


You can use one of the runtimeConfig for this, publicRuntimeConfig or privateRuntimeConfig depending on your requirement


export default {
  publicRuntimeConfig: {
    baseURL: ''
  privateRuntimeConfig: {
    apiSecret: 'something_private'

Once added this variable will be available under $config across your Nuxt app like below

In templates

  <p>Our Url is: {{ $config.baseURL}}</p>

In places where you use the context (plugins, asyncData etc)

  asyncData ({ $config: { baseURL } }) {
    const posts = await fetch(`${baseURL}/posts`)
      .then(res => res.json())