0
0
SvelteHow-ToBeginner · 3 min read

How to Use Environment Variables in SvelteKit

In SvelteKit, use import.meta.env.VITE_YOUR_VAR to access environment variables prefixed with VITE_ in client-side code. For server-side only variables, use import.meta.env.YOUR_VAR without the VITE_ prefix.
📐

Syntax

SvelteKit uses import.meta.env to access environment variables. Variables prefixed with VITE_ are exposed to client-side code. Variables without this prefix are only available on the server side.

Example parts:

  • import.meta.env.VITE_API_URL: Client and server access.
  • import.meta.env.SECRET_KEY: Server-only access.
javascript
const apiUrl = import.meta.env.VITE_API_URL;
const secretKey = import.meta.env.SECRET_KEY;

console.log('API URL:', apiUrl);
console.log('Secret Key:', secretKey);
Output
API URL: https://api.example.com Secret Key: (only on server, not exposed to client)
💻

Example

This example shows how to define environment variables in a .env file and use them in a SvelteKit component.

svelte
// .env file
VITE_API_URL=https://api.example.com
SECRET_KEY=supersecret

// src/routes/+page.svelte
<script>
  // Access client-exposed env variable
  const apiUrl = import.meta.env.VITE_API_URL;
</script>

<h1>API URL is: {apiUrl}</h1>
Output
API URL is: https://api.example.com
⚠️

Common Pitfalls

1. Forgetting to prefix client variables with VITE_ means they won't be available in the browser.
2. Exposing sensitive keys by prefixing them with VITE_ leaks secrets to the client.
3. Not restarting the dev server after changing .env files causes old values to persist.

javascript
/* Wrong: secret exposed to client */
// .env
VITE_SECRET_KEY=supersecret

// src/routes/+page.svelte
<script>
  const secret = import.meta.env.VITE_SECRET_KEY; // This is exposed to client!
</script>

/* Right: keep secret server-only */
// .env
SECRET_KEY=supersecret

// src/routes/+page.server.js
export function load() {
  const secret = import.meta.env.SECRET_KEY; // Server only
  return { secret };
}
📊

Quick Reference

UsageAccessPrefix RequiredNotes
Client-side env variableBrowser and serverVITE_Must start with VITE_ to be exposed
Server-side env variableServer onlyNo prefixSafe for secrets, not exposed to client
Access syntaxBothN/AUse import.meta.env.VARIABLE_NAME
Change env variablesDev serverN/ARestart dev server to apply changes

Key Takeaways

Prefix client environment variables with VITE_ to expose them safely in SvelteKit.
Keep sensitive variables without VITE_ prefix to restrict them to server-side only.
Access environment variables using import.meta.env.VARIABLE_NAME syntax.
Always restart the development server after modifying .env files.
Never expose secrets by prefixing them with VITE_ as they become public.