Skip to content
Getting Started

用 Nuxt 3 构建一个用户管理应用

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

🌐 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

从零开始构建 Vue 3 应用。

🌐 Build the Vue 3 app from scratch.

初始化一个 Nuxt 3 应用 #

🌐 Initialize a Nuxt 3 app

我们可以使用nuxi init来创建一个叫做nuxt-user-management的应用:

🌐 We can use nuxi init to create an app called nuxt-user-management:

1
npx nuxi init nuxt-user-management
2
3
cd nuxt-user-management

然后安装唯一的额外依赖:Nuxt Supabase。我们只需要把 Nuxt Supabase 作为开发依赖导入。

🌐 Then install the only additional dependency: Nuxt Supabase. We only need to import Nuxt Supabase as a dev dependency.

1
npm install @nuxtjs/supabase --save-dev

最后,我们想把环境变量保存在一个 .env 中。我们只需要你之前复制的 API URL 和密钥

🌐 And finally we want to save the environment variables in a .env. All we need are the API URL and the key that you copied earlier.

1
SUPABASE_URL="YOUR_SUPABASE_URL"
2
SUPABASE_KEY="YOUR_SUPABASE_PUBLISHABLE_KEY"

这些变量会在浏览器上暴露,不过完全没问题,因为我们的数据库已经启用了行级安全Nuxt Supabase 的神奇之处在于,只需设置环境变量就可以开始使用 Supabase。 不需要初始化 Supabase,库会自动处理这些事情。

🌐 These variables will be exposed on the browser, and that's completely fine since we have Row Level Security enabled on our Database. Amazing thing about Nuxt Supabase is that setting environment variables is all we need to do in order to start using Supabase. No need to initialize Supabase. The library will take care of it automatically.

应用风格(可选) #

🌐 App styling (optional)

一个可选步骤是更新 CSS 文件 assets/main.css 来让应用看起来更好。你可以在示例仓库中找到这个文件的完整内容。

🌐 An optional step is to update the CSS file assets/main.css to make the app look better. You can find the full contents of this file in the example repository.

1
import { defineNuxtConfig } from 'nuxt'
2
3
// https://v3.nuxtjs.org/api/configuration/nuxt.config
4
export default defineNuxtConfig({
5
modules: ['@nuxtjs/supabase'],
6
css: ['@/assets/main.css'],
7
})

设置认证组件 #

🌐 Set up Auth component

设置一个 Vue 组件来管理登录和注册。我们将使用 Magic Links,这样用户可以用邮箱登录而不用密码。

🌐 Set up a Vue component to manage logins and sign ups. We'll use Magic Links, so users can sign in with their email without using passwords.

1
<script setup>
2
const supabase = useSupabaseClient()
3
4
const loading = ref(false)
5
const email = ref('')
6
7
const handleLogin = async () => {
8
try {
9
loading.value = true
10
const { error } = await supabase.auth.signInWithOtp({ email: email.value })
11
if (error) throw error
12
alert('Check your email for the login link!')
13
} catch (error) {
14
alert(error.error_description || error.message)
15
} finally {
16
loading.value = false
17
}
18
}
19
</script>
20
21
<template>
22
<form class="row flex-center flex" @submit.prevent="handleLogin">
23
<div class="col-6 form-widget">
24
<h1 class="header">Supabase + Nuxt 3</h1>
25
<p class="description">Sign in via magic link with your email below</p>
26
<div>
27
<input class="inputField" type="email" placeholder="Your email" v-model="email" />
28
</div>
29
<div>
30
<input
31
type="submit"
32
class="button block"
33
:value="loading ? 'Loading' : 'Send magic link'"
34
:disabled="loading"
35
/>
36
</div>
37
</div>
38
</form>
39
</template>

用户状态 #

🌐 User state

要访问用户信息,使用 Supabase Nuxt 模块提供的可组合函数 useSupabaseUser

🌐 To access the user information, use the composable useSupabaseUser provided by the Supabase Nuxt module.

账户组件 #

🌐 Account component

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

🌐 After a user is signed in we can allow them to edit their profile details and manage their account. Create a new component called Account.vue.

1
<script setup>
2
const supabase = useSupabaseClient()
3
4
const loading = ref(true)
5
const username = ref('')
6
const website = ref('')
7
const avatar_path = ref('')
8
9
loading.value = true
10
const user = useSupabaseUser()
11
12
const { data } = await supabase
13
.from('profiles')
14
.select(`username, website, avatar_url`)
15
.eq('id', user.value.id)
16
.single()
17
18
if (data) {
19
username.value = data.username
20
website.value = data.website
21
avatar_path.value = data.avatar_url
22
}
23
24
loading.value = false
25
26
async function updateProfile() {
27
try {
28
loading.value = true
29
const user = useSupabaseUser()
30
31
const updates = {
32
id: user.value.id,
33
username: username.value,
34
website: website.value,
35
avatar_url: avatar_path.value,
36
updated_at: new Date(),
37
}
38
39
const { error } = await supabase.from('profiles').upsert(updates, {
40
returning: 'minimal', // Don't return the value after inserting
41
})
42
if (error) throw error
43
} catch (error) {
44
alert(error.message)
45
} finally {
46
loading.value = false
47
}
48
}
49
50
async function signOut() {
51
try {
52
loading.value = true
53
const { error } = await supabase.auth.signOut()
54
if (error) throw error
55
user.value = null
56
} catch (error) {
57
alert(error.message)
58
} finally {
59
loading.value = false
60
}
61
}
62
</script>
63
64
<template>
65
<form class="form-widget" @submit.prevent="updateProfile">
66
<div>
67
<label for="email">Email</label>
68
<input id="email" type="text" :value="user.email" disabled />
69
</div>
70
<div>
71
<label for="username">Username</label>
72
<input id="username" type="text" v-model="username" />
73
</div>
74
<div>
75
<label for="website">Website</label>
76
<input id="website" type="url" v-model="website" />
77
</div>
78
79
<div>
80
<input
81
type="submit"
82
class="button primary block"
83
:value="loading ? 'Loading ...' : 'Update'"
84
:disabled="loading"
85
/>
86
</div>
87
88
<div>
89
<button class="button block" @click="signOut" :disabled="loading">Sign Out</button>
90
</div>
91
</form>
92
</template>

头像照片 #

🌐 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:

1
<script setup>
2
const props = defineProps(['path'])
3
const { path } = toRefs(props)
4
5
const emit = defineEmits(['update:path', 'upload'])
6
7
const supabase = useSupabaseClient()
8
9
const uploading = ref(false)
10
const src = ref('')
11
const files = ref()
12
13
const downloadImage = async () => {
14
try {
15
const { data, error } = await supabase.storage.from('avatars').download(path.value)
16
if (error) throw error
17
src.value = URL.createObjectURL(data)
18
} catch (error) {
19
console.error('Error downloading image: ', error.message)
20
}
21
}
22
23
const uploadAvatar = async (evt) => {
24
files.value = evt.target.files
25
try {
26
uploading.value = true
27
28
if (!files.value || files.value.length === 0) {
29
throw new Error('You must select an image to upload.')
30
}
31
32
const file = files.value[0]
33
const fileExt = file.name.split('.').pop()
34
const fileName = `${Math.random()}.${fileExt}`
35
const filePath = `${fileName}`
36
37
const { error: uploadError } = await supabase.storage.from('avatars').upload(filePath, file)
38
39
if (uploadError) throw uploadError
40
41
emit('update:path', filePath)
42
emit('upload')
43
} catch (error) {
44
alert(error.message)
45
} finally {
46
uploading.value = false
47
}
48
}
49
50
downloadImage()
51
52
watch(path, () => {
53
if (path.value) {
54
downloadImage()
55
}
56
})
57
</script>
58
59
<template>
60
<div>
61
<img
62
v-if="src"
63
:src="src"
64
alt="Avatar"
65
class="avatar image"
66
style="width: 10em; height: 10em;"
67
/>
68
<div v-else class="avatar no-image" :style="{ height: size, width: size }" />
69
70
<div style="width: 10em; position: relative;">
71
<label class="button primary block" for="single">
72
{{ uploading ? 'Uploading ...' : 'Upload' }}
73
</label>
74
<input
75
style="position: absolute; visibility: hidden;"
76
type="file"
77
id="single"
78
accept="image/*"
79
@change="uploadAvatar"
80
:disabled="uploading"
81
/>
82
</div>
83
</div>
84
</template>

触发! #

🌐 Launch!

在所有组件就位后,更新 app.vue

🌐 With all the components in place, update app.vue:

1
<script setup>
2
const user = useSupabaseUser()
3
</script>
4
5
<template>
6
<div class="container" style="padding: 50px 0 100px 0">
7
<Account v-if="user" />
8
<Auth v-else />
9
</div>
10
</template>

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

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

1
npm run dev

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

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

Supabase Nuxt 3

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

🌐 At this stage you have a fully functional application!

添加一个服务器路由 #

🌐 Add a server route

到目前为止,这个应用在客户端验证用户。对于受保护的 API 接口或服务器渲染的数据,你需要一个服务器路由来验证会话。

🌐 So far the app authenticates the user on the client. For protected API endpoints or server-rendered data, you need a server route that verifies the session.

@supabase/server 通过一个中间件处理整个流程:它在本地验证 JWT(使用你项目的非对称签名密钥,不需要往返到认证服务器),把基于 RLS 的 Supabase 客户端和用户的声明附加到请求上,并在你的处理函数运行前直接用 401 拒绝未认证的请求。

1
npm install @supabase/server
1
import { withSupabase } from '@supabase/server/adapters/h3'
2
import { defineHandler } from 'h3'
3
4
export default defineHandler({
5
middleware: [withSupabase({ auth: 'user' })],
6
handler: async (event) => {
7
const { supabase, userClaims } = event.context.supabaseContext
8
9
const { data, error } = await supabase
10
.from('profiles')
11
.select('username, website, avatar_url')
12
.eq('id', userClaims.id)
13
.single()
14
15
if (error) {
16
throw createError({ statusCode: 500, statusMessage: error.message })
17
}
18
19
return data
20
},
21
})

对于未认证的路由,传入 auth: 'none'。如果是整个应用的认证,请在 server/middleware/supabase.ts 注册 withSupabase({ auth: 'user' }) 作为 Nuxt 服务器中间件。有关类型、路由覆盖和完整 API,请查看 h3/Nuxt 适配器文档

🌐 For an unauthenticated route, pass auth: 'none'. For app-wide auth, register withSupabase({ auth: 'user' }) as a Nuxt server middleware at server/middleware/supabase.ts instead. See the h3/Nuxt adapter docs for typing, route overrides, and the full API.