How can the 'env' property in Nuxt.js be utilized to access the new API?

I have been working on creating news web apps that utilize newsapi.org. To protect my API key, I decided to use the env property in Nuxt.Js. However, I am now encountering a 401 status code from the server.

Firstly, I created the .env file in my project directory and added my API_KEY. Then, I installed 'dotenv' using the 'yarn add dotenv' command in VSCode terminal.

In addition, I updated the nuxt.config.ts file. Since I am using TypeScript in my project, all files are dependent on TypeScript.

require('dotenv').config()
const { API_KEY } = process.env
export default {
 ~~~~~~~~~~
 env: {
    API_KEY,
  },
}

I used Vuex to fetch news information, here is the code snippet.

~/store/getNews.ts

import { MutationTree, ActionTree, GetterTree } from "vuex";
import axios from "axios";
const url = 'http://newsapi.org/v2/top-headlines';

interface RootState { }

export interface NewsArticles {
    source?: {}
    author?: string
    title?: string
    description?: string
    url?: any
    urlToImage?: any
    publishedAt?: string
    content?: string
}

interface State {
    newArticle: NewsArticles
}
export const state = () => ({
    newsArticle: []
})
export const getters: GetterTree<State, RootState> = {
    newsArticle: (state: State) => state.newArticle
}
export const mutations: MutationTree<State> = {
    setNewsArticle: (state: State, newsArticle: NewsArticles) => {
        state.newArticle = newsArticle
    }
}
export const actions: ActionTree<State, RootState> = {
    getNewsArticle: async ({ commit },{params}) => {
        try{
            const data = await axios.get(url,{params})
            commit('setNewsArticle', data.data.articles)
        }catch(error){
            commit('setNewsArticle',[])
        }
    }
}

export default { state, getters, mutations, actions }

Lastly, I created a vue file to display the news information.

<template>
  <div>
    <p>This is NewsApi test page!!</p>
    <ul v-for="(item, index) in items" :key="index">
      <li>{{ item.title }}</li>
    </ul>
  </div>
</template>
<script lang="ts">
import { Component, namespace, Vue } from 'nuxt-property-decorator'
import { NewsArticles } from '~/store/getNews'
const getNews = namespace('getNews')

@Component({})
export default class extends Vue {
  @getNews.Action getNewsArticle!: Function
  @getNews.Getter newsArticle!: NewsArticles
  items: any = []
  async mounted() {
    await this.getNewsArticle({
      params: { country: 'jp', category: 'business', apiKey: process.env.API_KEY },
    })
    this.items = this.newsArticle
  }
}
</script>

Upon running my app, I encountered a 401 status code and checked the console error message.

{status: "error", code: "apiKeyInvalid",…}
code: "apiKeyInvalid"
message: "Your API key is invalid or incorrect. Check your key, or go to https://newsapi.org to create a free API key."
status: "error"

I am unsure why this error has occurred even though I confirmed the proper setting of the API key through console.log.

In index.vue

<script lang='ts'>
~~~~
export default class extend Vue{
  mounted(){
   console.log(process.env.API_KEY)
}
}
</script>

Answer №1

No need to manually call `require('dotenv').config()`, Nuxt handles it automatically.

Additionally, in order for environment variables to be accessible in the production build, their names should start with `NUXT_ENV_` as detailed here (e.g., `NUXT_ENV_API_KEY`). Remember that while this approach prevents the key from being exposed in your source code (assuming you keep your `.env` file out of source control), it can still be viewed in the Network tab in DevTools.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I adjust the timeout or enhance my code for Excel Online's ExcelScript error regarding the Range getColumn function timing out?

I am struggling with a code that is supposed to scan through the "hello" sheet and remove any columns where the top cell contains the letter B: function main(workbook: ExcelScript.Workbook) { let ws = workbook.getWorksheet("hello"); let usedrange = ws ...

What is the best way to extract key/value pairs from an object in javascript that have a specific suffix?

I'm dealing with an object: { a_suff:"Something", b_suff: "Value", c: "Value", d: "Value, e_suff: "Value" } I'm looking for a way to extract all the keys that end in "_suff". What would be the most efficient solution? Currently, I have this im ...

Utilize DTOptionsBuilder and AngularJs ColVis to trigger actions when there are changes in column visibility

In my AngularJs project, I am using DTOptionsBuilder with ColVis plugin to show and hide columns in a datatable. I need to perform certain operations when the visibility of the columns changes. I came across an event called 'column-visibility.dt' ...

Creating dynamic classes in VueJS

After carefully reviewing the documentation, I am puzzled about how to modify a class. My component's data is structured as follows: props: [ 'm_c_id', 'recipient_id', 'sender_id', 'userId' ], If sende ...

How to Align Bootstrap 4 Navbar Brand Logo Separate from Navbar Toggler Button

Can anyone help me with center aligning navbar-brand? When I right align navbar-toggler for mobile devices, it causes the logo to be off-center. Is there a way to independently align these two classes, and if so, how can I achieve this? <nav class="n ...

Arrange arrays with multiple dimensions in JavaScript based on their ranges

Seeking assistance on sorting a multi-dimensional array returned from an API to enable users to choose a range based on beats. I'm currently facing challenges with the data my API is returning. var myObj = [{ title: 'title one', be ...

Maintain vertical spacing within Vue templates using Prettier

I'm currently utilizing the eslint-plugin-vue in my Vue project. In my project, I have a specific configuration defined in the .prettierrc file: // /.prettierrc { "arrowParens": "avoid", "bracketSpacing": true, "insertPragma": false, "jsxBra ...

Transitioning to Material-ui Version 4

During the process of upgrading material-ui in my React Application from version 3.9.3 to version 4.3.2, I encountered an error message stating TypeError: styles_1.createGenerateClassName is not a function. I am feeling lost when it comes to transitioning ...

Deciphering the Components of Web Applications: Express.js, Angular.js, and the MVC Puzzle

After exploring numerous discussions on Stack Overflow regarding the integration of Express.js with Angular.js and the presence of dual MVC components in both the client and server sides of web applications, I have found myself feeling somewhat perplexed. ...

Angular 2: trigger a function upon the element becoming visible on the screen

How can I efficiently trigger a function in Angular 2 when an element becomes visible on the screen while maintaining good performance? Here's the scenario: I have a loop, and I want to execute a controller function when a specific element comes into ...

Creating a Loading State for CRUD Operations in Vue.js

In the process of creating my initial Vue.js application with Vuex, I am encountering obstacles when it comes to loading state correctly. Currently, I have a route dedicated to displaying all accounts (/accounts) and successfully loading the account data ...

What could be causing BeautifulSoup to overlook certain elements on the page?

For practice, I am in the process of developing an Instagram web scraper. To handle dynamic webpages, I have opted to utilize Selenium. The webpage is loaded using: driver.execute_script("return document.documentElement.outerHTML") (Using this javascript ...

Encountered an issue while trying to access the length property of an undefined value within an aside

I am currently utilizing ng-strap's modal, alert, and aside features. Each of them is functioning properly on their own, but when I attempt to place an alert or modal inside an aside, it throws the following error: Uncaught TypeError: Cannot read p ...

Is it feasible to utilize a variable as a function within JavaScript programming?

I've been diving into the world of express.js and came across these statements. const express = require('express'); const app = express(); It's intriguing how we can call the variable "express" as a function by simply adding parenthese ...

How do you utilize the beforeMount lifecycle method in Vue.js?

I am currently working on creating a weather application using Vue.js. I have successfully obtained the latitude and longitude when the window loads, and I have set these values to variables lat and long. Despite this, I am encountering issues when tryin ...

Utilizing Vue to create multiple components and interact with Vuex state properties

I am currently learning Vue and using it with Vuex (without Webpack). However, I am facing some challenges while implementing a simple example and the documentation is not very clear to me. One issue I encountered is that I cannot access the Vuex st ...

jQuery - easily adjust wrapping and unwrapping elements for responsive design. Perfect for quickly undo

Within the WordPress PHP permalinks and Fancybox plugin, there are elements enclosed in an "a" tag like so: <a href="<?php the_permalink(); ?>" class="example" id="exampleid" data-fancybox-type="iframe"> <div class="exampledivclass"> ...

Strategies to troubleshoot and fix issues in Three.js

My Three.js page needs to be updated from version r42 to r55, and a lot of the API has changed since then. While most of the changes were easy to implement, I am currently facing some difficulty with the JSONLoader. The format has transitioned from JavaSc ...

Transitioning between different hues using specific fraction values

On my website, there is a variable called 'x' which represents a percentage. I am looking for a way to assign colors based on this percentage - with 0% being red and 100% being blue. For example, if 'x' is 50%, the color should be a mix ...

Selection of dropdown option is necessary

Hey there, I'm working on a dropdown feature and need to ensure that an option is always selected by the user. To achieve this, I'm looking to implement client-side validation for a required field. <b-dropdown id="clientData" ...