4

I am struggling with my nuxt project. I try to access to config variables written in nuxt.config.js I set my env variables in privateRuntimeConfig instead of dotenv. What I eventually want to do is that I want to access to them in my typescript file using url defined in nuxt.config.js file which calls api from backend.

Below is my api.ts

import axios, { AxiosResponse } from 'axios';
import { Context } from '@nuxt/types';
import { IRequestInquiry, IResponseInquiry } from '~/models/inquiry';

export const sendInquiry = async (createInquiry: IRequestInquiry, context : Context): Promise<IResponseInquiry> => {

  //context not found
  console.log(context);

  const apiUrl = context.$config.apiURL;

  const axiosResponse: AxiosResponse = await axios.post(
    apiUrl, // TODO
    createInquiry,
  );
  return { status: axiosResponse.status, results: axiosResponse.data };
};

Below is my nuxt.config.js

privateRuntimeConfig: {
    apiURL: process.env.API_URL,
    proxyBaseURL: process.env.BASE_URL,
  },
Nam
  • 41
  • 3
  • You can access the env variable by destructuring the Nuxt context: https://nuxtjs.org/docs/concepts/context-helpers Meanwhile, why are you setting axios with a private variable since it will be public anyway (when doing your POST). Also, why are you overriding your endpoint in your call after setting it in the config file? This may also help: https://stackoverflow.com/a/67705541/8816585 – kissu Oct 14 '21 at 04:04
  • @kissu I am sorry, I just wanted to know how to use private config for later use of GET method. thank you so much. I will fix the question. – Nam Oct 14 '21 at 05:43
  • @kissu I can not still access using context. could you check if it is right? import { Context } from '@nuxt/types'; const apiUrl = context.$config.apiURL; – Nam Oct 14 '21 at 06:03
  • Please do not write inline code in comments. Rather, edit your question. I don't write any TS so I'm not sure about the exact syntax. – kissu Oct 14 '21 at 06:48
  • @kissu i edited. it works, but it might not a good idea to call context config in here, right? – Nam Oct 14 '21 at 07:30
  • You can call the context whenever you need it, it's totally fine. Meanwhile yeah, you should probably do the setting of your axios in one place. Like an external plugin to set the endpoint globally. Also, stop using a global variable since it'll be used by Axios. – kissu Oct 14 '21 at 07:41
  • This is a good starting point: https://stackoverflow.com/a/67705541/8816585 – kissu Oct 14 '21 at 08:59

0 Answers0