All posts

SvelteKit Logging: Server Hooks and Client Errors

SvelteKit logging guide: structured server logs in hooks.server.ts, request IDs and timing, client error capture in hooks.client.ts, with code.

SvelteKit Logging Best Practices

SvelteKit runs on both server and client. Your logging strategy needs to cover both.

Server-Side Logging with Hooks

// src/hooks.server.ts
import type { Handle, HandleServerError } from '@sveltejs/kit';

export const handle: Handle = async ({ event, resolve }) => {
  const requestId = crypto.randomUUID();
  event.locals.requestId = requestId;
  const start = performance.now();

  const response = await resolve(event);
  const duration = performance.now() - start;

  console.log(JSON.stringify({
    type: 'request',
    requestId,
    method: event.request.method,
    path: event.url.pathname,
    status: response.status,
    duration_ms: Math.round(duration),
  }));

  return response;
};

export const handleError: HandleServerError = ({ error, event }) => {
  console.error(JSON.stringify({
    type: 'error',
    requestId: event.locals.requestId,
    message: error instanceof Error ? error.message : 'Unknown error',
    stack: error instanceof Error ? error.stack : undefined,
    path: event.url.pathname,
  }));

  return {
    message: 'Internal server error',
  };
};

Client-Side Error Logging

// src/hooks.client.ts
import type { HandleClientError } from '@sveltejs/kit';

export const handleError: HandleClientError = ({ error, message }) => {
  console.error('Client error:', error);

  // Send to logging endpoint
  fetch('/api/log', {
    method: 'POST',
    body: JSON.stringify({
      type: 'client_error',
      message: error instanceof Error ? error.message : message,
      stack: error instanceof Error ? error.stack : undefined,
      url: window.location.href,
      userAgent: navigator.userAgent,
    }),
    keepalive: true,
  }).catch(() => {}); // Don't let logging failures break the app

  return { message: 'Something went wrong' };
};

Structured Logging in Server Routes

// src/routes/api/orders/+server.ts
import type { RequestHandler } from './$types';

export const POST: RequestHandler = async ({ request, locals }) => {
  const logger = createLogger(locals.requestId);

  logger.info('Creating order', { userId: locals.user.id });

  try {
    const order = await createOrder(await request.json());
    logger.info('Order created', { orderId: order.id });
    return json(order, { status: 201 });
  } catch (error) {
    logger.error('Order creation failed', { error: error.message });
    throw error;
  }
};

What to Log

  • All requests — method, path, status, duration
  • Business events — order created, user signed up
  • Errors — with full context and request ID
  • External calls — API requests with latency

Send server and client errors to an error tracker

Console logs disappear when the process restarts. To keep errors, group them and get alerted, add an error tracker to the same two hooks. Bugsly accepts the Sentry protocol, so the official @sentry/sveltekit package works with a Bugsly DSN:

// src/hooks.server.ts
import * as Sentry from '@sentry/sveltekit';
import { sequence } from '@sveltejs/kit/hooks';

Sentry.init({ dsn: 'https://<public-key>@bugsly.dev/<project-id>' });

export const handle = sequence(Sentry.sentryHandle(), yourLoggingHandle);
export const handleError = Sentry.handleErrorWithSentry(yourHandleError);
// src/hooks.client.ts
import * as Sentry from '@sentry/sveltekit';

Sentry.init({ dsn: 'https://<public-key>@bugsly.dev/<project-id>' });

export const handleError = Sentry.handleErrorWithSentry();

Keep your own requestId logging as shown above, and use the same request ID as a tag so a log line and its tracked error can be matched. Create a free project at signup to get a DSN; see pricing for plan limits. For other stacks, see the integration guides.

Try Bugsly free, no card

Free plan, no card: 1 project, 100 new issues and 50,000 events a month, 7-day retention, 10 AI explanations a month. Paid plans from $19/month, 7-day money-back, cancel anytime.

Start free, no card

From the same team