用 React 构建一个用户管理应用
探索适用于你 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
从零开始搭建 React 应用。
🌐 Start building the React app from scratch.
初始化一个 React 应用 #
🌐 Initialize a React app
使用 Vite 初始化一个名为 supabase-react 的应用:
🌐 Use Vite to initialize an app called supabase-react:
1npm create vite@latest supabase-react -- --template react2cd supabase-react安装 supabase-js:
🌐 Install supabase-js:
1npm install @supabase/supabase-js将环境变量保存到 .env.local 文件中,使用你之前复制的项目 URL 和密钥 参考。
🌐 Save the environment variables in a .env.local file, using the Project URL and the key that you copied earlier.
1VITE_SUPABASE_URL=2VITE_SUPABASE_PUBLISHABLE_KEY=在配置好 API 凭证后,创建一个辅助文件来初始化 Supabase 客户端。应用会在浏览器中暴露这些变量,这没问题,因为 Supabase 默认在所有表上启用了 行级安全。
🌐 With the API credentials in place, create a helper file to initialize the Supabase client. The application exposes these variables in the browser, and that's fine as Supabase enables Row Level Security by default on all tables.
创建并编辑 src/supabaseClient.js:
🌐 Create and edit src/supabaseClient.js:
1/**2 * lib/supabaseClient.js3 * Helper to initialize the Supabase client.4 */56import { createClient } from '@supabase/supabase-js'78const supabaseUrl = import.meta.env.VITE_SUPABASE_URL9const supabasePublishableKey = import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY1011export const supabase = createClient(supabaseUrl, supabasePublishableKey)应用风格(可选) #
🌐 App styling (optional)
一个可选步骤是更新 CSS 文件 src/index.css,让应用看起来更好。你可以在示例仓库中找到这个文件的完整内容。
🌐 An optional step is to update the CSS file src/index.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
你需要一个 React 组件来管理登录和注册。它使用 Magic Links,所以用户可以通过邮箱登录而无需使用密码。
🌐 You need a React component to manage logins and sign-ups. It uses Magic Links, so users can sign in with their email without using passwords.
你知道吗?
你可以自定义发送给新用户的其他邮件,包括邮件的外观、内容以及查询参数,都可以在仪表板的 认证 > 邮件 部分进行设置。
🌐 You can customize other emails sent out to new users, including the email's looks, content, and query parameters from the Authentication > Email section of the Dashboard.
创建并编辑 src/Auth.jsx:
🌐 Create and edit src/Auth.jsx:
1import { useState } from 'react'2import { supabase } from './supabaseClient'34export default function Auth() {5 const [loading, setLoading] = useState(false)6 const [email, setEmail] = useState('')78 const handleLogin = async (event) => {9 event.preventDefault()1011 setLoading(true)12 const { error } = await supabase.auth.signInWithOtp({ email })1314 if (error) {15 alert(error.error_description || error.message)16 } else {17 alert('Check your email for the login link!')18 }19 setLoading(false)20 }2122 return (23 <div className="row flex flex-center">24 <div className="col-6 form-widget">25 <h1 className="header">Supabase + React</h1>26 <p className="description">Sign in via magic link with your email below</p>27 <form className="form-widget" onSubmit={handleLogin}>28 <div>29 <input30 className="inputField"31 type="email"32 placeholder="Your email"33 value={email}34 required={true}35 onChange={(e) => setEmail(e.target.value)}36 />37 </div>38 <div>39 <button className={'button block'} disabled={loading}>40 {loading ? <span>Loading</span> : <span>Send magic link</span>}41 </button>42 </div>43 </form>44 </div>45 </div>46 )47}账户页面 #
🌐 Account page
用户登录后,需要一种方式来编辑他们的个人资料信息并管理他们的账户。
🌐 After a user signs in, they need a way to edit their profile details and manage their accounts.
创建一个名为 src/Account.jsx 的新组件,并添加以下代码:
🌐 Create a new component called src/Account.jsx and add the following code:
1import { useState, useEffect } from 'react'2import { supabase } from './supabaseClient'34// ...567export default function Account({ user }) {8 const [loading, setLoading] = useState(true)9 const [username, setUsername] = useState(null)10 const [website, setWebsite] = useState(null)11 const [avatar_url, setAvatarUrl] = useState(null)1213 useEffect(() => {14 let ignore = false15 async function getProfile() {16 setLoading(true)1718 const { data, error } = await supabase19 .from('profiles')20 .select(`username, website, avatar_url`)21 .eq('id', user.id)22 .single()2324 if (!ignore) {25 if (error) {26 console.warn(error)27 } else if (data) {28 setUsername(data.username)29 setWebsite(data.website)30 setAvatarUrl(data.avatar_url)31 }32 }3334 setLoading(false)35 }3637 getProfile()3839 return () => {40 ignore = true41 }42 }, [user])4344 async function updateProfile(event, avatarUrl) {45 event.preventDefault()4647 setLoading(true)4849 const updates = {50 id: user.id,51 username,52 website,53 avatar_url: avatarUrl,54 updated_at: new Date(),55 }5657 const { error } = await supabase.from('profiles').upsert(updates)5859 if (error) {60 alert(error.message)61 } else {62 setAvatarUrl(avatarUrl)63 }64 setLoading(false)65 }6667 return (68 <form onSubmit={updateProfile} className="form-widget">6970 {/* ... */}7172 <div>73 <label htmlFor="email">Email</label>74 <input id="email" type="text" value={user.email} disabled />75 </div>76 <div>77 <label htmlFor="username">Name</label>78 <input79 id="username"80 type="text"81 required82 value={username || ''}83 onChange={(e) => setUsername(e.target.value)}84 />85 </div>86 <div>87 <label htmlFor="website">Website</label>88 <input89 id="website"90 type="url"91 value={website || ''}92 onChange={(e) => setWebsite(e.target.value)}93 />94 </div>9596 <div>97 <button className="button block primary" type="submit" disabled={loading}>98 {loading ? 'Loading ...' : 'Update'}99 </button>100 </div>101102 <div>103 <button className="button block" type="button" onClick={() => supabase.auth.signOut()}>104 Sign Out105 </button>106 </div>107 </form>108 )109}头像照片 #
🌐 Profile photos
添加一个让用户上传个人资料照片的方式。Supabase 为每个项目配置了 Storage,用于管理照片和视频等大文件。
🌐 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
创建 src/Avatar.jsx 并添加以下代码:
🌐 Create src/Avatar.jsx and add the following code:
1import { useEffect, useState } from 'react'2import { supabase } from './supabaseClient'34export default function Avatar({ url, size, onUpload }) {5 const [avatarUrl, setAvatarUrl] = useState(null)6 const [uploading, setUploading] = useState(false)78 useEffect(() => {9 if (url) downloadImage(url)10 }, [url])1112 async function downloadImage(path) {13 try {14 const { data, error } = await supabase.storage.from('avatars').download(path)15 if (error) {16 throw error17 }18 const url = URL.createObjectURL(data)19 setAvatarUrl(url)20 } catch (error) {21 console.log('Error downloading image: ', error.message)22 }23 }2425 async function uploadAvatar(event) {26 try {27 setUploading(true)2829 if (!event.target.files || event.target.files.length === 0) {30 throw new Error('You must select an image to upload.')31 }3233 const file = event.target.files[0]34 const fileExt = file.name.split('.').pop()35 const fileName = `${Math.random()}.${fileExt}`36 const filePath = `${fileName}`3738 let { error: uploadError } = await supabase.storage.from('avatars').upload(filePath, file)3940 if (uploadError) {41 throw uploadError42 }4344 onUpload(event, filePath)45 } catch (error) {46 alert(error.message)47 } finally {48 setUploading(false)49 }50 }5152 return (53 <div>54 {avatarUrl ? (55 <img56 src={avatarUrl}57 alt="Avatar"58 className="avatar image"59 style={{ height: size, width: size }}60 />61 ) : (62 <div className="avatar no-image" style={{ height: size, width: size }} />63 )}64 <div style={{ width: size }}>65 <label className="button primary block" htmlFor="single">66 {uploading ? 'Uploading ...' : 'Upload'}67 </label>68 <input69 style={{70 visibility: 'hidden',71 position: 'absolute',72 }}73 type="file"74 id="single"75 accept="image/*"76 onChange={uploadAvatar}77 disabled={uploading}78 />79 </div>80 </div>81 )82}更新账户组件 #
🌐 Update the Account component
创建了 Avatar 组件后,更新 src/Account.jsx 来包含它:
🌐 With the Avatar component created, update src/Account.jsx to include it:
1import { useState, useEffect } from 'react'2import { supabase } from './supabaseClient'3import Avatar from './Avatar'45export default function Account({ user }) {6 const [loading, setLoading] = useState(true)7 const [username, setUsername] = useState(null)8 const [website, setWebsite] = useState(null)9 const [avatar_url, setAvatarUrl] = useState(null)1011 useEffect(() => {12 let ignore = false13 async function getProfile() {14 setLoading(true)1516 const { data, error } = await supabase17 .from('profiles')18 .select(`username, website, avatar_url`)19 .eq('id', user.id)20 .single()2122 if (!ignore) {23 if (error) {24 console.warn(error)25 } else if (data) {26 setUsername(data.username)27 setWebsite(data.website)28 setAvatarUrl(data.avatar_url)29 }30 }3132 setLoading(false)33 }3435 getProfile()3637 return () => {38 ignore = true39 }40 }, [user])4142 async function updateProfile(event, avatarUrl) {43 event.preventDefault()4445 setLoading(true)4647 const updates = {48 id: user.id,49 username,50 website,51 avatar_url: avatarUrl,52 updated_at: new Date(),53 }5455 const { error } = await supabase.from('profiles').upsert(updates)5657 if (error) {58 alert(error.message)59 } else {60 setAvatarUrl(avatarUrl)61 }62 setLoading(false)63 }6465 return (66 <form onSubmit={updateProfile} className="form-widget">67 <Avatar68 url={avatar_url}69 size={150}70 onUpload={(event, url) => {71 updateProfile(event, url)72 }}73 />74 <div>75 <label htmlFor="email">Email</label>76 <input id="email" type="text" value={user.email} disabled />77 </div>78 <div>79 <label htmlFor="username">Name</label>80 <input81 id="username"82 type="text"83 required84 value={username || ''}85 onChange={(e) => setUsername(e.target.value)}86 />87 </div>88 <div>89 <label htmlFor="website">Website</label>90 <input91 id="website"92 type="url"93 value={website || ''}94 onChange={(e) => setWebsite(e.target.value)}95 />96 </div>9798 <div>99 <button className="button block primary" type="submit" disabled={loading}>100 {loading ? 'Loading ...' : 'Update'}101 </button>102 </div>103104 <div>105 <button className="button block" type="button" onClick={() => supabase.auth.signOut()}>106 Sign Out107 </button>108 </div>109 </form>110 )111}触发! #
🌐 Launch!
在所有组件就位后,修改 src/App.jsx 的内容,将新组件和身份验证逻辑加入进去。
🌐 With all the components in place, change the contents of src/App.jsx to include the new components and Auth logic.
Supabase Auth SDK 包含三种不同的函数,用于验证用户对应用的访问权限:
🌐 The Supabase Auth SDK contains three different functions for authenticating user access to applications:
方法总结 #
🌐 Summary of the methods
- 使用
getClaims来保护页面和用户数据。它会从存储中读取访问令牌并进行验证。在本地通过 WebCrypto API 和缓存的 JWKS 端点进行操作,当项目使用非对称签名密钥时(这是新项目的默认设置);如果使用对称密钥,则仅通过调用getUser来验证。返回的声明总是来自解析 JWT,而不是通过用户查询获得。 [getUser](/docs/reference/javascript/auth-getuser)会向项目的 Auth 实例发起网络请求以获取用户记录,这样可以获得用户的最新信息,但需要进行一次网络请求。getSession当你需要原始会话(访问令牌、刷新令牌和过期时间)时使用。例如,将访问令牌转发到另一个服务。会话是直接从本地存储加载的,并不会重新向认证服务器验证,因此当存储与客户端共享(如 cookies、请求头)时,嵌入的用户对象不应单独信任。要验证身份,请使用getClaims验证访问令牌,或调用getUser获取一个新的、服务器确认的用户记录。
总结:使用 getClaims 来验证身份(通常用于保护页面和数据),当你需要从认证服务器获取最新的用户记录时用 getUser,而当你直接需要访问或刷新令牌时用 getSession,但不要依赖它返回的用户对象来做授权决策。
1function App() {2 const [claims, setClaims] = useState(null)34 useEffect(() => {5 const loadClaims = async () => {6 const {7 data: { claims },8 } = await supabase.auth.getClaims()9 setClaims(claims)10 }1112 loadClaims()1314 const {15 data: { subscription },16 } = supabase.auth.onAuthStateChange(() => {17 loadClaims()18 })1920 return () => subscription.unsubscribe()21 }, [])2223 return (24 <div className="container" style={{ padding: '50px 0 100px 0' }}>25 {!claims ? <Auth /> : <Account key={claims.sub} claims={claims} />}26 </div>27 )28}完成后,在终端窗口运行这个:
🌐 Once that's done, run this in a terminal window:
1npm run dev然后打开浏览器访问 localhost:5173,你应该能看到完成的应用。
🌐 And then open the browser to localhost:5173 and you should see the completed app.

在这个阶段,你已经有了一个完全可用的应用!
🌐 At this stage you have a fully functional application!