Managing Environment Variables in SvelteKit: A Comprehensive Guide

SvelteKit: Environment Variables in Static and Private Modes

Overview

SvelteKit allows you to effectively manage environment variables, which are crucial for configuring your application. This tutorial covers how to work with these variables in different contexts, specifically focusing on static and private modes.

Key Concepts

1. Environment Variables

  • Definition: Environment variables are key-value pairs that provide configuration settings to your application.
  • Use Cases: They are often used for sensitive information (like API keys) or environment-specific settings (like database URLs).

2. Static Environment Variables

  • Definition: Static variables are defined at build time and do not change during runtime.
  • Accessibility: You can access these variables in your components using the $env module.

3. Private Environment Variables

  • Definition: Private variables are only accessible on the server side (like API keys) and are not exposed to the client.
  • Use: This is important for keeping sensitive information secure.

How to Use Environment Variables

Setting Up

  1. Accessing Variables:
    • Public Variables: Start with VITE_ to expose them to the client.
    • Private Variables: Can be accessed directly in server-side files.

Create a .env File: Place your environment variables in this file.

VITE_PUBLIC_API_URL=https://api.example.com
PRIVATE_API_KEY=secretkey123

Example Usage

// Accessing public variable in a Svelte component

  import { env } from '$env/dynamic/public';

  const apiUrl = env.VITE_PUBLIC_API_URL;


// Accessing private variable in a server-side endpoint
export async function get() {
  const apiKey = process.env.PRIVATE_API_KEY;
  // Use apiKey to make a request
}

Conclusion

Understanding how to manage environment variables in SvelteKit is essential for building secure and configurable applications. By using static and private variables appropriately, you can ensure sensitive data remains protected while providing necessary configurations for your app.