Understanding Environment Variables in SvelteKit
Summary of SvelteKit Environment Variables
Main Point
The SvelteKit tutorial on environment variables explains how to manage and access environment-specific configurations in your SvelteKit applications. This is essential for managing settings that differ between development and production environments.
Key Concepts
- Environment Variables: These are variables that can affect the way running processes behave on a computer. They are typically used for configuration settings that should not be hardcoded in your application.
- Static vs Public Variables:
- Static Variables: These are variables that are not exposed to the client-side code. They are only accessible in server code.
- Public Variables: These are variables that can be accessed by both server and client-side code. They are prefixed with
$
to indicate that they are public.
How to Define Environment Variables
- Creating a
.env
file:- You can create a
.env
file at the root of your SvelteKit project to define your environment variables.
- You can create a
- Accessing Environment Variables:
- Use
import.meta.env
to access your environment variables in your application.
- Use
Example of accessing a public variable:
const apiUrl = import.meta.env.VITE_API_URL;
Example content of .env
:
VITE_API_URL=https://api.example.com
VITE_PUBLIC_KEY=abc123
Practical Example
Using Static Variables in Server Code:
// src/routes/api.js
import { env } from '$env/dynamic/private';
const secret = env.SECRET_KEY; // This won't be exposed to the client
Using Public Variables in Components:
<script>
let apiUrl = import.meta.env.VITE_API_URL;
</script>
<p>The API URL is: {apiUrl}</p>
Summary
Understanding how to use environment variables in SvelteKit allows developers to create applications that are adaptable to different environments, such as local development or production. By distinguishing between static and public variables, you can ensure sensitive information remains secure while still providing necessary configurations to your client-side code.