Skip to content
Getting Started

用 Svelte 构建一个用户管理应用

本教程演示了如何构建一个基本的用户管理应用。该应用可以进行用户认证和识别,将用户的个人资料信息存储在数据库中,并允许用户登录、更新他们的个人资料信息以及上传头像。该应用使用了:

🌐 This tutorial demonstrates how to build a basic user management app. The app authenticates and identifies the user, stores their profile information in the database, and allows the user to log in, update their profile details, and upload a profile photo. The app uses:

Supabase User Management example

项目设置 #

🌐 Project setup

在你开始构建之前,你需要先设置数据库和 API。你可以通过在 Supabase 中启动一个新项目,然后在数据库中创建一个“架构”来完成这一步。

🌐 Before you start building you need to set up the Database and API. You can do this by starting a new Project in Supabase and then creating a "schema" inside the database.

创建一个项目 #

🌐 Create a project

  1. 在 Supabase 仪表板中创建一个新项目
  2. 输入你的项目详情。
  3. 等新数据库上线。

设置数据库模式 #

🌐 Set up the database schema

现在设置数据库模式。你可以在 SQL 编辑器中使用“用户管理入门”快速开始,也可以复制粘贴下面的 SQL 并运行。

🌐 Now set up the database schema. You can use the "User Management Starter" quickstart in the SQL Editor, or you can copy/paste the SQL from below and run it.

  1. 在仪表板中转到SQL 编辑器页面。
  2. 点击 社区 > 快速入门 标签下的 用户管理入门
  3. 点击运行

获取 API 详情 #

🌐 Get API details

要与数据库表中的数据进行交互,你可以使用封装了自动生成的数据 API 端点的客户端库,并使用来自项目 Connect 对话框的项目 URL 和密钥进行认证。

🌐 To interact with data in database tables, you use the client libraries that wrap the auto-generated Data API endpoints, authenticating using the Project URL and key from the project Connect dialog.

Project URL
Publishable key

正在构建应用 #

🌐 Building the app

从零开始构建 Svelte 应用。

🌐 Start building the Svelte app from scratch.

初始化一个 Svelte 应用 #

🌐 Initialize a Svelte app

你可以使用 Vite Svelte TypeScript 模板来初始化一个名为 supabase-svelte 的应用:

🌐 You can use the Vite Svelte TypeScript Template to initialize an app called supabase-svelte:

1
npm create vite@latest supabase-svelte -- --template svelte-ts
2
cd supabase-svelte
3
npm install

安装唯一的额外依赖: supabase-js

🌐 Install the only additional dependency: supabase-js

1
npm install @supabase/supabase-js

最后,将环境变量保存在 .env 中。你只需要之前复制的 API URL 和密钥 链接 就可以了。

🌐 Finally, save the environment variables in a .env. All you need are the API URL and the key that you copied earlier.

1
VITE_SUPABASE_URL=YOUR_SUPABASE_URL
2
VITE_SUPABASE_PUBLISHABLE_KEY=YOUR_SUPABASE_PUBLISHABLE_KEY

现在你已经有了 API 凭证,创建一个辅助文件来初始化 Supabase 客户端。这些变量会在浏览器上暴露出来,这没问题,因为你在数据库上启用了 行级别安全

🌐 Now you have the API credentials in place, create a helper file to initialize the Supabase client. These variables will be exposed on the browser, and that's fine since you have Row Level Security enabled on the Database.

src/supabaseClient.ts
1
import { createClient } from '@supabase/supabase-js'
2
3
const supabaseUrl = import.meta.env.VITE_SUPABASE_URL
4
const supabasePublishableKey = import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY
5
6
export const supabase = createClient(supabaseUrl, supabasePublishableKey)
View source

应用风格(可选) #

🌐 App styling (optional)

可选择更新 CSS 文件 src/app.css 来让应用看起来更好。你可以在 示例仓库 中找到这个文件的完整内容。

🌐 Optionally, update the CSS file src/app.css to make the app look better. You can find the full contents of this file in the example repository.

设置一个登录组件 #

🌐 Set up a login component

设置一个 Svelte 组件来管理登录和注册。它使用 Magic Links,所以用户可以用邮箱登录而不用密码。

🌐 Set up a Svelte component to manage logins and sign ups. It uses Magic Links, so users can sign in with their email without using passwords.

src/lib/Auth.svelte
1
<script lang="ts">
2
import { supabase } from "../supabaseClient";
3
4
let loading = $state(false);
5
let email = $state("");
6
7
const handleLogin = async () => {
8
try {
9
loading = true;
10
const { error } = await supabase.auth.signInWithOtp({ email });
11
if (error) throw error;
12
alert("Check your email for login link!");
13
} catch (error) {
14
if (error instanceof Error) {
15
alert(error.message);
16
}
17
} finally {
18
loading = false;
19
}
20
};
21
</script>
22
23
<div class="row flex-center flex">
24
<div class="col-6 form-widget" aria-live="polite">
25
<h1 class="header">Supabase + Svelte</h1>
26
<p class="description">Sign in via magic link with your email below</p>
27
<form class="form-widget" onsubmit={(e) => { e.preventDefault(); handleLogin(); }}>
28
<div>
29
<label for="email">Email</label>
30
<input
31
id="email"
32
class="inputField"
33
type="email"
34
placeholder="Your email"
35
bind:value={email}
36
/>
37
</div>
38
<div>
39
<button
40
type="submit"
41
class="button block"
42
aria-live="polite"
43
disabled={loading}
44
>
45
<span>{loading ? "Loading" : "Send magic link"}</span>
46
</button>
47
</div>
48
</form>
49
</div>
50
</div>
View source

账户页面 #

🌐 Account page

用户登录后,允许他们编辑个人资料信息并管理账户。为此创建一个新组件,名为 Account.svelte

🌐 After a user is signed in, allow them to edit their profile details and manage their account. Create a new component for that called Account.svelte.

1
<script lang="ts">
2
import { onMount } from "svelte";
3
import type { AuthSession } from "@supabase/supabase-js";
4
import { supabase } from "../supabaseClient";
5
6
// ...
7
8
9
interface Props {
10
session: AuthSession;
11
}
12
13
let { session }: Props = $props();
14
15
let loading = $state(false);
16
let username = $state<string | null>(null);
17
let website = $state<string | null>(null);
18
let avatarUrl = $state<string | null>(null);
19
20
onMount(() => {
21
getProfile();
22
});
23
24
const getProfile = async () => {
25
try {
26
loading = true;
27
const { user } = session;
28
29
const { data, error, status } = await supabase
30
.from("profiles")
31
.select("username, website, avatar_url")
32
.eq("id", user.id)
33
.single();
34
35
if (error && status !== 406) throw error;
36
37
if (data) {
38
username = data.username;
39
website = data.website;
40
avatarUrl = data.avatar_url;
41
}
42
} catch (error) {
43
if (error instanceof Error) {
44
alert(error.message);
45
}
46
} finally {
47
loading = false;
48
}
49
};
50
51
const updateProfile = async () => {
52
try {
53
loading = true;
54
const { user } = session;
55
56
const updates = {
57
id: user.id,
58
username,
59
website,
60
avatar_url: avatarUrl,
61
updated_at: new Date().toISOString(),
62
};
63
64
const { error } = await supabase.from("profiles").upsert(updates);
65
66
if (error) {
67
throw error;
68
}
69
} catch (error) {
70
if (error instanceof Error) {
71
alert(error.message);
72
}
73
} finally {
74
loading = false;
75
}
76
};
77
</script>
78
79
<form onsubmit={(e) => { e.preventDefault(); updateProfile(); }} class="form-widget">
80
<div>Email: {session.user.email}</div>
81
<div>
82
83
// ...
84
85
<label for="username">Name</label>
86
<input id="username" type="text" bind:value={username} />
87
</div>
88
<div>
89
<label for="website">Website</label>
90
<input id="website" type="text" bind:value={website} />
91
</div>
92
<div>
93
<button type="submit" class="button primary block" disabled={loading}>
94
{loading ? "Saving ..." : "Update profile"}
95
</button>
96
</div>
97
<button
98
type="button"
99
class="button block"
100
onclick={() => supabase.auth.signOut()}
101
>
102
Sign Out
103
</button>
104
</form>
View source

头像照片 #

🌐 Profile photos

接下来,添加一个让用户上传个人资料照片的方式。Supabase 会为每个项目配置 Storage,用于管理像照片和视频这样的大文件。

🌐 Next, add a way for users to upload a profile photo. Supabase configures every project with Storage for managing large files like photos and videos.

创建一个上传小工具 #

🌐 Create an upload widget

先从创建一个新组件开始:

🌐 Start by creating a new component:

src/lib/Avatar.svelte
1
<script lang="ts">
2
import { supabase } from "../supabaseClient";
3
4
interface Props {
5
size: number;
6
url?: string | null;
7
onupload?: () => void;
8
}
9
10
let { size, url = $bindable(null), onupload }: Props = $props();
11
12
let avatarUrl = $state<string | null>(null);
13
let uploading = $state(false);
14
let files = $state<FileList>();
15
16
const downloadImage = async (path: string) => {
17
try {
18
const { data, error } = await supabase.storage
19
.from("avatars")
20
.download(path);
21
22
if (error) {
23
throw error;
24
}
25
26
const url = URL.createObjectURL(data);
27
avatarUrl = url;
28
} catch (error) {
29
if (error instanceof Error) {
30
console.log("Error downloading image: ", error.message);
31
}
32
}
33
};
34
35
const uploadAvatar = async () => {
36
try {
37
uploading = true;
38
39
if (!files || files.length === 0) {
40
throw new Error("You must select an image to upload.");
41
}
42
43
const file = files[0];
44
const fileExt = file.name.split(".").pop();
45
const filePath = `${Math.random()}.${fileExt}`;
46
47
const { error } = await supabase.storage
48
.from("avatars")
49
.upload(filePath, file);
50
51
if (error) {
52
throw error;
53
}
54
55
url = filePath;
56
onupload?.();
57
} catch (error) {
58
if (error instanceof Error) {
59
alert(error.message);
60
}
61
} finally {
62
uploading = false;
63
}
64
};
65
66
$effect(() => {
67
if (url) downloadImage(url);
68
});
69
</script>
70
71
<div style="width: {size}px" aria-live="polite">
72
{#if avatarUrl}
73
<img
74
src={avatarUrl}
75
alt={avatarUrl ? "Avatar" : "No image"}
76
class="avatar image"
77
style="height: {size}px, width: {size}px"
78
/>
79
{:else}
80
<div class="avatar no-image" style="height: {size}px, width: {size}px"></div>
81
{/if}
82
<div style="width: {size}px">
83
<label class="button primary block" for="single">
84
{uploading ? "Uploading ..." : "Upload avatar"}
85
</label>
86
<span style="display:none">
87
<input
88
type="file"
89
id="single"
90
accept="image/*"
91
bind:files
92
onchange={uploadAvatar}
93
disabled={uploading}
94
/>
95
</span>
96
</div>
97
</div>
View source

更新账户组件 #

🌐 Update the account component

创建了 Avatar 组件后,更新 src/lib/Account.svelte 来包含它:

🌐 With the Avatar component created, update src/lib/Account.svelte to include it:

src/lib/Account.svelte
1
<script lang="ts">
2
import { onMount } from "svelte";
3
import type { AuthSession } from "@supabase/supabase-js";
4
import { supabase } from "../supabaseClient";
5
import Avatar from "./Avatar.svelte";
6
7
interface Props {
8
session: AuthSession;
9
}
10
11
let { session }: Props = $props();
12
13
let loading = $state(false);
14
let username = $state<string | null>(null);
15
let website = $state<string | null>(null);
16
let avatarUrl = $state<string | null>(null);
17
18
onMount(() => {
19
getProfile();
20
});
21
22
const getProfile = async () => {
23
try {
24
loading = true;
25
const { user } = session;
26
27
const { data, error, status } = await supabase
28
.from("profiles")
29
.select("username, website, avatar_url")
30
.eq("id", user.id)
31
.single();
32
33
if (error && status !== 406) throw error;
34
35
if (data) {
36
username = data.username;
37
website = data.website;
38
avatarUrl = data.avatar_url;
39
}
40
} catch (error) {
41
if (error instanceof Error) {
42
alert(error.message);
43
}
44
} finally {
45
loading = false;
46
}
47
};
48
49
const updateProfile = async () => {
50
try {
51
loading = true;
52
const { user } = session;
53
54
const updates = {
55
id: user.id,
56
username,
57
website,
58
avatar_url: avatarUrl,
59
updated_at: new Date().toISOString(),
60
};
61
62
const { error } = await supabase.from("profiles").upsert(updates);
63
64
if (error) {
65
throw error;
66
}
67
} catch (error) {
68
if (error instanceof Error) {
69
alert(error.message);
70
}
71
} finally {
72
loading = false;
73
}
74
};
75
</script>
76
77
<form onsubmit={(e) => { e.preventDefault(); updateProfile(); }} class="form-widget">
78
<div>Email: {session.user.email}</div>
79
<div>
80
<Avatar bind:url={avatarUrl} size={150} onupload={updateProfile} />
81
<label for="username">Name</label>
82
<input id="username" type="text" bind:value={username} />
83
</div>
84
<div>
85
<label for="website">Website</label>
86
<input id="website" type="text" bind:value={website} />
87
</div>
88
<div>
89
<button type="submit" class="button primary block" disabled={loading}>
90
{loading ? "Saving ..." : "Update profile"}
91
</button>
92
</div>
93
<button
94
type="button"
95
class="button block"
96
onclick={() => supabase.auth.signOut()}
97
>
98
Sign Out
99
</button>
100
</form>
View source

触发! #

🌐 Launch!

在所有组件就位后,更新 App.svelte

🌐 With all the components in place, update App.svelte:

src/App.svelte
1
<script lang="ts">
2
import { onMount } from 'svelte'
3
import { supabase } from './supabaseClient'
4
import type { AuthSession } from '@supabase/supabase-js'
5
import Account from './lib/Account.svelte'
6
import Auth from './lib/Auth.svelte'
7
8
let session = $state<AuthSession | null>(null)
9
10
onMount(() => {
11
supabase.auth.getSession().then(({ data }) => {
12
session = data.session
13
})
14
15
supabase.auth.onAuthStateChange((_event, _session) => {
16
session = _session
17
})
18
})
19
</script>
20
21
<div class="container" style="padding: 50px 0 100px 0">
22
{#if !session}
23
<Auth />
24
{:else}
25
<Account {session} />
26
{/if}
27
</div>
View source

完成后,在终端窗口运行这个:

🌐 Once that's done, run this in a terminal window:

1
npm run dev

然后打开浏览器访问 localhost:5173,你应该能看到完成的应用。

🌐 And then open the browser to localhost:5173 and you should see the completed app.

Supabase Svelte

在这个阶段,你已经有了一个完全可用的应用!

🌐 At this stage you have a fully functional application!