Dev Cafe
Published in

Dev Cafe

How to setup .env variables to your Svelte JS app

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_URL= https://api-local.yourdomain.com/v1
API_CLIENT_KEY= 2314233453451232
API_REGION= EU

Step 3: Update the rollup.config.js file

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

Here is the rollup.config.js file

rollup.config.js

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

//App.svelte<script>
const isProd = __myapp.env.isProd
const apiUrl = __myapp.env.API_URL
</script>
<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.

Conclusion

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

--

--

--

Helpful short articles and ideas make better developers

Recommended from Medium

Building a React-based Chat Client with Redux

React Server Side Rendering(SSR) for existing big nodejs project. webpack 4

Express.js and AWS Lambda — a serverless love story

The time saving order of web development

Do you promise to use asynchronous Javascript?

Microsoft Azure (AZ-104): ARM Template

How to match phone numbers?

Let’s talk about NodeJS Promises, I promise it won't be long

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
Firthous

Firthous

Tech Lead | Full Stack Dev

More from Medium

Add a Map With a Point to Your Website

## Intended audience

Create a GitHub-Style Calendar Heatmap

VSCode can now Transfer Files…?