busayolawumi
busayolawumi

Reputation: 49

Issues accessing variables from .env file

I have been trying to get my API key from my .env file that is at the root of my folder of my Vite app to a JSX file where I want to do the fetching, but each time I use process.env.{MY_VARIABLE_NAME} the browser console returns an error:

ReferenceError: process is not defined

The line where I am trying to get data from the API:

const api = await axios.get(`https://api.spoonacular.com/recipes/random?apikey=${process.env.RECIPE_API_KEY}`)

I checked around and I have tried installing dotenv and it still not works

Can anyone help with this, and if there is any more information that will be needed, I am available to provide it.

Upvotes: 1

Views: 90

Answers (4)

Satyen272
Satyen272

Reputation: 1

Use this:

const api_key = import.meta.env.VITE_API_KEY;

Also in .env file use VITE_ in place of REACT_APP_ if you are using VITE in your project.

This works for me.

Upvotes: 0

busayolawumi
busayolawumi

Reputation: 49

After doing some research, I found out that, since I am using a Vite React app, to access the variables in the .env file import.meta.env.{MY_VARIABLE_NAME} should be used instead of process.env.

And my I have to add a VITE_ prefix to the start of the variable name in both my .env file and where I am trying to access the API key.

Upvotes: 0

Rhythm Shandlya
Rhythm Shandlya

Reputation: 124

If you're not using a React app or a bundler like Webpack, and you want to use environment variables directly on the client side without any build process, you can expose the environment variables in your server's response and access them in your client-side JavaScript code.

Upvotes: 1

Amit Poudyal
Amit Poudyal

Reputation: 97

You may try by assigning it to the variable and then use it as:

const API= process.env.RECIPE_API_KEY;
const api = await axios.get(`https://api.spoonacular.com/recipes/random?apikey=${API}`)

I think this will work

Upvotes: 1

Related Questions