Reputation: 1976
I am trying to get some environment variables to work but for the life of me I can not...I have looked through a few SO answers and they all seem to point to how I have set things up.
Yet I keep getting undefined. This is how I am testing the variable.
import {useState} from 'react'
import {FaCog} from 'react-icons/fa'
function App() {
const [data, setData] = useState([])
const [dealId, setDealId] = useState('')
const [loading, setLoading] = useState(null)
const [error, setError] = useState('')
// Counter
const [count, setCounter] = useState(0)
console.log('HOST:', import.meta.env.HOST) // returns undefined
This is my .env
file, which is placed in the root
# .env
HOST=127.0.0.1:8000
This is my structure (removed node_modules) for ease
.
├── .env
├── index.html
├── package-lock.json
├── package.json
├── postcss.config.js
├── src
│ ├── App.jsx
│ ├── favicon.svg
│ ├── index.css
│ ├── logo.svg
│ └── main.jsx
├── tailwind.config.js
└── vite.config.js
Where am I going wrong? I have restated the vite server many times already...i am stumped
Upvotes: 5
Views: 11622
Reputation: 123
You need to prefix the name of your environment variables with VITE_
if you want to expose the variables clientside.
Like this: VITE_HOST
both in the .env
-file and in the code. See the example below.
# .env
VITE_HOST=127.0.0.1:8000
// .js-file
console.log('HOST:', import.meta.env.VITE_HOST)
More about environment variables in Vite here: https://vitejs.dev/guide/env-and-mode.html#env-variables
Upvotes: 8