This is a comprehensive request about implementing dynamic server-side data fetching in SvelteKit using the handleFetch hook. The user wants to:
Intercept all server-side fetch requests
Inject an internal API key or mTLS certificate automatically
Handle internal microservice calls
Let me create a comprehensive implementation that covers:
Basic handleFetch hook implementation
API key injection
mTLS certificate handling
Environment-based configuration
Retry logic and error handling
Logging and monitoring
Example usage in routes
I'll provide a production-ready solution with best practices.
SvelteKit Dynamic Server-Side Data Fetching with handleFetch
I'll provide a comprehensive implementation for intercepting and handling server-side fetch requests with automatic authentication injection.
1. Core Hook Implementation
typescript Copy code
// src/hooks.server.ts
import { sequence } from '@sveltejs/kit/hooks';
import type { Handle } from '@sveltejs/kit';
import { handleFetch as handleFetchHook } from './lib/server/fetch-handler';
export const handle: Handle = sequence(handleFetchHook);
2. Fetch Handler with API Key Injection
typescript Copy code
// src/lib/server/fetch-handler.ts
import type { Handle, RequestEvent } from '@sveltejs/kit';
import type { Request, Response } from '@sveltejs/kit';
import {
INTERNAL_API_KEY,
INTERNAL_API_BASEURL,
NODE_ENV
} from '$env/static/private';
import { logger } from './logger';
import { retryFetch } from './retry-handler';
const INTERNAL_HOSTS = ['localhost', 'internal-api', '127.0.0.1'];
const MAX_RETRIES = 3;
const RETRY_DELAY = 1000;
interface FetchMetrics {
startTime: number;
endTime?: number;
duration?: number;
status?: number;
error?: string;
}
/**
* Determine if URL is an internal service call
*/
function isInternalService(url: string): boolean {
try {
const urlObj = new URL(url);
const host = urlObj.hostname;
return (
INTERNAL_HOSTS.some(h => host.includes(h)) ||
url.includes(INTERNAL_API_BASEURL)
);
} catch {
return false;
}
}
/**
* Inject authentication headers for internal services
*/
function injectAuthHeaders(
headers: Headers,
isInternal: boolean
): Headers {
const newHeaders = new Headers(headers);
if (isInternal && INTERNAL_API_KEY) {
newHeaders.set('Authorization', `Bearer ${INTERNAL_API_KEY}`);
newHeaders.set('X-Service-To-Service', 'true');
newHeaders.set('X-Request-ID', generateRequestId());
}
// Always set user-agent for internal tracking
newHeaders.set('User-Agent', `SvelteKit-Internal/${NODE_ENV}`);
return newHeaders;
}
/**
* Generate unique request ID for tracing
*/
function generateRequestId(): string {
return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
}
/**
* Record fetch metrics
*/
function recordMetrics(
url: string,
metrics: FetchMetrics
): void {
const duration = (metrics.endTime || 0) - metrics.startTime;
logger.debug('Fetch metrics', {
url,
duration,
status: metrics.status,
error: metrics.error
});
// Send to monitoring service if needed
if (duration > 5000) {
logger.warn('Slow fetch detected', {
url,
duration,
status: metrics.status
});
}
}
/**
* Main fetch handler
*/
export const handleFetch: Handle = async ({ event, resolve }) => {
const originalFetch = global.fetch;
// Override fetch during server-side rendering
global.fetch = async (
input: RequestInfo | URL,
init?: RequestInit
): Promise<Response> => {
const url = input instanceof Request ? input.url : String(input);
const metrics: FetchMetrics = { startTime: Date.now() };
try {
const isInternal = isInternalService(url);
if (isInternal) {
logger.debug('Internal service request', { url });
}
// Create fetch request with injected headers
const headers = new Headers(init?.headers);
const finalHeaders = injectAuthHeaders(headers, isInternal);
const fetchInit: RequestInit = {
...init,
headers: finalHeaders
};
// Retry logic for internal services
const response = isInternal
? await retryFetch(url, fetchInit, MAX_RETRIES, RETRY_DELAY)
: await originalFetch(url, fetchInit);
metrics.endTime = Date.now();
metrics.status = response.status;
// Clone response for logging without consuming the body
const clonedResponse = response.clone();
recordMetrics(url, metrics);
// Log response details for debugging
if (!response.ok && isInternal) {
const errorBody = await clonedResponse.text().catch(() => '');
logger.error('Internal service error', {
url,
status: response.status,
statusText: response.statusText,
body: errorBody.substring(0, 200)
});
}
return response;
} catch (error) {
metrics.endTime = Date.now();
metrics.error = error instanceof Error ? error.message : String(error);
recordMetrics(url, metrics);
logger.error('Fetch failed', {
url,
error: metrics.error
});
throw error;
}
};
const response = await resolve(event);
// Restore original fetch
global.fetch = originalFetch;
return response;
};
export default handleFetch;
3. Retry Handler
typescript Copy code
// src/lib/server/retry-handler.ts
import { logger } from './logger';
export interface RetryOptions {
maxRetries?: number;
delayMs?: number;
backoffMultiplier?: number;
timeoutMs?: number;
}
/**
* Fetch with exponential backoff retry logic
*/
export async function retryFetch(
url: string,
init: RequestInit,
maxRetries: number = 3,
initialDelayMs: number = 1000,
backoffMultiplier: number = 2
): Promise<Response> {
let lastError: Error | null = null;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 30000); // 30s timeout
const response = await fetch(url, {
...init,
signal: controller.signal
});
clearTimeout(timeoutId);
// Success - return immediately
if (response.ok) {
if (attempt > 0) {
logger.info('Fetch succeeded after retry', {
url,
attempts: attempt + 1
});
}
return response;
}
// Don't retry on 4xx errors (except 429)
if (response.status >= 400 && response.status < 500 && response.status !== 429) {
return response;
}
// Store error for logging
lastError = new Error(`HTTP ${response.status}: ${response.statusText}`);
if (attempt < maxRetries) {
const delayMs = initialDelayMs * Math.pow(backoffMultiplier, attempt);
logger.warn('Fetch failed, retrying', {
url,
attempt: attempt + 1,
maxRetries,
nextRetryIn: delayMs,
status: response.status
});
await new Promise(resolve => setTimeout(resolve, delayMs));
}
} catch (error) {
lastError = error instanceof Error ? error : new Error(String(error));
if (attempt < maxRetries) {
const delayMs = initialDelayMs * Math.pow(backoffMultiplier, attempt);
logger.warn('Fetch error, retrying', {
url,
attempt: attempt + 1,
maxRetries,
nextRetryIn: delayMs,
error: lastError.message
});
await new Promise(resolve => setTimeout(resolve, delayMs));
}
}
}
logger.error('Fetch failed after retries', {
url,
attempts: maxRetries + 1,
lastError: lastError?.message
});
throw lastError || new Error('Fetch failed after retries');
}
4. mTLS Certificate Handler
typescript Copy code
// src/lib/server/mtls-handler.ts
import * as fs from 'fs';
import * as path from 'path';
import type https from 'https';
import { logger } from './logger';
interface mTLSConfig {
enabled: boolean;
certPath: string;
keyPath: string;
caPath?: string;
}
let cachedAgent: https.Agent | null = null;
/**
* Get mTLS configuration from environment
*/
export function getmTLSConfig(): mTLSConfig {
return {
enabled: process.env.MTLS_ENABLED === 'true',
certPath: process.env.MTLS_CERT_PATH || '',
keyPath: process.env.MTLS_KEY_PATH || '',
caPath: process.env.MTLS_CA_PATH
};
}
/**
* Create HTTPS agent with mTLS certificates
*/
export function createTLSAgent(config: mTLSConfig): https.Agent | null {
if (!config.enabled || !config.certPath || !config.keyPath) {
return null;
}
if (cachedAgent) {
return cachedAgent;
}
try {
const cert = fs.readFileSync(config.certPath, 'utf8');
const key = fs.readFileSync(config.keyPath, 'utf8');
const agentOptions: https.AgentOptions = {
cert,
key,
rejectUnauthorized: process.env.NODE_ENV === 'production'
};
// Add CA certificate if provided
if (config.caPath) {
try {
const ca = fs.readFileSync(config.caPath, 'utf8');
agentOptions.ca = ca;
} catch (error) {
logger.warn('Failed to load CA certificate', {
path: config.caPath,
error
});
}
}
const https = require('https');
cachedAgent = new https.Agent(agentOptions);
logger.info('mTLS Agent initialized successfully');
return cachedAgent;
} catch (error) {
logger.error('Failed to create mTLS Agent', {
error: error instanceof Error ? error.message : String(error),
certPath: config.certPath,
keyPath: config.keyPath
});
return null;
}
}
/**
* Validate certificate paths exist
*/
export function validateCertificatePaths(config: mTLSConfig): boolean {
if (!config.enabled) {
return true;
}
const paths = [config.certPath, config.keyPath];
if (config.caPath) paths.push(config.caPath);
for (const certPath of paths) {
if (!fs.existsSync(certPath)) {
logger.error('Certificate file not found', { path: certPath });
return false;
}
}
return true;
}
5. Advanced Fetch Handler with mTLS
6. Logger Implementation
typescript Copy code
// src/lib/server/logger.ts
import { NODE_ENV } from '$env/static/private';
export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
interface LogEntry {
timestamp: string;
level: LogLevel;
message: string;
data?: Record<string, any>;
context?: string;
}
class Logger {
private isDevelopment = NODE_ENV === 'development';
private format(entry: LogEntry): string {
const { timestamp, level, message, data } = entry;
const dataStr = data ? ` ${JSON.stringify(data)}` : '';
return `[${timestamp}] ${level.toUpperCase()}: ${message}${dataStr}`;
}
private shouldLog(level: LogLevel): boolean {
if (this.isDevelopment) return true;
const levels: LogLevel[] = ['debug', 'info', 'warn', 'error'];
return levels.indexOf(level) >= levels.indexOf('info');
}
private log(level: LogLevel, message: string, data?: Record<string, any>): void {
if (!this.shouldLog(level)) return;
const entry: LogEntry = {
timestamp: new Date().toISOString(),
level,
message,
data,
context: 'SvelteKit-Fetch'
};
const formatted = this.format(entry);
switch (level) {
case 'debug':
console.debug(formatted);
break;
case 'info':
console.info(formatted);
break;
case 'warn':
console.warn(formatted);
break;
case 'error':
console.error(formatted);
break;
}
// Send to external logging service
if (level === 'error' || level === 'warn') {
sendToExternalLogger(entry).catch(err =>
console.error('Failed to send log to external service:', err)
);
}
}
debug(message: string, data?: Record<string, any>): void {
this.log('debug', message, data);
}
info(message: string, data?: Record<string, any>): void {
this.log('info', message, data);
}
warn(message: string, data?: Record<string, any>): void {
this.log('warn', message, data);
}
error(message: string, data?: Record<string, any>): void {
this.log('error', message, data);
}
}
async function sendToExternalLogger(entry: LogEntry): Promise<void> {
const endpoint = process.env.LOG_ENDPOINT;
if (!endpoint) return;
try {
await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(entry)
});
} catch (error) {
// Silently fail to avoid recursive errors
}
}
export const logger = new Logger();
7. Cache Handler
typescript Copy code
// src/lib/server/cache-handler.ts
import { logger } from './logger';
interface CacheEntry<T> {
data: T;
timestamp: number;
ttl: number;
}
class FetchCache {
private cache = new Map<string, CacheEntry<any>>();
private timers = new Map<string, NodeJS.Timeout>();
/**
* Get cached response
*/
get<T>(key: string): T | null {
const entry = this.cache.get(key);
if (!entry) {
return null;
}
if (this.isExpired(entry)) {
this.delete(key);
return null;
}
logger.debug('Cache hit', { key });
return entry.data as T;
}
/**
* Set cached response
*/
set<T>(key: string, data: T, ttlSeconds: number = 300): void {
// Clear existing timer
if (this.timers.has(key)) {
clearTimeout(this.timers.get(key)!);
}
const entry: CacheEntry<T> = {
data,
timestamp: Date.now(),
ttl: ttlSeconds * 1000
};
this.cache.set(key, entry);
// Set auto-expire timer
const timer = setTimeout(() => {
this.delete(key);
logger.debug('Cache expired', { key });
}, entry.ttl);
this.timers.set(key, timer);
logger.debug('Cache set', { key, ttlSeconds });
}
/**
* Check if cache entry is expired
*/
private isExpired(entry: CacheEntry<any>): boolean {
return Date.now() - entry.timestamp > entry.ttl;
}
/**
* Delete cache entry
*/
delete(key: string): void {
this.cache.delete(key);
if (this.timers.has(key)) {
clearTimeout(this.timers.get(key)!);
this.timers.delete(key);
}
}
/**
* Clear all cache
*/
clear(): void {
this.timers.forEach(timer => clearTimeout(timer));
this.cache.clear();
this.timers.clear();
}
/**
* Get cache statistics
*/
getStats() {
return {
size: this.cache.size,
keys: Array.from(this.cache.keys())
};
}
}
export const fetchCache = new FetchCache();
/**
* Decorator to cache fetch results
*/
export function cacheable(ttlSeconds: number = 300) {
return function (
target: any,
propertyKey: string,
descriptor: PropertyDescriptor
) {
const originalMethod = descriptor.value;
descriptor.value = async function (...args: any[]) {
const cacheKey = `${propertyKey}:${JSON.stringify(args)}`;
// Check cache
const cached = fetchCache.get(cacheKey);
if (cached) return cached;
// Execute method
const result = await originalMethod.apply(this, args);
// Cache result
fetchCache.set(cacheKey, result, ttlSeconds);
return result;
};
return descriptor;
};
}
8. Service Fetcher Utility
9. Route Usage Examples
typescript Copy code
// src/routes/api/users/+server.ts
import type { RequestHandler } from '@sveltejs/kit';
import { userService } from '$lib/server/service-fetcher';
import { logger } from '$lib/server/logger';
export const GET: RequestHandler = async ({ url }) => {
try {
const userId = url.searchParams.get('id');
if (!userId) {
return new Response(JSON.stringify({ error: 'Missing user ID' }), {
status: 400
});
}
// Fetch from internal service with caching (5 minutes)
const user = await userService.fetch(
`/users/${userId}`,
{ cache: 300 }
);
return new Response(JSON.stringify(user), {
headers: { 'Content-Type': 'application/json' }
});
} catch (error) {
logger.error('Failed to fetch user', { error });
return new Response(JSON.stringify({ error: 'Internal server error' }), {
status: 500
});
}
};
export const POST: RequestHandler = async ({ request }) => {
try {
const userData = await request.json();
const createdUser = await userService.fetch(
'/users',
{
method: 'POST',
body: userData
}
);
return new Response(JSON.stringify(createdUser), {
status: 201,
headers: { 'Content-Type': 'application/json' }
});
} catch (error) {
logger.error('Failed to create user', { error });
return new Response(JSON.stringify({ error: 'Internal server error' }), {
status: 500
});
}
};
10. Load Function with Data Fetching
typescript Copy code
// src/routes/+page.server.ts
import type { PageServerLoad } from './$types';
import { userService, dataService } from '$lib/server/service-fetcher';
import { logger } from '$lib/server/logger';
interface PageData {
users: any[];
stats: any;
error?: string;
}
export const load: PageServerLoad<PageData> = async ({ depends }) => {
depends('data:users');
try {
// Parallel requests with caching
const [users, stats] = await Promise.all([
userService.fetch('/users', { cache: 600 }),
dataService.fetch('/stats', { cache: 300 })
]);
logger.info('Page data loaded successfully', {
userCount: users.length
});
return {
users,
stats
};
} catch (error) {
logger.error('Failed to load page data', { error });
return {
users: [],
stats: {},
error: 'Failed to load data'
};
}
};
11. Environment Configuration
bash Copy code
# .env.local
INTERNAL_API_KEY=your-secret-api-key-here
INTERNAL_API_BASEURL=http://internal-api
AUTH_SERVICE_URL=http://localhost:3001
USER_SERVICE_URL=http://localhost:3002
DATA_SERVICE_URL=http://localhost:3003
# mTLS Configuration (optional)
MTLS_ENABLED=true
MTLS_CERT_PATH=/path/to/client.crt
MTLS_KEY_PATH=/path/to/client.key
MTLS_CA_PATH=/path/to/ca.crt
# Logging
LOG_ENDPOINT=http://localhost:9000/logs
# Environment
NODE_ENV=development
12. Advanced Usage with Error Recovery
typescript Copy code
// src/lib/server/resilient-fetcher.ts
import { userService } from './service-fetcher';
import { logger } from './logger';
interface CircuitBreakerState {
state: 'closed' | 'open' | 'half-open';
failures: number;
lastFailureTime: number;
successCount: number;
}
class ResilientServiceFetcher {
private circuitBreaker: CircuitBreakerState = {
state: 'closed',
failures: 0,
lastFailureTime: 0,
successCount: 0
};
private readonly failureThreshold = 5;
private readonly resetTimeout = 60000; // 1 minute
private readonly halfOpenTimeout = 30000; // 30 seconds
async fetch<T>(
service: any,
endpoint: string,
options?: any
): Promise<T> {
// Check circuit breaker
if (this.circuitBreaker.state === 'open') {
if (Date.now() - this.circuitBreaker.lastFailureTime > this.resetTimeout) {
logger.info('Circuit breaker: transitioning to half-open');
this.circuitBreaker.state = 'half-open';
this.circuitBreaker.successCount = 0;
} else {
throw new Error('Service temporarily unavailable (circuit open)');
}
}
try {
const result = await service.fetch<T>(endpoint, options);
// Update circuit breaker on success
if (this.circuitBreaker.state === 'half-open') {
this.circuitBreaker.successCount++;
if (this.circuitBreaker.successCount >= 2) {
logger.info('Circuit breaker: transitioning to closed');
this.circuitBreaker.state = 'closed';
this.circuitBreaker.failures = 0;
}
} else {
this.circuitBreaker.failures = 0;
}
return result;
} catch (error) {
this.circuitBreaker.failures++;
this.circuitBreaker.lastFailureTime = Date.now();
if (this.circuitBreaker.failures >= this.failureThreshold) {
logger.warn('Circuit breaker: opening due to repeated failures');
this.circuitBreaker.state = 'open';
}
throw error;
}
}
getCircuitBreakerStatus() {
return {
...this.circuitBreaker,
hasFailures: this.circuitBreaker.failures > 0
};
}
}
export const resilientFetcher = new ResilientServiceFetcher();
13. Testing
typescript Copy code
// src/lib/server/__tests__/fetch-handler.test.ts
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { createAdvancedFetchHandler } from '../advanced-fetch-handler';
import type { RequestEvent } from '@sveltejs/kit';
describe('Advanced Fetch Handler', () => {
let mockEvent: Partial<RequestEvent>;
let mockResolve: any;
beforeEach(() => {
mockResolve = vi.fn(async () => new Response('OK'));
mockEvent = {
request: new Request('http://example.com'),
locals: {}
} as Partial<RequestEvent>;
});
afterEach(() => {
vi.clearAllMocks();
});
it('should inject authentication headers for internal services', async () => {
const handler = createAdvancedFetchHandler();
global.fetch = vi.fn();
await handler({
event: mockEvent as RequestEvent,
resolve: mockResolve
});
// Verify fetch was called with auth headers
expect(global.fetch).toHaveBeenCalled();
});
it('should handle service URL resolution', () => {
// Test service URL mapping
expect(true).toBe(true);
});
it('should retry on failure', async () => {
const handler = createAdvancedFetchHandler();
let attemptCount = 0;
global.fetch = vi.fn(() => {
attemptCount++;
if (attemptCount < 3) {
return Promise.reject(new Error('Network error'));
}
return Promise.resolve(new Response('OK'));
});
await handler({
event: mockEvent as RequestEvent,
resolve: mockResolve
});
expect(attemptCount).toBeGreaterThanOrEqual(1);
});
});
14. Monitoring & Observability
typescript Copy code
// src/lib/server/observability.ts
import { logger } from './logger';
export class FetchObservability {
private metrics = {
totalRequests: 0,
successfulRequests: 0,
failedRequests: 0,
totalDuration: 0,
avgDuration: 0
};
recordRequest(
success: boolean,
duration: number,
url: string
): void {
this.metrics.totalRequests++;
this.metrics.totalDuration += duration;
if (success) {
this.metrics.successfulRequests++;
} else {
this.metrics.failedRequests++;
}
this.metrics.avgDuration =
this.metrics.totalDuration / this.metrics.totalRequests;
if (this.metrics.totalRequests % 100 === 0) {
this.logMetrics();
}
}
private logMetrics(): void {
logger.info('Fetch metrics', this.metrics);
}
getMetrics() {
return { ...this.metrics };
}
reset(): void {
this.metrics = {
totalRequests: 0,
successfulRequests: 0,
failedRequests: 0,
totalDuration: 0,
avgDuration: 0
};
}
}
export const observability = new FetchObservability();
Key Features:
✅ Automatic API Key Injection - All internal requests auto-authenticated
✅ mTLS Support - Optional mutual TLS for secure microservice communication
✅ Retry Logic - Exponential backoff with configurable attempts
✅ Request Caching - Reduce downstream service load
✅ Service Discovery - URL mapping and resolution
✅ Circuit Breaker - Protect against cascading failures
✅ Request Tracing - Unique IDs for tracking across services
✅ Comprehensive Logging - Debug and monitor all fetches
✅ Type Safety - Full TypeScript support
✅ Production Ready - Error handling and timeout protection
This implementation provides enterprise-grade server-side data fetching with automatic authentication injection!