skip to Main Content

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


  1. From the firebase docs

    Unlike how API keys are typically used, API keys for Firebase services are not used to control access to backend resources; that can only be done with Firebase Security Rules (to control which users can access resources) and App Check (to control which apps can access resources).

    Usually, you need to fastidiously guard API keys (for example, by using a vault service or setting the keys as environment variables); however, API keys for Firebase services are ok to include in code or checked-in config files.

    Login or Signup to reply.
  2. Your .env file should have variables like this VITE_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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search