How to use .env in Nuxt3
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
⇨ Click here for the Vue article index
I'm playing around with Nuxt3.
I summarized how to use .env in Nuxt3.
It seems that the method has been updated since Nuxt2.13, and it didn't work well with the previous method.
Environment
node --version v16.13.0
Nuxt3
Example of Failure
Create a .env in the root directory
(※ (For beginners) The root directory refers to the project directory.)
your-project-name/.env
Create a file named .env like this.
As long as the location and file name match, it's okay.
Let's see what's inside the file.
BASE_URL=https://127.0.0.1:8000
Experiment to see if it can be loaded
<template>
<div>{{ baseUrl }}</div>
</template>
<script>
export default {
data() {
return {
baseUrl: "http://127.0.0.1:8000",
}
},
created() {
console.log(process.env.BASE_URL)
},
}
</script>
Console
Uncaught (in promise) TypeError: Cannot read property 'BASE_URL' of undefined
It seems like it didn't work.
Implementation Method (Conclusion)
It seems that it should be defined in nuxt.config.ts and output as config.
Edit nuxt.config.ts
export default defineNuxtConfig({
publicRuntimeConfig: {
baseUrl: process.env.BASE_URL,
},
})
Let's display it
<template>
<div>{{ $config.baseUrl }}</div>
</template>
<script>
export default {
data() {
return {
baseUrl: "http://127.0.0.1:8000",
}
},
created() {
console.log(this.$config.baseUrl)
},
}
</script>
It displayed well. Yay!
When you want to use it in set up
<script setup lang="ts">
const config = useRuntimeConfig()
console.log(`${config.baseUrl}/api/count`)
const { data } = await useAsyncData("count", () =>
$fetch(`${config.baseUrl}/api/count`)
)
//$fetch I couldn't find a way to specify baseUrl like axios baseUrl in Nuxt2, so is this the best way to do it? What do you think?
</script>
Summary
I tried using env in Nuxt3.
I searched quite a bit for how to change the baseUrl of $fetch like axios baseUrl, but I couldn't find it. Disappointing.
If you have any information, please let me know!
Complaints, corrections, please contact me via DM on Twitter below.
That's it!
How to extract only data that meets the conditions from an array using filter in Vue (Javascript)