Skip to content
Getting Started

Build a User Management App with 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 User Management example

Project setup#

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. Create a new project in the Supabase Dashboard.
  2. Enter your project details.
  3. Wait for the new database to launch.

Set up the database schema#

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. Go to the SQL Editor page in the Dashboard.
  2. Click User Management Starter under the Reference > Examples tab.
  3. Click Run.

Get API details#

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#

Start building the SolidJS app from scratch.

Initialize a SolidJS app#

You can use degit to initialize an app called supabase-solid:

npx degit solidjs/templates/ts supabase-solid
cd supabase-solid

Then install the only additional dependency: supabase-js

npm install @supabase/supabase-js

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.co
VITE_SUPABASE_PUBLISHABLE_KEY=your-publishable-key
View source

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_URL
const supabasePublishableKey = import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY
export const supabase = createClient(supabaseUrl, supabasePublishableKey)
View source

App styling (optional)#

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#

Set up a SolidJS component to manage logins 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
View source

Account page#

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.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
View source

Profile photos#

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
View source

Update the Account component#

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
View source

Launch!#

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
View source

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

npm start

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

Supabase SolidJS

At this stage you have a fully functional application!

Add a server route (SolidStart)#

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 validates the incoming request's JWT locally (using your project's asymmetric signing keys, no round-trip to the Auth server), scopes a Supabase client to the authenticated user via RLS, and exposes the user's claims, all from a single call inside your SolidStart API route handler.

npm install @supabase/server
import 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)
}

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.