The Be Sure Blog

Code Snippets | Problem Solving | Tips & Tricks

The Be Sure Blog banner

Use environmental variables in Nuxt 3

posted on 3.2.2023 by Below Surface in "Nuxt"

Learn how to use environmental variables from someone who codes with Nuxt since four hours ago.


First of all, create an .env file in the projects root directory and add your variables there, like:

EMAIL_SERVICE=123
EMAIL_TEMPLATE=123
EMAIL_USER=123

Then, open the nuxt.config.ts file and add:

runtimeConfig: {
    public: {
        emailService: process.env.EMAIL_SERVICE,
        emailTemplate: process.env.EMAIL_TEMPLATE,
        emailUser: process.env.EMAIL_USER
    }
}

Please note that if these are not used within the client, "public" is not needed here. In our case, we need the variables in the browser to send emails.

Finally, within the component where we need the variables, add this to the export default {} object:

setup() { 
  const runtimeConfig = useRuntimeConfig();
  return {
    runtimeConfig
  }
},

In our case we use the variables to send emails with Emailjs. We can access the environmental variables like this:

methods: {
  sendEmail(e: HTMLFormElement) {
    try {
        emailjs.sendForm(this.runtimeConfig.emailService, this.runtimeConfig.emailTemplate, e.target, this.runtimeConfig.emailUser)
    } catch(error) {
      console.log({ error })
    }
  }
}

Do not forget to restart the local server after applying these changes.

Tags:

nuxt 3
vue.js
.env

Sources:

https://www.youtube.com/watch?v=dc93ZrDFUcghttps://dev.to/amitgurbani/environment-variables-in-nuxt-3-9p6https://vuejs.org/api/composition-api-setup.html#basic-usage

More posts of this category

My Nuxt 3 fix for npm ERR! Invalid comparator: latest

After starting to code with Nuxt, I ran into this issue and found the fix

Nuxt

Pm2: Make your Nuxt 3 live app run on a port other than 3000

A five hour research solution for switching the live port to 3002

Nuxt

How to add HTML head data to a Nuxt 3 app

Learn how to set the important SEO data

Nuxt