mirror of
https://github.com/supabase/supabase.git
synced 2026-10-16 06:39:09 +03:00
Partials are currently defined via MDX includes. This PR switches to pre-compile-time partials, which have a new syntax: ``` <$Partial path="path/to/file.mdx" /> ``` ## Rationale This produces two improvements: 1. Partial substitution can occur in pipelines that don't use MDX compilation. For example, we can now do partial substitution before building the search index, so partial content will also be indexed. 2. After the App Router migration, the MDXProviders should've been deprecated, but were kept around for the sole reason of making partials work, and leading to us shipping unnecessary client-side code. We get a minor decrease in overall client bundle size (5.74 MB to 5.6 MB) by getting rid of the Providers. ## Breaking changes Besides the change to partial syntax, the arguments are also less powerful than before because we are doing string substitution and don't have the full power of JS. Defining string variables is still possible (documented in the Contributing guide), and since that's all we actually do in practice, this shouldn't be too cumbersome. There is always the escape hatch of making a custom component for more complex content reuse cases.
375 lines
9.7 KiB
Plaintext
375 lines
9.7 KiB
Plaintext
---
|
|
title: 'Build a User Management App with Svelte'
|
|
description: 'Learn how to use Supabase in your Svelte App.'
|
|
---
|
|
|
|
<$Partial path="quickstart_intro.mdx" />
|
|
|
|

|
|
|
|
<Admonition type="note">
|
|
|
|
If you get stuck while working through this guide, refer to the [full example on GitHub](https://github.com/supabase/supabase/tree/master/examples/user-management/svelte-user-management).
|
|
|
|
</Admonition>
|
|
|
|
<$Partial path="project_setup.mdx" />
|
|
|
|
## Building the app
|
|
|
|
Let's start building the Svelte app from scratch.
|
|
|
|
### Initialize a Svelte app
|
|
|
|
We can use the Vite Svelte TypeScript Template to initialize an app called `supabase-svelte`:
|
|
|
|
```bash
|
|
npm create vite@latest supabase-svelte -- --template svelte-ts
|
|
cd supabase-svelte
|
|
npm install
|
|
```
|
|
|
|
Then let's install the only additional dependency: [supabase-js](https://github.com/supabase/supabase-js)
|
|
|
|
```bash
|
|
npm install @supabase/supabase-js
|
|
```
|
|
|
|
And finally we want to save the environment variables in a `.env`.
|
|
All we need are the API URL and the `anon` key that you copied [earlier](#get-the-api-keys).
|
|
|
|
```bash .env
|
|
VITE_SUPABASE_URL=YOUR_SUPABASE_URL
|
|
VITE_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY
|
|
```
|
|
|
|
Now that we have the API credentials in place, let's create a helper file to initialize the Supabase client. These variables will be exposed
|
|
on the browser, and that's completely fine since we have [Row Level Security](/docs/guides/auth#row-level-security) enabled on our Database.
|
|
|
|
```js src/supabaseClient.ts
|
|
import { createClient } from '@supabase/supabase-js'
|
|
|
|
const supabaseUrl = import.meta.env.VITE_SUPABASE_URL
|
|
const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY
|
|
|
|
export const supabase = createClient(supabaseUrl, supabaseAnonKey)
|
|
```
|
|
|
|
### App styling (optional)
|
|
|
|
An optional step is to update the CSS file `src/app.css` to make the app look nice.
|
|
You can find the full contents of this file [here](https://raw.githubusercontent.com/supabase/supabase/master/examples/user-management/svelte-user-management/src/app.css).
|
|
|
|
### Set up a login component
|
|
|
|
Let's set up a Svelte component to manage logins and sign ups. We'll use Magic Links, so users can sign in with their email without using passwords.
|
|
|
|
```html src/lib/Auth.svelte
|
|
<script lang="ts">
|
|
import { supabase } from '../supabaseClient'
|
|
|
|
let loading = false
|
|
let email = ''
|
|
|
|
const handleLogin = async () => {
|
|
try {
|
|
loading = true
|
|
const { error } = await supabase.auth.signInWithOtp({ email })
|
|
if (error) throw error
|
|
alert('Check your email for login link!')
|
|
} catch (error) {
|
|
if (error instanceof Error) {
|
|
alert(error.message)
|
|
}
|
|
} finally {
|
|
loading = false
|
|
}
|
|
}
|
|
</script>
|
|
|
|
<div class="row flex-center flex">
|
|
<div class="col-6 form-widget" aria-live="polite">
|
|
<h1 class="header">Supabase + Svelte</h1>
|
|
<p class="description">Sign in via magic link with your email below</p>
|
|
<form class="form-widget" on:submit|preventDefault="{handleLogin}">
|
|
<div>
|
|
<label for="email">Email</label>
|
|
<input
|
|
id="email"
|
|
class="inputField"
|
|
type="email"
|
|
placeholder="Your email"
|
|
bind:value="{email}"
|
|
/>
|
|
</div>
|
|
<div>
|
|
<button type="submit" class="button block" aria-live="polite" disabled="{loading}">
|
|
<span>{loading ? 'Loading' : 'Send magic link'}</span>
|
|
</button>
|
|
</div>
|
|
</form>
|
|
</div>
|
|
</div>
|
|
```
|
|
|
|
### Account page
|
|
|
|
After a user is signed in we can allow them to edit their profile details and manage their account.
|
|
Let's create a new component for that called `Account.svelte`.
|
|
|
|
```tsx src/lib/Account.svelte
|
|
<script lang="ts">
|
|
import { onMount } from 'svelte'
|
|
import type { AuthSession } from '@supabase/supabase-js'
|
|
import { supabase } from '../supabaseClient'
|
|
|
|
export let session: AuthSession
|
|
|
|
let loading = false
|
|
let username: string | null = null
|
|
let website: string | null = null
|
|
let avatarUrl: string | null = null
|
|
|
|
onMount(() => {
|
|
getProfile()
|
|
})
|
|
|
|
const getProfile = async () => {
|
|
try {
|
|
loading = true
|
|
const { user } = session
|
|
|
|
const { data, error, status } = await supabase
|
|
.from('profiles')
|
|
.select('username, website, avatar_url')
|
|
.eq('id', user.id)
|
|
.single()
|
|
|
|
if (error && status !== 406) throw error
|
|
|
|
if (data) {
|
|
username = data.username
|
|
website = data.website
|
|
avatarUrl = data.avatar_url
|
|
}
|
|
} catch (error) {
|
|
if (error instanceof Error) {
|
|
alert(error.message)
|
|
}
|
|
} finally {
|
|
loading = false
|
|
}
|
|
}
|
|
|
|
const updateProfile = async () => {
|
|
try {
|
|
loading = true
|
|
const { user } = session
|
|
|
|
const updates = {
|
|
id: user.id,
|
|
username,
|
|
website,
|
|
avatar_url: avatarUrl,
|
|
updated_at: new Date().toISOString(),
|
|
}
|
|
|
|
const { error } = await supabase.from('profiles').upsert(updates)
|
|
|
|
if (error) {
|
|
throw error
|
|
}
|
|
} catch (error) {
|
|
if (error instanceof Error) {
|
|
alert(error.message)
|
|
}
|
|
} finally {
|
|
loading = false
|
|
}
|
|
}
|
|
</script>
|
|
|
|
<form on:submit|preventDefault="{updateProfile}" class="form-widget">
|
|
<div>Email: {session.user.email}</div>
|
|
<div>
|
|
<label for="username">Name</label>
|
|
<input id="username" type="text" bind:value="{username}" />
|
|
</div>
|
|
<div>
|
|
<label for="website">Website</label>
|
|
<input id="website" type="text" bind:value="{website}" />
|
|
</div>
|
|
<div>
|
|
<button type="submit" class="button primary block" disabled="{loading}">
|
|
{loading ? 'Saving ...' : 'Update profile'}
|
|
</button>
|
|
</div>
|
|
<button type="button" class="button block" on:click={() => supabase.auth.signOut()}> Sign Out
|
|
</button>
|
|
</form>
|
|
```
|
|
|
|
### Launch!
|
|
|
|
Now that we have all the components in place, let's update `App.svelte`:
|
|
|
|
```html src/App.svelte
|
|
<script lang="ts">
|
|
import { onMount } from 'svelte'
|
|
import { supabase } from './supabaseClient'
|
|
import type { AuthSession } from '@supabase/supabase-js'
|
|
import Account from './lib/Account.svelte'
|
|
import Auth from './lib/Auth.svelte'
|
|
|
|
let session: AuthSession | null
|
|
|
|
onMount(() => {
|
|
supabase.auth.getSession().then(({ data }) => {
|
|
session = data.session
|
|
})
|
|
|
|
supabase.auth.onAuthStateChange((_event, _session) => {
|
|
session = _session
|
|
})
|
|
})
|
|
</script>
|
|
|
|
<div class="container" style="padding: 50px 0 100px 0">
|
|
{#if !session}
|
|
<Auth />
|
|
{:else}
|
|
<Account {session} />
|
|
{/if}
|
|
</div>
|
|
```
|
|
|
|
Once that's done, run this in a terminal window:
|
|
|
|
```bash
|
|
npm run dev
|
|
```
|
|
|
|
And then open the browser to [localhost:5173](http://localhost:5173) and you should see the completed app.
|
|
|
|
<Admonition type="tip">
|
|
|
|
Svelte uses Vite and the default port is `5173`, Supabase uses `port 3000`. To change the redirection port for Supabase go to: `Authentication > Settings` and change the `Site Url` to `http://localhost:5173/`
|
|
|
|
</Admonition>
|
|
|
|

|
|
|
|
## Bonus: Profile photos
|
|
|
|
Every Supabase project is configured with [Storage](/docs/guides/storage) for managing large files like photos and videos.
|
|
|
|
### Create an upload widget
|
|
|
|
Let's create an avatar for the user so that they can upload a profile photo. We can start by creating a new component:
|
|
|
|
```html src/lib/Avatar.svelte
|
|
<script lang="ts">
|
|
import { createEventDispatcher } from 'svelte'
|
|
import { supabase } from '../supabaseClient'
|
|
|
|
export let size: number
|
|
export let url: string | null = null
|
|
|
|
let avatarUrl: string | null = null
|
|
let uploading = false
|
|
let files: FileList
|
|
|
|
const dispatch = createEventDispatcher()
|
|
|
|
const downloadImage = async (path: string) => {
|
|
try {
|
|
const { data, error } = await supabase.storage.from('avatars').download(path)
|
|
|
|
if (error) {
|
|
throw error
|
|
}
|
|
|
|
const url = URL.createObjectURL(data)
|
|
avatarUrl = url
|
|
} catch (error) {
|
|
if (error instanceof Error) {
|
|
console.log('Error downloading image: ', error.message)
|
|
}
|
|
}
|
|
}
|
|
|
|
const uploadAvatar = async () => {
|
|
try {
|
|
uploading = true
|
|
|
|
if (!files || files.length === 0) {
|
|
throw new Error('You must select an image to upload.')
|
|
}
|
|
|
|
const file = files[0]
|
|
const fileExt = file.name.split('.').pop()
|
|
const filePath = `${Math.random()}.${fileExt}`
|
|
|
|
const { error } = await supabase.storage.from('avatars').upload(filePath, file)
|
|
|
|
if (error) {
|
|
throw error
|
|
}
|
|
|
|
url = filePath
|
|
dispatch('upload')
|
|
} catch (error) {
|
|
if (error instanceof Error) {
|
|
alert(error.message)
|
|
}
|
|
} finally {
|
|
uploading = false
|
|
}
|
|
}
|
|
|
|
$: if (url) downloadImage(url)
|
|
</script>
|
|
|
|
<div style="width: {size}px" aria-live="polite">
|
|
{#if avatarUrl} <img src={avatarUrl} alt={avatarUrl ? 'Avatar' : 'No image'} class="avatar image"
|
|
style="height: {size}px, width: {size}px" /> {:else}
|
|
<div class="avatar no-image" style="height: {size}px, width: {size}px" />
|
|
{/if}
|
|
<div style="width: {size}px">
|
|
<label class="button primary block" for="single">
|
|
{uploading ? 'Uploading ...' : 'Upload avatar'}
|
|
</label>
|
|
<span style="display:none">
|
|
<input
|
|
type="file"
|
|
id="single"
|
|
accept="image/*"
|
|
bind:files
|
|
on:change={uploadAvatar}
|
|
disabled={uploading}
|
|
/>
|
|
</span>
|
|
</div>
|
|
</div>
|
|
```
|
|
|
|
### Add the new widget
|
|
|
|
And then we can add the widget to the Account page:
|
|
|
|
```html src/lib/Account.svelte
|
|
<script lang="ts">
|
|
// Import the new component
|
|
import Avatar from './Avatar.svelte'
|
|
</script>
|
|
|
|
<form on:submit|preventDefault="{updateProfile}" class="form-widget">
|
|
<!-- Add to body -->
|
|
<Avatar bind:url="{avatarUrl}" size="{150}" on:upload="{updateProfile}" />
|
|
|
|
<!-- Other form elements -->
|
|
</form>
|
|
```
|
|
|
|
At this stage you have a fully functional application!
|