用 Nuxt 3 构建一个用户管理应用
探索适用于你 Supabase 应用的即插即用 UI 组件。
基于 shadcn/ui 构建的 UI 组件,通过一个命令连接到 Supabase。
🌐 UI components built on shadcn/ui that connect to Supabase via a single command.
探索组件本教程演示了如何构建一个基本的用户管理应用。该应用可以进行用户认证和识别,将用户的个人资料信息存储在数据库中,并允许用户登录、更新他们的个人资料信息以及上传头像。该应用使用了:
🌐 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 数据库 - 一个用于存储用户数据的 Postgres 数据库,并且有 行级安全,所以数据是受保护的,用户只能访问自己的信息。
- Supabase Auth - 允许用户注册和登录。
- Supabase 存储 - 允许用户上传个人头像。

如果你在跟着这个指南操作时遇到困难,你可以在GitHub上找到完整示例。
🌐 If you get stuck while working through this guide, you can find the full example on GitHub.
项目设置 #
🌐 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
- 在 Supabase 仪表板中创建一个新项目。
- 输入你的项目详情。
- 等新数据库上线。
设置数据库模式 #
🌐 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.
- 在仪表板中转到SQL 编辑器页面。
- 点击 社区 > 快速入门 标签下的 用户管理入门。
- 点击运行。
你可以通过运行 db pull 命令将数据库架构拉到本地项目。查看本地开发文档获取详细说明。
🌐 You can pull the database schema down to your local project by running the db pull command. Read the local development docs for detailed instructions.
1supabase link --project-ref <project-id>2# You can get <project-id> from your project's dashboard URL: https://supabase.com/dashboard/project/<project-id>3supabase db pull获取 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.
阅读 API 密钥文档 以全面了解所有密钥类型、用途以及在哪里可以找到它们。
正在构建应用 #
🌐 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:
1npx nuxi init nuxt-user-management23cd 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.
1npm 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.
1SUPABASE_URL="YOUR_SUPABASE_URL"2SUPABASE_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.
1import { defineNuxtConfig } from 'nuxt'23// https://v3.nuxtjs.org/api/configuration/nuxt.config4export 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>2const supabase = useSupabaseClient()34const loading = ref(false)5const email = ref('')67const handleLogin = async () => {8 try {9 loading.value = true10 const { error } = await supabase.auth.signInWithOtp({ email: email.value })11 if (error) throw error12 alert('Check your email for the login link!')13 } catch (error) {14 alert(error.error_description || error.message)15 } finally {16 loading.value = false17 }18}19</script>2021<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 <input31 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>2const supabase = useSupabaseClient()34const loading = ref(true)5const username = ref('')6const website = ref('')7const avatar_path = ref('')89loading.value = true10const user = useSupabaseUser()1112const { data } = await supabase13 .from('profiles')14 .select(`username, website, avatar_url`)15 .eq('id', user.value.id)16 .single()1718if (data) {19 username.value = data.username20 website.value = data.website21 avatar_path.value = data.avatar_url22}2324loading.value = false2526async function updateProfile() {27 try {28 loading.value = true29 const user = useSupabaseUser()3031 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 }3839 const { error } = await supabase.from('profiles').upsert(updates, {40 returning: 'minimal', // Don't return the value after inserting41 })42 if (error) throw error43 } catch (error) {44 alert(error.message)45 } finally {46 loading.value = false47 }48}4950async function signOut() {51 try {52 loading.value = true53 const { error } = await supabase.auth.signOut()54 if (error) throw error55 user.value = null56 } catch (error) {57 alert(error.message)58 } finally {59 loading.value = false60 }61}62</script>6364<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>7879 <div>80 <input81 type="submit"82 class="button primary block"83 :value="loading ? 'Loading ...' : 'Update'"84 :disabled="loading"85 />86 </div>8788 <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>2const props = defineProps(['path'])3const { path } = toRefs(props)45const emit = defineEmits(['update:path', 'upload'])67const supabase = useSupabaseClient()89const uploading = ref(false)10const src = ref('')11const files = ref()1213const downloadImage = async () => {14 try {15 const { data, error } = await supabase.storage.from('avatars').download(path.value)16 if (error) throw error17 src.value = URL.createObjectURL(data)18 } catch (error) {19 console.error('Error downloading image: ', error.message)20 }21}2223const uploadAvatar = async (evt) => {24 files.value = evt.target.files25 try {26 uploading.value = true2728 if (!files.value || files.value.length === 0) {29 throw new Error('You must select an image to upload.')30 }3132 const file = files.value[0]33 const fileExt = file.name.split('.').pop()34 const fileName = `${Math.random()}.${fileExt}`35 const filePath = `${fileName}`3637 const { error: uploadError } = await supabase.storage.from('avatars').upload(filePath, file)3839 if (uploadError) throw uploadError4041 emit('update:path', filePath)42 emit('upload')43 } catch (error) {44 alert(error.message)45 } finally {46 uploading.value = false47 }48}4950downloadImage()5152watch(path, () => {53 if (path.value) {54 downloadImage()55 }56})57</script>5859<template>60 <div>61 <img62 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 }" />6970 <div style="width: 10em; position: relative;">71 <label class="button primary block" for="single">72 {{ uploading ? 'Uploading ...' : 'Upload' }}73 </label>74 <input75 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>2const user = useSupabaseUser()3</script>45<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:
1npm run dev然后打开浏览器访问 localhost:3000,你应该能看到完成的应用。
🌐 And then open the browser to localhost:3000 and you should see the completed app.

在这个阶段,你已经有了一个完全可用的应用!
🌐 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 拒绝未认证的请求。
1npm install @supabase/server1import { withSupabase } from '@supabase/server/adapters/h3'2import { defineHandler } from 'h3'34export default defineHandler({5 middleware: [withSupabase({ auth: 'user' })],6 handler: async (event) => {7 const { supabase, userClaims } = event.context.supabaseContext89 const { data, error } = await supabase10 .from('profiles')11 .select('username, website, avatar_url')12 .eq('id', userClaims.id)13 .single()1415 if (error) {16 throw createError({ statusCode: 500, statusMessage: error.message })17 }1819 return data20 },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.