How to setup .env variables to your Svelte JS app

Feb 23, 2020 · 2 min read

Most of the time writing apps required configuration variables based on environments like local, QA, stage, and production.

In Svelte JS we can use node modules dotenv and @rollup/plugin-replace to get the environment variables on client-side code.

Let see the implementations as step by step

Step 1: Install the following node modules as a dev dependency

npm install --save-dev dotenv @rollup/plugin-replace

Step 2: Add .env file into your project root

Our .env file should look like this

API_CLIENT_KEY= 2314233453451232

Step 3: Update the rollup.config.js file

import the node modules (dotenv, @rollup/plugin-replace)

Here is the rollup.config.js file


Adding replace() inside plugins. It is used to find the defined properties, and replace them into the value at compile time.

So we parsed the dotenv config() variables as JSON.stringify() object inside replace().

If we don't want to parse all the declared variables in the .env file, we can use required ones like

//replace() for specific variable import__myapp: JSON.stringify({        
env: {
isProd: production,
API_URL : process.env.API_URL //only using API_URL

Step 4: Access the variables inside Svelte components

const isProd = __myapp.env.isProd
const apiUrl = __myapp.env.API_URL
<h4>{isProd} - {apiUrl}</h4>

Now we can access all the environment variable as if it was a global variable inside our Svelte component.

Dev Note: This technique can be only used the application run completely on the client-side. It is not a recommended approach for Sapper or app running in the server with hydratable options.

Check out my other Svelte JS articles if you like.


Consider this way we can add environment-specific client-side variables into our awesome Svelte JS app.

Dev Cafe

Cofeetime Dev Articles

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store