Choose between universal and server-only load functions
masterSvelteKit provides two types of load functions. Choosing the correct one is critical for security and data serialization.
+page.server.ts (Server-only)
Use this when you need to:
- Access secrets or credentials (e.g., API keys from
$env/static/private). - Connect to a database.
- Call server-only APIs.
- Execute sensitive business logic.
+page.js (Universal)
Use this when you need to:
- Access public APIs.
- Return non-serializable data (e.g., functions, classes, or
DOMParser). - Benefit from client-side caching.
Warning: Never use +page.js for secrets, as this code runs in the browser and will expose your credentials.
// +page.server.ts - CORRECT for secrets
import { STRIPE_SECRET_KEY } from "$env/static/private";
export const load = async ({ fetch }) => {
const response = await fetch("https://api.stripe.com/charges", {
headers: { Authorization: `Bearer ${STRIPE_SECRET_KEY}` },
});
return { charges: await response.json() };
};