I have seen this question come up numerous times in the svelte discord chat, so I have decided to write a short guide on how to get dotenv working with Svelte 3 . I won’t be walking through setting up Svelte 3 in this guide, but you can check out the Svelte website for that. Before we go into how to set up dotenv, let’s talk a little about dotenv first.
What is dotenv?
Dotenv is a node module that loads .env
files, which contains environment variables into node’s process.env
.
Why should I use it?
You should use it when you want to have separate environment variables based on the platform (dev, staging, production) the code is running on. You should never have multiple .env
files inside of the same project e.g. .env.test
and .env.prod
. Each platform should only contain one .env
file in the project root.
The Setup
First, we need to install dotenv from the terminal using either npm or yarn.
# with npm
npm install dotenv --save-dev
# or with yarn
yarn add dotenv --dev
Next, you will also need to install @rollup/plugin-replace .
# with npm
npm install @rollup/plugin-replace --save-dev
# or with yarn
yarn add @rollup/plugin-replace --dev
Once these packages have been installed we then need to modify our rollup.config.js
to get dotenv into our Svelte build. But before we get to that, you might be wondering why we installed the dotenv module as a dev dependency, this is because we won’t be using this at runtime, we cannot use it at runtime in a svelte project that doesn’t have server-side rendering because its a node module.
Let’s modify our rollup.config.js
now to include both dotenv and @rollup/plugin-replace.
import svelte from 'rollup-plugin-svelte';
...
import replace from '@rollup/plugin-replace';
import dotenv from 'dotenv';
dotenv.config();
const production = !process.env.ROLLUP_WATCH;
export default {
...
plugins: [
replace({
USER_NAME: JSON.stringify(process.env.USER_NAME)
}),
svelte({
// enable run-time checks when not in production
dev: !production,
// we'll extract any component CSS out into
// a separate file - better for performance
css: css => {
css.write('public/build/bundle.css');
}
}),
...
],
...
};
Because our Svelte project is a client (browser) only project, we cannot directly import dotenv into our Svelte code, we have to use the @rollup/plugin-replace plugin to get the values into our Svelte code.
Things to be aware of
- IMPORTANT - You must NOT include sensitive data in your
.env
file that you are using with your Svelte client-side only project, these will be exposed to anyone using your web app. - You should
JSON.stringify
data from a.env
file when using it in @rollup/plugin-replace, otherwise, your app will break because it will replace the variable as it is, so if in your.env
file you haveUSER_NAME=Andrew
, then in you doconst userName = USER_NAME
in your Svelte app, it will replace it asconst userName = Andrew
without any quotes.