Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use .env file in Nuxt 3

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>
like image 214
user20663233 Avatar asked Oct 29 '25 02:10

user20663233


2 Answers

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>
like image 72
Manos Avatar answered Oct 31 '25 22:10

Manos


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.

  1. Create a .env file
  2. Add data e.g [email protected]
  3. In your nuxt.config.ts file, add this runtimeConfig: { EMAIL: process.env.EMAIL, },
  4. To access it in the backend, your need to use the 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


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!