If you deploy with Vercel, you know how easy it is to to work with. Sometimes you want to hide certain environment variables from your users. In this example, I am going to use the Firebase Api keys, although they do not necessarily need to be secured.
Step 1
- Create
.env
file at the root of your sveltekit project
Step 2
- Add this file
.env
to your.gitignore
file
Step 3
- Add the environment variables you want to secure to the file with the
VITE_
prefix.
SvelteKit with vite imports the dotenv package under the hood.
Example .env
file:
VITE_FIREBASE_APIKEY="----"
VITE_FIREBASE_AUTH_DOMAIN="---"
VITE_FIREBASE_PROJECT_ID="---"
VITE_FIREBASE_STORAGE_BUCKET="---"
VITE_FIREBASE_MESSAGING_SENDER_ID="---"
VITE_FIREBASE_APP_ID="---"
VITE_FIREBASE_MEASUREMENT_ID="---"
VITE_DGRAPH_ENDPOINT="---"
Step 4
- Create your configuration file.
Example: src/config.ts
let process: any;
const p = process?.env ? process.env : import.meta.env;
export const dgraph_config = p.VITE_DGRAPH_ENDPOINT;
export const firebase_config = {
"apiKey": p.VITE_FIREBASE_APIKEY,
"authDomain": p.VITE_FIREBASE_AUTH_DOMAIN,
"projectId": p.VITE_FIREBASE_PROJECT_ID,
"storageBucket": p.VITE_FIREBASE_STORAGE_BUCKET,
"messagingSenderId": p.VITE_FIREBASE_MESSAGING_SENDER_ID,
"appId": p.VITE_FIREBASE_MEASUREMENT_ID,
"measurementId": p.VITE_DGRAPH_ENDPOINT
};
SvelteKit uses
import.meta.env.VITE_YOUR_VARIABLE
as a way to automatically import any file with.env
.Vercel uses
process.env.YOUR_VARIABLE
to import the environments.You don't need the
VITE_
prefix in Vercel, I just kept it for consistency.
Step 5 - Typescript Users
- If you use typescript (why you wouldn't is beyond me) and you get a type error with
import.meta.env
, add this totsconfig.json
:
{
"compilerOptions": {
...
"types": [
"vite/client"
]
Step 6 - Vercel
- Add your equivalent variables to your Vercel Project under Settings --> Environment Variables:
Step 7
Finally, import the code in any file you want to use it in:
import { firebase_config } from '../config';
Note: If you want to test production and dev versions on your local machine, you could also use dev
to detect which mode you're in:
import { dev } from '$app/env';
Hope this helps someone,
J
Top comments (2)
Just wondering whether the
let process
declaration insrc/config.ts
would shadow the globalprocess
object and therefore thep
constant would always be assignedimport.meta.env
?The let declaration is so that Typescript does not throw an error. Vercel will set the
process
variable as expected. The?
checks whether or not it is undefined. Thelet
keyword does not actually set it to a value.