SvelteKit Server & Env

18. Server Hooks, Error Handling & Env Variables

Intercept requests with server hooks, implement expected error contracts with custom +error.svelte views, and strictly isolate private secrets.

hooks-env-errors.ts
// src/hooks.server.ts & Environment Isolation
import type { Handle, HandleServerError } from '@sveltejs/kit';
import { SECRET_DB_KEY } from '$env/static/private'; // Compile-time private secret
import { PUBLIC_APP_URL } from '$env/static/public';   // Safe public constant

export const handle: Handle = async ({ event, resolve }) => {
  // Global Auth / Session Verification Hook
  const sessionCookie = event.cookies.get('session_id');
  if (sessionCookie) {
    event.locals.user = { id: 'usr_88', role: 'admin' };
  }

  const response = await resolve(event);
  response.headers.set('X-Frame-Options', 'DENY');
  return response;
};

export const handleError: HandleServerError = ({ error, event }) => {
  console.error(`Server Error on ${event.url.pathname}:`, error);
  return { message: 'An internal server error occurred.', code: 'ERR_INTERNAL' };
};

Server Hooks, Error Handling & Environment Variables

SvelteKit provides strict boundaries for server middleware hooks, expected vs unexpected errors, and four isolated tiers of environment variable protection.

  • Server Hooks (hooks.server.ts): Intercept incoming requests with handle, transform backend fetch requests with handleFetch, and log errors globally with handleError.
  • Error Contract (error() vs +error.svelte): Throw typed errors using error(404, { message: 'Not Found' }) to render friendly user-facing +error.svelte layouts without leaking stack traces.
  • Strict Environment Isolation: SvelteKit statically prevents private secrets ($env/static/private) from ever being imported into client-side code at compile time.
Environment Variable Security Matrix 4-Tier Env Isolation
Import Path: $env/static/private
Evaluation Strategy:

Compile-time inlined (Server only)

Security Boundary:

Protected: Build fails if bundled into client code

# Sample usage in .env:
DATABASE_URL=postgres://neon.tech/main