Accessing Environment variable in Svelte App

I am trying to utilise Environment variables in a svelte application.
The app is running fine on a local machine which uses a .env file but does not work when published on Netlify.(This is igonored by github)
I have added the environment variable API_KEY in the deployment section and am trying to access it using process.env.API_KEY.
i.e const ApiKey = process.env.API_KEY

My deployment is:

from github:

Can you advise if this is the correct approach to use?

hi there, did you see this guide already?

Hi Perry,
Thanks for your quick response.

I have used the UI to set a value for API_KEY but when i try to access it using process.env.API_KEY it is showing as undefined.

I am still having difficulty using teh environment variables.

I have set a varaiable API_URL in the netlify UI and I am trying to access it using process.env.API_URL.
This results in Undefined.
Could someone advise if i am doing something wrong?
Any advice would be helpful other than to read the Support Guide which I have done but still cannot get the app to work.
It is a Svelte app built using NPM RUN BUILD

Hi, @WormCrew. The environment variables you define only exists in two places at Netlify:

  • in the build system during the site build
  • in the runtime environment of serverless functions

The environment variables will not be available in the client side javascript.

The environment variables are not defined in the end user’s web browser because it has no way to see the build system environment or the serverless function environment. You cannot access these environment variables in your client side code unless you include them in your client side javascript somewhere.

In other words, if you modify your javascript files to include the literal environment variables in some way - only then will the client javascript have access to those variables. You must put the variable in the javascript file for the browser’s javascript to be able to see them.

If there are other questions about this, please let us know.

Hi Luke,

I managed to resolve this. I had a typo error in the rollup.config.js file.

For reference the rollup.config.js file needs the following added:

import { config as configDotenv } from 'dotenv';
import replace from '@rollup/plugin-replace';
const production = !process.env.ROLLUP_WATCH;

and also

  __app: JSON.stringify({
    env: {
      isProd: production,
      API_KEY : process.env.API_KEY

added to the plugins object.
I can then access this variable in my code using the following:

const ApiKey = __myapp.env.API_KEY

1 Like

sorry __app should read __myapp

1 Like

thank you for sharing, @WormCrew !