I have a Sveltekit project where I am using firebase for authentication. I am storing the firebase.js file which contains the config parameters like apiKey and authDomain in the srclib folder. I am storing the apiKey value in the .env file which is present at the root of the project and using the process.env.API_KEY to load the value for the same. However when I do npm run build I get an error in the browser console – "process is not defined". I tried the below approaches but none of them seem to work –
Approach 1 –
import { initializeApp } from 'firebase/app'
import { getAuth } from 'firebase/auth'
import { config } from 'dotenv'
config()
const firebaseConfig = {
apiKey: process.env.API_KEY,
authDomain: process.env.AUTH_DOMAIN,
}
const app = initializeApp(firebaseConfig)
const auth = getAuth(app)
export default auth
Approach 2 –
Here I used the env-cmd library which I found via another Stackoverflow post. Below is the updated code
import { initializeApp } from 'firebase/app'
import { getAuth } from 'firebase/auth'
const firebaseConfig = {
apiKey: process.env['API_KEY'],
authDomain: process.env['AUTH_DOMAIN'],
}
const app = initializeApp(firebaseConfig)
const auth = getAuth(app)
export default auth
I also updated the scripts in package.json like below –
"scripts": {
"dev": "env-cmd vite dev",
"build": "env-cmd vite build",
"package": "svelte-kit package",
"preview": "vite preview",
"prepare": "svelte-kit sync"
}
Neither of the approaches seem to work and I still get the same error i.e. "process is not defined". Even some of the other repos I checked on Github had the apiKey hard coded in the config file, which obviously is a bad practice, even for hobby projects.
Any ideas on how I could incorporate the firebase apiKey via the .env file?
2
Answers
From the firebase docs
Your
.env
file should have variables like thisVITE_SECURE_API_KEY=API-KEY
and you can use them in your client-side app using
import.meta.env.VITE_SECURE_API_KEY
.dotenv
works on the server-side for sveltekit using node-adapter, also the firebase-admin package works only on the node environment.