用 SolidJS 构建一个用户管理应用
本教程演示了如何构建一个基本的用户管理应用。该应用可以进行用户认证和识别,将用户的个人资料信息存储在数据库中,并允许用户登录、更新他们的个人资料信息以及上传头像。该应用使用了:
🌐 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.
supabase link --project-ref <project-id># You can get <project-id> from your project's dashboard URL: https://supabase.nodejs.cn/dashboard/project/<project-id>supabase 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.
正在构建应用 #
🌐 Building the app
从零开始构建 SolidJS 应用。
🌐 Start building the SolidJS app from scratch.
初始化一个 SolidJS 应用 #
🌐 Initialize a SolidJS app
你可以使用 degit 来初始化一个叫做 supabase-solid 的应用:
🌐 You can use degit to initialize an app called supabase-solid:
npx degit solidjs/templates/ts supabase-solidcd supabase-solid然后安装唯一的额外依赖:supabase-js
🌐 Then install the only additional dependency: supabase-js
npm install @supabase/supabase-js最后,把环境变量保存在一个 .env 文件中,里面包含你之前复制的 API URL 和密钥 earlier。
🌐 And finally save the environment variables in a .env with the API URL and the key that you copied earlier.
VITE_SUPABASE_URL=https://your-project-ref.supabase.coVITE_SUPABASE_PUBLISHABLE_KEY=your-publishable-key既然你已经有了 API 凭证,就创建一个辅助文件来初始化 Supabase 客户端。这些变量会暴露在浏览器上,这完全没问题,因为你在数据库上启用了行级安全。
🌐 Now that 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 completely fine since you have Row Level Security enabled on the Database.
import { createClient } from '@supabase/supabase-js'import { Database } from './schema'const supabaseUrl = import.meta.env.VITE_SUPABASE_URLconst supabasePublishableKey = import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEYexport 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 sign-in component
设置一个 SolidJS 组件来管理使用 Magic Links 的登录和注册,让用户可以用邮箱登录而无需密码。
🌐 Set up a SolidJS component to manage sign-ins and sign-ups using Magic Links, so users can sign in with their email without using passwords.
import { Component, createSignal } from 'solid-js'import { supabase } from './supabaseClient'const Auth: Component = () => { const [loading, setLoading] = createSignal(false) const [email, setEmail] = createSignal('') const handleLogin = async (e: SubmitEvent) => { e.preventDefault() try { setLoading(true) const { error } = await supabase.auth.signInWithOtp({ email: email() }) if (error) throw error alert('Check your email for the login link!') } catch (error) { if (error instanceof Error) { alert(error.message) } } finally { setLoading(false) } } return ( <div class="row flex-center flex"> <div class="col-6 form-widget" aria-live="polite"> <h1 class="header">Supabase + SolidJS</h1> <p class="description">Sign in via magic link with your email below</p> <form class="form-widget" onSubmit={handleLogin}> <div> <label for="email">Email</label> <input id="email" class="inputField" type="email" placeholder="Your email" value={email()} onChange={(e) => setEmail(e.currentTarget.value)} /> </div> <div> <button type="submit" class="button block" aria-live="polite"> {loading() ? <span>Loading</span> : <span>Send magic link</span>} </button> </div> </form> </div> </div> )}export default Auth账户页面 #
🌐 Account page
用户登录后,允许他们编辑个人资料详情并管理账户。
🌐 After a user is signed in allow them to edit their profile details and manage their account.
为此创建一个名为 Account.tsx 的新组件。
🌐 Create a new component for that called Account.tsx.
import { Component, createEffect, createSignal } from 'solid-js'// ...import { supabase } from './supabaseClient'interface Props { userId: string userEmail: string | null}const Account: Component<Props> = ({ userId, userEmail }) => { const [loading, setLoading] = createSignal(true) const [username, setUsername] = createSignal<string | null>(null) const [website, setWebsite] = createSignal<string | null>(null) const [avatarUrl, setAvatarUrl] = createSignal<string | null>(null) createEffect(() => { getProfile() }) const getProfile = async () => { try { setLoading(true) let { data, error, status } = await supabase .from('profiles') .select(`username, website, avatar_url`) .eq('id', userId) .single() if (error && status !== 406) { throw error } if (data) { setUsername(data.username) setWebsite(data.website) setAvatarUrl(data.avatar_url) } } catch (error) { if (error instanceof Error) { alert(error.message) } } finally { setLoading(false) } } const updateProfile = async (e: Event) => { e.preventDefault() try { setLoading(true) const updates = { id: userId, username: username(), website: website(), avatar_url: avatarUrl(), updated_at: new Date().toISOString(), } let { error } = await supabase.from('profiles').upsert(updates) if (error) { throw error } } catch (error) { if (error instanceof Error) { alert(error.message) } } finally { setLoading(false) } } return ( <div aria-live="polite"> <form onSubmit={updateProfile} class="form-widget"> {/* ... */} <div>Email: {userEmail}</div> <div> <label for="username">Name</label> <input id="username" type="text" value={username() || ''} onChange={(e) => setUsername(e.currentTarget.value)} /> </div> <div> <label for="website">Website</label> <input id="website" type="text" value={website() || ''} onChange={(e) => setWebsite(e.currentTarget.value)} /> </div> <div> <button type="submit" class="button primary block" disabled={loading()}> {loading() ? 'Saving ...' : 'Update profile'} </button> </div> <button type="button" class="button block" onClick={() => supabase.auth.signOut()}> Sign Out </button> </form> </div> )}export default Account头像照片 #
🌐 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:
import { Component, createEffect, createSignal, JSX } from 'solid-js'import { supabase } from './supabaseClient'interface Props { size: number url: string | null onUpload: (event: Event, filePath: string) => void}const Avatar: Component<Props> = (props) => { const [avatarUrl, setAvatarUrl] = createSignal<string | null>(null) const [uploading, setUploading] = createSignal(false) createEffect(() => { if (props.url) downloadImage(props.url) }) 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) setAvatarUrl(url) } catch (error) { if (error instanceof Error) { console.log('Error downloading image: ', error.message) } } } const uploadAvatar: JSX.EventHandler<HTMLInputElement, Event> = async (event) => { try { setUploading(true) const target = event.currentTarget if (!target?.files || target.files.length === 0) { throw new Error('You must select an image to upload.') } const file = target.files[0] const fileExt = file.name.split('.').pop() const fileName = `${Math.random()}.${fileExt}` const filePath = `${fileName}` let { error: uploadError } = await supabase.storage.from('avatars').upload(filePath, file) if (uploadError) { throw uploadError } props.onUpload(event, filePath) } catch (error) { if (error instanceof Error) { alert(error.message) } } finally { setUploading(false) } } return ( <div style={{ width: `${props.size}px` }} aria-live="polite"> {avatarUrl() ? ( <img src={avatarUrl()!} alt={avatarUrl() ? 'Avatar' : 'No image'} class="avatar image" style={{ height: `${props.size}px`, width: `${props.size}px` }} /> ) : ( <div class="avatar no-image" style={{ height: `${props.size}px`, width: `${props.size}px` }} /> )} <div style={{ width: `${props.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/*" onChange={uploadAvatar} disabled={uploading()} /> </span> </div> </div> )}export default Avatar更新账户组件 #
🌐 Update the Account component
创建了 Avatar 组件后,更新 src/Account.tsx 来包含它:
🌐 With the Avatar component created, update src/Account.tsx to include it:
import { Component, createEffect, createSignal } from 'solid-js'import Avatar from './Avatar'import { supabase } from './supabaseClient'interface Props { userId: string userEmail: string | null}const Account: Component<Props> = ({ userId, userEmail }) => { const [loading, setLoading] = createSignal(true) const [username, setUsername] = createSignal<string | null>(null) const [website, setWebsite] = createSignal<string | null>(null) const [avatarUrl, setAvatarUrl] = createSignal<string | null>(null) createEffect(() => { getProfile() }) const getProfile = async () => { try { setLoading(true) let { data, error, status } = await supabase .from('profiles') .select(`username, website, avatar_url`) .eq('id', userId) .single() if (error && status !== 406) { throw error } if (data) { setUsername(data.username) setWebsite(data.website) setAvatarUrl(data.avatar_url) } } catch (error) { if (error instanceof Error) { alert(error.message) } } finally { setLoading(false) } } const updateProfile = async (e: Event) => { e.preventDefault() try { setLoading(true) const updates = { id: userId, username: username(), website: website(), avatar_url: avatarUrl(), updated_at: new Date().toISOString(), } let { error } = await supabase.from('profiles').upsert(updates) if (error) { throw error } } catch (error) { if (error instanceof Error) { alert(error.message) } } finally { setLoading(false) } } return ( <div aria-live="polite"> <form onSubmit={updateProfile} class="form-widget"> <Avatar url={avatarUrl()} size={150} onUpload={(e: Event, url: string) => { setAvatarUrl(url) updateProfile(e) }} /> <div>Email: {userEmail}</div> <div> <label for="username">Name</label> <input id="username" type="text" value={username() || ''} onChange={(e) => setUsername(e.currentTarget.value)} /> </div> <div> <label for="website">Website</label> <input id="website" type="text" value={website() || ''} onChange={(e) => setWebsite(e.currentTarget.value)} /> </div> <div> <button type="submit" class="button primary block" disabled={loading()}> {loading() ? 'Saving ...' : 'Update profile'} </button> </div> <button type="button" class="button block" onClick={() => supabase.auth.signOut()}> Sign Out </button> </form> </div> )}export default Account触发! #
🌐 Launch!
在所有组件就位后,更新 App.tsx:
🌐 With all the components in place, update App.tsx:
import { Component, createEffect, createSignal } from 'solid-js'import { supabase } from './supabaseClient'import Account from './Account'import Auth from './Auth'const App: Component = () => { const [userId, setUserId] = createSignal<string | null>(null) const [userEmail, setUserEmail] = createSignal<string | null>(null) const syncClaims = async () => { const { data } = await supabase.auth.getClaims() setUserId((data?.claims.sub as string) ?? null) setUserEmail((data?.claims.email as string) ?? null) } createEffect(() => { syncClaims() supabase.auth.onAuthStateChange(() => { syncClaims() }) }) return ( <div class="container" style={{ padding: '50px 0 100px 0' }}> {!userId() ? <Auth /> : <Account userId={userId()!} userEmail={userEmail()} />} </div> )}export default App完成后,在终端窗口运行这个:
🌐 Once that's done, run this in a terminal window:
npm start然后打开浏览器访问 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!
添加一个服务器路由(SolidStart) #
🌐 Add a server route (SolidStart)
上面的示例只是客户端。如果你把应用迁移到 SolidStart 以实现服务器端渲染和 API 路由,你可以使用 @supabase/server 添加受保护的服务器端接口。
🌐 The example above is client-only. If you migrate the app to SolidStart for server-side rendering and API routes, you can add protected server endpoints with @supabase/server.
createSupabaseContext 可以在本地验证传入请求的 JWT(使用你项目的非对称签名密钥,无需往返认证服务器)、通过 RLS 将 Supabase 客户端限定到已认证的用户,并暴露用户的声明,所有这些都可以通过在你的 SolidStart API 路由处理器里的一次调用完成。
npm install @supabase/serverimport type { APIEvent } from '@solidjs/start/server'import { createSupabaseContext } from '@supabase/server'export async function GET({ request }: APIEvent) { const { data: ctx, error } = await createSupabaseContext(request, { auth: 'user', }) if (error) { return Response.json({ message: error.message, code: error.code }, { status: error.status }) } const { supabase, userClaims } = ctx const { data, error: queryError } = await supabase .from('profiles') .select('username, website, avatar_url') .eq('id', userClaims.id) .single() if (queryError) { return Response.json({ message: queryError.message }, { status: 500 }) } return Response.json(data)}要将一个路由设为公开,请将 auth: 'user' 替换为 auth: 'none'。若想通过 SolidStart 中间件进行全应用的认证,或使用完整的 @supabase/server API,请查看入门指南。
🌐 To make a route public, swap auth: 'user' for auth: 'none'. For app-wide authentication via SolidStart middleware, or for the full @supabase/server API, see the getting started guide.