500 Internal Error — error in load function
What causes this
Your SvelteKit load function threw an unhandled error. SvelteKit catches it and shows a generic 500 page. The actual error is in your terminal/server logs. Common causes:
- An API call failed and you didn’t handle the error response
- You’re accessing a property on
undefined(data hasn’t loaded yet) - A database query failed
- Environment variables are missing on the server
Fix 1: Add error handling to your load function
// src/routes/+page.server.ts
import { error } from '@sveltejs/kit';
export async function load({ fetch }) {
// ❌ No error handling — any failure crashes the page
const res = await fetch('/api/data');
const data = await res.json();
return { data };
// ✅ Handle errors properly
const res = await fetch('/api/data');
if (!res.ok) {
throw error(res.status, 'Failed to load data');
}
return { data: await res.json() };
}
Fix 2: Check your terminal for the real error
The browser shows a generic 500, but the actual error is in your terminal where npm run dev is running. Look for the stack trace — it tells you exactly which line failed.
# The terminal will show something like:
# TypeError: Cannot read properties of undefined (reading 'id')
# at load (src/routes/+page.server.ts:8:24)
Fix 3: Handle missing data
If your load function depends on URL params or external data:
export async function load({ params }) {
const post = await db.post.findUnique({
where: { slug: params.slug }
});
// ❌ post might be null
return { title: post.title };
// ✅ Handle the null case
if (!post) {
throw error(404, 'Post not found');
}
return { title: post.title };
}
Fix 4: Check environment variables
Server-side load functions can access env vars, but they might be missing:
import { env } from '$env/dynamic/private';
export async function load() {
// ❌ API_KEY might be undefined
const res = await fetch(env.API_URL, {
headers: { Authorization: `Bearer ${env.API_KEY}` }
});
// ✅ Check first
if (!env.API_URL || !env.API_KEY) {
throw error(500, 'Missing API configuration');
}
// ...
}
Fix 5: Add a proper error page
Create +error.svelte to show users a helpful error instead of the default:
<!-- src/routes/+error.svelte -->
<script>
import { page } from '$app/stores';
</script>
<h1>{$page.status}</h1>
<p>{$page.error?.message || 'Something went wrong'}</p>
<a href="/">Go home</a>
How to prevent it
- Always wrap external calls (fetch, database queries) in try/catch or check response status
- Use SvelteKit’s
error()helper to throw typed errors with proper status codes - Add
+error.sveltepages at the route level to handle errors gracefully - Check your terminal logs during development — the real error is always there