SvelteKit

πŸ‘‹ FYI, this note is over 6 months old. Some of the content may be out of date.
On this page

Routing file structure for pages Jump to heading

β”œβ”€ src
β”‚ β”œβ”€ routes
β”‚ β”‚ β”œβ”€ pageName ## app.com/pageName
β”‚ β”‚ β”‚ β”œβ”€ +page.svelte
β”‚ β”‚ β”‚ β”œβ”€ +page.server.ts ## or
β”‚ β”‚ β”‚ β”œβ”€ +page.ts
β”‚ β”‚ β”œβ”€ entry
β”‚ β”‚ β”‚ β”œβ”€ [id] ## app.com/entry/123
β”‚ β”‚ β”‚ β”‚ β”œβ”€ +page.svelte
β”‚ β”‚ β”‚ β”‚ β”œβ”€ +page.server.ts ## or
β”‚ β”‚ β”‚ β”‚ β”œβ”€ +page.ts

Server side Jump to heading

This example +page.server.ts file uses supabase to insert a new entry into a table and then redirects to the new entry’s page.

import { parseForm } from '@formdata-helper/base'
import type { PageServerLoad } from './$types'
import { redirect } from '@sveltejs/kit'

export const load: PageServerLoad = async ({
locals: { supabase },
parent,
}) => {
const { session } = await parent()
if (!session) {
throw redirect(303, '/')
}

const { data: journals } = await supabase
.from('journals')
.select('*')
.match({ status: 'active' })

return {
journals,
}
}

export const actions = {
default: async ({ request, locals: { supabase, getSession } }) => {
const session = await getSession()
const formData = await request.formData()
const formDataObject = parseForm(formData)

const { data: newEntry, error } = await supabase
.from('journal_entries')
.insert([{ ...formDataObject, owner: session?.user.id }])
.select()

if (error) {
console.error(`πŸš€ ~ default: ~ error`, error)
throw error
}
if (newEntry?.length) {
throw redirect(303, `/entry/${newEntry[0].id}`)
}
},
}

How To Add A Client Side Only Library To SvelteKit Jump to heading

<script>
import { onMount } from 'svelte';
import { browser } from '$app/env';

onMount(() => {
document.getElementByClass("test");
})

// or...

if (browser) {
document.getElementByClass("test");
}
</script>

Importing a client-side library Jump to heading

Sometimes, you might have a problem importing a library because some of its dependenices expect the DOM to be avaible. In that case, you can import it like so;

<script>
import { onMount } from 'svelte';

onMount(async () => {
const module = await import('some-lib');
const SomeLib = module.default;

// use module here...
});
</script>

← Back home