Am using Nuxt-3 as my framework for the project and am very new to the framework too and when I was integrating api for my project and I was getting the response later when I tried to use api as global variable from the .env file in the root; but am unable to get the response as am getting error on the console hence forth kindly guide me on the right path in a simple way of explanation so I can sort the issue as well learn new concepts. I installed the dependencies with: npm install --save-dev @nuxtjs/dotenv
The code I tried was:
<template>
</template>
<script setup>
import axios from 'axios'
axios.defaults.baseURL = process.env.API_URL
axios.defaults.headers.common['Authorization'] = process.env.API_KEY
const response = await this.$axios.get('/pgs').then(response => response.data)
console.log(response)
</script>
Runtime config values can be automatically replaced by matching environment variables at runtime. By naming your .env variables starting with NUXT_ which uses _ to separate keys and case changes. No need to pass any proceess.env in this scenario. This example taken from the docs.
// .env file
NUXT_API_SECRET=####
NUXT_PUBLIC_API_BASE=###
export default defineNuxtConfig({
runtimeConfig: {
apiSecret: '', // can be overridden by NUXT_API_SECRET environment variable
public: {
apiBase: '', // can be overridden by NUXT_PUBLIC_API_BASE environment variable
}
},
})
<script setup lang="ts">
const config = useRuntimeConfig()
console.log('Runtime config:', config.public.apiBase)
if (process.server) {
console.log('API secret:', config.apiSecret)
}
</script>
You don't need any dependency when you use .env file for your project. In all my projects, this is process I do when I store important data.
[email protected]nuxt.config.ts file, add this runtimeConfig: { EMAIL: process.env.EMAIL, },useRuntimeConfig composables See more details https://nuxt.com/docs/api/composables/use-runtime-config#useruntimeconfig.See example on stackblitz https://stackblitz.com/edit/nuxt-starter-g534de?file=nuxt.config.ts
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