Client-side only middleware in SvelteKit

You can easily add client-only middleware to your SvelteKit project by modifying the file you export your load function from.

I'm building a SPA with SvelteKit and came across a need to add some middleware (for authentication purposes) to the app.

Now, in SvelteKit, we have this concept of a load function, which basically acts like Next's getServerSideProps, except that in SvelteKit it can run both on the server and the client.

We also have server routes and logic in SvelteKit if we append `server` to our routes such as `+page.server.ts`. This allows any logic to run purely on the server.

However, we don't have this same syntax for client-side only logic, which brings me back to my original problem.

It turns out, you can make load run on the client-side and act as a piece of middleware if you also export const ssr = false from the same file.

Something like this:

export function load(){
	// Some client-friendly business logic.

export const ssr = false;

In this context, export const ssr = false means that the corresponding route/page will not be rendered on the server first and then later hydrated when it is loaded. Instead, the entire page will be client-side rendered at run time.

If you're building a SPA, this is perfect, but in some other contexts this may not be ideal!

Nonetheless, this is how you can add client-side middleware to your SvelteKit project.