# Svelte Kit

## Introduction

* SvelteKit is a framework for rapidly developing robust, performant web applications using [Svelte](https://svelte.dev/). If you're coming from React, SvelteKit is similar to Next.

## Data Pre-rendering

* SvelteKit allows server-side rendering, but also can be disabled to let application be single app application (spa)

<pre class="language-typescript" data-title="+page.ts"><code class="lang-typescript">import { error } from '@sveltejs/kit';
import type { PageLoad } from './$types';

/** @type {import('./$types').PageLoad} */
export const load:PageLoad = ({ params }) => {
	if (params.slug === 'hello-world') {
		return {
			title: 'Hello world!',
			content: 'Welcome to our blog. Lorem ipsum dolor sit amet...'
		};
	}

	throw error(404, 'Not found');
}

// Disable SSR
<strong>// export const csr = true;
</strong>// export const ssr = false;
</code></pre>

{% code title="+page.svelte" %}
```html
<script>
    export let data: ApiKeysPage;
</script>
<div>
    {data.title}
</div>
```
{% endcode %}

## API

* The page can act as an api

{% code title="login/+page.server.js" %}
```javascript
/** @type {import('./$types').Actions} */
export const actions = {
	login: async (event) => {
		// TODO log the user in
	},
	register: async (event) => {
		// TODO register the user
	}
};
```
{% endcode %}

{% code title="login/+page.svelte" %}
```html
<form method="POST" action="?/register">
```
{% endcode %}

## Hook

* 'Hooks' are app-wide functions you declare that SvelteKit will call in response to specific events, giving you fine-grained control over the framework's behaviour
* Every time the SvelteKit server receives a [request](https://kit.svelte.dev/docs/web-standards#fetch-apis-request) — whether that happens while the app is running, or during [prerendering](https://kit.svelte.dev/docs/page-options#prerender) — and determines the [response](https://kit.svelte.dev/docs/web-standards#fetch-apis-response). It receives an `event` object representing the request and a function called `resolve`, which renders the route and generates a `Response`. This allows you to modify response headers or bodies, or bypass SvelteKit entirely

```javascript
/** @type {import('@sveltejs/kit').Handle} */
export async function handle({ event, resolve }) {
	if (event.url.pathname.startsWith('/custom')) {
		return new Response('custom response');
	}

	const response = await resolve(event);
	return response;
}
```

* Allows you to modify (or replace) a `fetch` request that happens inside a `load` or `action` function that runs on the server

```javascript
/** @type {import('@sveltejs/kit').HandleFetch} */
export async function handleFetch({ request, fetch }) {
	if (request.url.startsWith('https://api.yourapp.com/')) {
		// clone the original request, but change the URL
		request = new Request(
			request.url.replace('https://api.yourapp.com/', 'http://localhost:9999/'),
			request
		);
	}

	return fetch(request);
}
```

&#x20;
