tezvyn:

What is the purpose of +page.server.js in SvelteKit?

AI-drafted, machine-checkedSource: svelte.devbeginner
What is the purpose of +page.server.js in SvelteKit?
WHAT IT TESTS

Server-only load boundaries in SvelteKit.

ANSWER OUTLINE

Exclusively server-side load feeding the data prop, used for secrets like DB queries and private env vars.

RED FLAG

Claiming it runs in the browser or equating it with +page.js.

WHAT THIS TESTS: Whether the candidate understands SvelteKit's file-based routing and the critical distinction between universal load functions and server-only load functions. The interviewer wants to know if you can place sensitive operations on the correct side of the network boundary and explain why +page.server.js exists as a separate concept from +page.js.

A GOOD ANSWER COVERS: Four things in order. First, the file is a sibling to +page.svelte and exports a load function that executes exclusively on the server during SSR or when an endpoint is hit directly. Second, the return value of that load function is serialized and provided to the page as the data prop. Third, it is the correct place for secrets like database queries, calls to internal microservices, or reading private environment variables through $env modules. Fourth, it contrasts with +page.js which runs universally on both server and browser and therefore cannot safely contain credentials or server-only modules.

COMMON WRONG ANSWERS: Saying +page.server.js runs in the browser during client-side navigation. Claiming it is just a naming preference with no behavioral difference from +page.js. Storing API keys or direct SQL in +page.js and assuming they stay hidden. Forgetting that the returned data is still sent to the client, so you must not return raw password hashes or internal tokens even from a server file.

LIKELY FOLLOW-UPS: How would you access cookies or request headers during a load? When would you use +page.js instead of +page.server.js? How does SvelteKit handle a load error thrown in a server file? What is the difference between a server load function and a form action? Can you stream promises from a server load?

ONE CONCRETE EXAMPLE: Imagine a dashboard at routes/admin/+page.server.js. The load function imports a database client, reads a private connection string from a server-only env module, queries the users table for admin metrics, and returns { metrics }. The +page.svelte component receives metrics through its data prop and renders charts. Because the database client and connection string never appear in +page.js, they are never shipped to the browser. If the user navigates client-side from another page, SvelteKit still calls the server load via a fetch to the page endpoint, keeping the secrets server-bound.

Source: svelte.dev docs on Loading data

Read the original → svelte.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.