Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use env variables in nuxt 3 outside of setup scripts

So the problem is that I would like to use Axios instance. Because:

  1. new useFetch is only possible to use inside of components aka setup scrips. https://v3.nuxtjs.org/guide/features/data-fetching/
  2. community axios module is only possible inside of nuxt2 https://github.com/nuxt-community/axios-module/issues/536 and are nor supported in nuxt3
  3. I need to make calls in pinia actions(store) to my backend service.

nuxt.config.js

import { defineNuxtConfig } from "nuxt";

export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      apiBase: process.env.API_BASE_URL ?? "http://localhost:8080/api/v1",
    },
  },
  env: {
    apiBase: process.env.API_BASE_URL ?? "http://localhost:8080/api/v1",
  },
  buildModules: ["@pinia/nuxt"],
});

and here is instance.js

import axios, { AxiosResponse } from "axios";

const instance = axios.create({
  baseURL: process.env.API_BASE_URL,
});

instance.interceptors.response.use((response: AxiosResponse) => {
  return response.data;
});

export default instance;

So it does see the envs on server-side as I can console log them but on client I do receive can't read of undefined

like image 542
Victor Orlyk Avatar asked Sep 05 '25 03:09

Victor Orlyk


1 Answers

You can access your env variables using a composable and the useRuntimeConfig method.

Something like this for instance:

// file composables/use-axios-instance.ts

import axios, { AxiosResponse } from "axios";

let instance = null;

export const useAxiosInstance = () => {
  const { API_BASE_URL } = useRuntimeConfig();

  if (!instance) {
    instance = axios.create({
      baseURL: API_BASE_URL,
    });

    instance.interceptors.response.use((response: AxiosResponse) => {
      return response.data;
    });
  }

  return instance;
};

Then you can access to your axios instance using const axios = useAxiosInstance();

like image 88
Tristan Avatar answered Sep 07 '25 21:09

Tristan



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!