Using the .env file in NuxtJS helps manage variables across different environments (such as development and production), for example, API keys, server addresses, etc. This prevents sensitive information from being hardcoded directly in the code. The steps to use .env variables are as follows:
Step 1: Install Dependencies
First, ensure that you have installed the @nuxtjs/dotenv module in your NuxtJS project.
bashnpm install @nuxtjs/dotenv
Step 2: Configure nuxt.config.js
Next, configure this module in your nuxt.config.js file:
javascriptrequire('dotenv').config() export default { // Other configurations... modules: [ '@nuxtjs/dotenv', ], }
Step 3: Create and Use .env File
Create a .env file in the project root directory and define the environment variables you need:
shellAPI_SECRET=verysecretkey API_URL=https://api.example.com
In your application, you can now access these variables via process.env. For example, if you want to use these environment variables in your page:
javascript<script> export default { asyncData ({ params, $axios }) { const apiUrl = process.env.API_URL return $axios.$get(`${apiUrl}/data`) .then((data) => { return { data } }) } } </script>
Example
Suppose we are developing a NuxtJS application that needs to fetch data from different APIs. We can store the API URL and key in the .env file and then use this information in our pages or components to make API requests. This ensures that sensitive information is not hardcoded in the source code and makes it easy to switch these values across different environments.
Important Notes
- Do not add the
.envfile to version control systems (such as Git), as this may lead to sensitive information leaks. - In server or deployment environments, ensure that environment variables are correctly set so that your application can read these values.
By doing this, we can effectively manage environment variables in NuxtJS projects, improving security and maintainability.