DEV Community

Cover image for SvelteKit .env secrets
Scott Spence
Scott Spence

Posted on • Originally published at scottspence.com

1 1

SvelteKit .env secrets

So SvelteKit is super awesome n' all and the best thing ever but have
you ever tried to use a .env secret that you didn't want exposed on
the client?

SvelteKit uses Vite and it has a specific way to reference Env
Variables and Modes
, you reference a .env variable with
import.meta.env.VITE_NAME_OF_VARIABLE the VITE_* prefix means in
SvelteKit it makes that variable available on the client.

What if you have a secret key?

So if you want a secret key that's not exposed to the client then,
what? Remove the VITE_* prefix? Well, no, so, how to have secrets??

The answer is don't use Vite and instead use something to load the
variables from the .env file.

Use env-cmd or dotenv or whatever you want to use to ensure the
runtime process.env is populated in dev.

Example

Here I have defined my .env file at the root of my project:

VITE_CLIENT_VARIABLE=wheeeeeeeee
SUPER_SECRET_SECRET=shhhhhh
Enter fullscreen mode Exit fullscreen mode

Then I've created a secret.js file to access my secret:

export const API_URL = process.env['SUPER_SECRET_SECRET']
Enter fullscreen mode Exit fullscreen mode

Then I've added env-cmd to my dev script in my package.json so
that process.env has the super secret secret populated:

"scripts": {
  "dev": "env-cmd svelte-kit dev",
Enter fullscreen mode Exit fullscreen mode

Now I can access my super secret secret and have client side variables
too.

Update

There's annother option to use which I found on the Blog by
Hideckies
in their example it's a svelte.config.js change:

const config = {
  kit: {
    // ...
    vite: {
      define: {
        'process.env': process.env,
      },
    },
  },
}

export default config
Enter fullscreen mode Exit fullscreen mode

Check out the post linked earlier for more info!

Thanks!

A kind thank you to Discord users Xyo and especially saikatdas0790
on the Svelte Discord svelte-kit channel for helping me out with
this!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (1)

Collapse
 
gevera profile image
Denis Donici

I didn't know that. Thanks for sharing

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more