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.