Home

Build a User Management App with Angular

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 Database - a Postgres database for storing your user data and Row Level Security so data is protected and users can only access their own information.
  • Supabase Auth - users log in through magic links sent to their email (without having to set up passwords).
  • Supabase Storage - users can upload a profile photo.

Supabase User Management example

note

If you get stuck while working through this guide, refer to the full example on GitHub.

Project setup#

Before we start building we're going to set up our Database and API. This is as simple as 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 we are going to set up the database schema. We can use the "User Management Starter" quickstart in the SQL Editor, or you can just copy/paste the SQL from below and run it yourself.

  1. Go to the SQL Editor page in the Dashboard.
  2. Click User Management Starter.
  3. Click Run.

note

You can easily pull the database schema down to your local project by running the db pull command. Read the local development docs for detailed instructions.


_10
supabase link --project-ref <project-id>
_10
# You can get <project-id> from your project's dashboard URL: https://supabase.com/dashboard/project/<project-id>
_10
supabase db pull

Get the API Keys#

Now that you've created some database tables, you are ready to insert data using the auto-generated API. We just need to get the Project URL and anon key from the API settings.

  1. Go to the API Settings page in the Dashboard.
  2. Find your Project URL, anon, and service_role keys on this page.

Building the App#

Let's start building the Angular app from scratch.

Initialize an Angular app#

We can use the Angular CLI to initialize an app called supabase-angular:


_10
npx ng new supabase-angular --routing false --style css
_10
cd supabase-angular

Then let's install the only additional dependency: supabase-js


_10
npm install @supabase/supabase-js

And finally we want to save the environment variables in the environment.ts file. All we need are the API URL and the anon key that you copied earlier. These variables will be exposed on the browser, and that's completely fine since we have Row Level Security enabled on our Database.

environment.ts

_10
export const environment = {
_10
production: false,
_10
supabaseUrl: 'YOUR_SUPABASE_URL',
_10
supabaseKey: 'YOUR_SUPABASE_KEY',
_10
}

Now that we have the API credentials in place, let's create a SupabaseService with ng g s supabase to initialize the Supabase client and implement functions to communicate with the Supabase API.

src/app/supabase.service.ts

_73
import { Injectable } from '@angular/core'
_73
import {
_73
AuthChangeEvent,
_73
AuthSession,
_73
createClient,
_73
Session,
_73
SupabaseClient,
_73
User,
_73
} from '@supabase/supabase-js'
_73
import { environment } from 'src/environments/environment'
_73
_73
export interface Profile {
_73
id?: string
_73
username: string
_73
website: string
_73
avatar_url: string
_73
}
_73
_73
@Injectable({
_73
providedIn: 'root',
_73
})
_73
export class SupabaseService {
_73
private supabase: SupabaseClient
_73
_session: AuthSession | null = null
_73
_73
constructor() {
_73
this.supabase = createClient(environment.supabaseUrl, environment.supabaseKey)
_73
}
_73
_73
get session() {
_73
this.supabase.auth.getSession().then(({ data }) => {
_73
this._session = data.session
_73
})
_73
return this._session
_73
}
_73
_73
profile(user: User) {
_73
return this.supabase
_73
.from('profiles')
_73
.select(`username, website, avatar_url`)
_73
.eq('id', user.id)
_73
.single()
_73
}
_73
_73
authChanges(callback: (event: AuthChangeEvent, session: Session | null) => void) {
_73
return this.supabase.auth.onAuthStateChange(callback)
_73
}
_73
_73
signIn(email: string) {
_73
return this.supabase.auth.signInWithOtp({ email })
_73
}
_73
_73
signOut() {
_73
return this.supabase.auth.signOut()
_73
}
_73
_73
updateProfile(profile: Profile) {
_73
const update = {
_73
...profile,
_73
updated_at: new Date(),
_73
}
_73
_73
return this.supabase.from('profiles').upsert(update)
_73
}
_73
_73
downLoadImage(path: string) {
_73
return this.supabase.storage.from('avatars').download(path)
_73
}
_73
_73
uploadAvatar(filePath: string, file: File) {
_73
return this.supabase.storage.from('avatars').upload(filePath, file)
_73
}
_73
}

Optionally, update src/styles.css to style the app.

Set up a Login component#

Let's set up an Angular component to manage logins and sign ups. We'll use Magic Links, so users can sign in with their email without using passwords. Create an AuthComponent with ng g c auth Angular CLI command.

src/app/auth/auth.component.ts

_38
import { Component } from '@angular/core'
_38
import { FormBuilder } from '@angular/forms'
_38
import { SupabaseService } from '../supabase.service'
_38
_38
@Component({
_38
selector: 'app-auth',
_38
templateUrl: './auth.component.html',
_38
styleUrls: ['./auth.component.css'],
_38
})
_38
export class AuthComponent {
_38
loading = false
_38
_38
signInForm = this.formBuilder.group({
_38
email: '',
_38
})
_38
_38
constructor(
_38
private readonly supabase: SupabaseService,
_38
private readonly formBuilder: FormBuilder
_38
) {}
_38
_38
async onSubmit(): Promise<void> {
_38
try {
_38
this.loading = true
_38
const email = this.signInForm.value.email as string
_38
const { error } = await this.supabase.signIn(email)
_38
if (error) throw error
_38
alert('Check your email for the login link!')
_38
} catch (error) {
_38
if (error instanceof Error) {
_38
alert(error.message)
_38
}
_38
} finally {
_38
this.signInForm.reset()
_38
this.loading = false
_38
}
_38
}
_38
}

src/app/auth/auth.component.html

_23
<div class="row flex-center flex">
_23
<div class="col-6 form-widget" aria-live="polite">
_23
<h1 class="header">Supabase + Angular</h1>
_23
<p class="description">Sign in via magic link with your email below</p>
_23
<form [formGroup]="signInForm" (ngSubmit)="onSubmit()" class="form-widget">
_23
<div>
_23
<label for="email">Email</label>
_23
<input
_23
id="email"
_23
formControlName="email"
_23
class="inputField"
_23
type="email"
_23
placeholder="Your email"
_23
/>
_23
</div>
_23
<div>
_23
<button type="submit" class="button block" [disabled]="loading">
_23
{{ loading ? 'Loading' : 'Send magic link' }}
_23
</button>
_23
</div>
_23
</form>
_23
</div>
_23
</div>

Account page#

Users also need a way to edit their profile details and manage their accounts after signing in. Create an AccountComponent with the ng g c account Angular CLI command.

src/app/account/account.component.ts

_87
import { Component, Input, OnInit } from '@angular/core'
_87
import { FormBuilder } from '@angular/forms'
_87
import { AuthSession } from '@supabase/supabase-js'
_87
import { Profile, SupabaseService } from '../supabase.service'
_87
_87
@Component({
_87
selector: 'app-account',
_87
templateUrl: './account.component.html',
_87
styleUrls: ['./account.component.css'],
_87
})
_87
export class AccountComponent implements OnInit {
_87
loading = false
_87
profile!: Profile
_87
_87
@Input()
_87
session!: AuthSession
_87
_87
updateProfileForm = this.formBuilder.group({
_87
username: '',
_87
website: '',
_87
avatar_url: '',
_87
})
_87
_87
constructor(private readonly supabase: SupabaseService, private formBuilder: FormBuilder) {}
_87
_87
async ngOnInit(): Promise<void> {
_87
await this.getProfile()
_87
_87
const { username, website, avatar_url } = this.profile
_87
this.updateProfileForm.patchValue({
_87
username,
_87
website,
_87
avatar_url,
_87
})
_87
}
_87
_87
async getProfile() {
_87
try {
_87
this.loading = true
_87
const { user } = this.session
_87
const { data: profile, error, status } = await this.supabase.profile(user)
_87
_87
if (error && status !== 406) {
_87
throw error
_87
}
_87
_87
if (profile) {
_87
this.profile = profile
_87
}
_87
} catch (error) {
_87
if (error instanceof Error) {
_87
alert(error.message)
_87
}
_87
} finally {
_87
this.loading = false
_87
}
_87
}
_87
_87
async updateProfile(): Promise<void> {
_87
try {
_87
this.loading = true
_87
const { user } = this.session
_87
_87
const username = this.updateProfileForm.value.username as string
_87
const website = this.updateProfileForm.value.website as string
_87
const avatar_url = this.updateProfileForm.value.avatar_url as string
_87
_87
const { error } = await this.supabase.updateProfile({
_87
id: user.id,
_87
username,
_87
website,
_87
avatar_url,
_87
})
_87
if (error) throw error
_87
} catch (error) {
_87
if (error instanceof Error) {
_87
alert(error.message)
_87
}
_87
} finally {
_87
this.loading = false
_87
}
_87
}
_87
_87
async signOut() {
_87
await this.supabase.signOut()
_87
}
_87
}

src/app/account/account.component.html

_24
<form [formGroup]="updateProfileForm" (ngSubmit)="updateProfile()" class="form-widget">
_24
<div>
_24
<label for="email">Email</label>
_24
<input id="email" type="text" [value]="session.user.email" disabled />
_24
</div>
_24
<div>
_24
<label for="username">Name</label>
_24
<input formControlName="username" id="username" type="text" />
_24
</div>
_24
<div>
_24
<label for="website">Website</label>
_24
<input formControlName="website" id="website" type="url" />
_24
</div>
_24
_24
<div>
_24
<button type="submit" class="button primary block" [disabled]="loading">
_24
{{ loading ? 'Loading ...' : 'Update' }}
_24
</button>
_24
</div>
_24
_24
<div>
_24
<button class="button block" (click)="signOut()">Sign Out</button>
_24
</div>
_24
</form>

Launch!#

Now that we have all the components in place, let's update AppComponent:

src/app/app.component.ts

_19
import { Component, OnInit } from '@angular/core'
_19
import { SupabaseService } from './supabase.service'
_19
_19
@Component({
_19
selector: 'app-root',
_19
templateUrl: './app.component.html',
_19
styleUrls: ['./app.component.css'],
_19
})
_19
export class AppComponent implements OnInit {
_19
title = 'angular-user-management'
_19
_19
session = this.supabase.session
_19
_19
constructor(private readonly supabase: SupabaseService) {}
_19
_19
ngOnInit() {
_19
this.supabase.authChanges((_, session) => (this.session = session))
_19
}
_19
}

src/app/app.component.html

_10
<div class="container" style="padding: 50px 0 100px 0">
_10
<app-account *ngIf="session; else auth" [session]="session"></app-account>
_10
<ng-template #auth>
_10
<app-auth></app-auth>
_10
</ng-template>
_10
</div>

app.module.ts also needs to be modified to include the ReactiveFormsModule from the @angular/forms package.

src/app/app.module.ts

_16
import { NgModule } from '@angular/core'
_16
import { BrowserModule } from '@angular/platform-browser'
_16
_16
import { AppComponent } from './app.component'
_16
import { AuthComponent } from './auth/auth.component'
_16
import { AccountComponent } from './account/account.component'
_16
import { ReactiveFormsModule } from '@angular/forms'
_16
import { AvatarComponent } from './avatar/avatar.component'
_16
_16
@NgModule({
_16
declarations: [AppComponent, AuthComponent, AccountComponent, AvatarComponent],
_16
imports: [BrowserModule, ReactiveFormsModule],
_16
providers: [],
_16
bootstrap: [AppComponent],
_16
})
_16
export class AppModule {}

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


_10
npm run start

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

Supabase Angular

Bonus: Profile photos#

Every Supabase project is configured with Storage for managing large files like photos and videos.

Create an upload widget#

Let's create an avatar for the user so that they can upload a profile photo. Create an AvatarComponent with ng g c avatar Angular CLI command.

src/app/avatar/avatar.component.ts

_59
import { Component, EventEmitter, Input, Output } from '@angular/core'
_59
import { SafeResourceUrl, DomSanitizer } from '@angular/platform-browser'
_59
import { SupabaseService } from '../supabase.service'
_59
_59
@Component({
_59
selector: 'app-avatar',
_59
templateUrl: './avatar.component.html',
_59
styleUrls: ['./avatar.component.css'],
_59
})
_59
export class AvatarComponent {
_59
_avatarUrl: SafeResourceUrl | undefined
_59
uploading = false
_59
_59
@Input()
_59
set avatarUrl(url: string | null) {
_59
if (url) {
_59
this.downloadImage(url)
_59
}
_59
}
_59
_59
@Output() upload = new EventEmitter<string>()
_59
_59
constructor(private readonly supabase: SupabaseService, private readonly dom: DomSanitizer) {}
_59
_59
async downloadImage(path: string) {
_59
try {
_59
const { data } = await this.supabase.downLoadImage(path)
_59
if (data instanceof Blob) {
_59
this._avatarUrl = this.dom.bypassSecurityTrustResourceUrl(URL.createObjectURL(data))
_59
}
_59
} catch (error) {
_59
if (error instanceof Error) {
_59
console.error('Error downloading image: ', error.message)
_59
}
_59
}
_59
}
_59
_59
async uploadAvatar(event: any) {
_59
try {
_59
this.uploading = true
_59
if (!event.target.files || event.target.files.length === 0) {
_59
throw new Error('You must select an image to upload.')
_59
}
_59
_59
const file = event.target.files[0]
_59
const fileExt = file.name.split('.').pop()
_59
const filePath = `${Math.random()}.${fileExt}`
_59
_59
await this.supabase.uploadAvatar(filePath, file)
_59
this.upload.emit(filePath)
_59
} catch (error) {
_59
if (error instanceof Error) {
_59
alert(error.message)
_59
}
_59
} finally {
_59
this.uploading = false
_59
}
_59
}
_59
}

src/app/avatar/avatar.component.html

_23
<div>
_23
<img
_23
*ngIf="_avatarUrl"
_23
[src]="_avatarUrl"
_23
alt="Avatar"
_23
class="avatar image"
_23
style="height: 150px; width: 150px"
_23
/>
_23
</div>
_23
<div *ngIf="!_avatarUrl" class="avatar no-image" style="height: 150px; width: 150px"></div>
_23
<div style="width: 150px">
_23
<label class="button primary block" for="single">
_23
{{ uploading ? 'Uploading ...' : 'Upload' }}
_23
</label>
_23
<input
_23
style="visibility: hidden;position: absolute"
_23
type="file"
_23
id="single"
_23
accept="image/*"
_23
(change)="uploadAvatar($event)"
_23
[disabled]="uploading"
_23
/>
_23
</div>

Add the new widget#

And then we can add the widget on top of the AccountComponent html template:

src/app/account.component.html

_10
<form [formGroup]="updateProfileForm" (ngSubmit)="updateProfile()" class="form-widget">
_10
<app-avatar [avatarUrl]="this.avatarUrl" (upload)="updateAvatar($event)"> </app-avatar>
_10
<!-- input fields -->
_10
</form>

And add an updateAvatar function along with an avatarUrl getter to the AccountComponent typescript file:

src/app/account.component.ts

_19
@Component({
_19
selector: 'app-account',
_19
templateUrl: './account.component.html',
_19
styleUrls: ['./account.component.css'],
_19
})
_19
export class AccountComponent implements OnInit {
_19
// ...
_19
get avatarUrl() {
_19
return this.updateProfileForm.value.avatar_url as string
_19
}
_19
_19
async updateAvatar(event: string): Promise<void> {
_19
this.updateProfileForm.patchValue({
_19
avatar_url: event,
_19
})
_19
await this.updateProfile()
_19
}
_19
// ...
_19
}

Storage management#

If you upload additional profile photos, they'll accumulate in the avatars bucket because of their random names with only the latest being referenced from public.profiles and the older versions getting orphaned.

To automatically remove obsolete storage objects, extend the database triggers. Note that it is not sufficient to delete the objects from the storage.objects table because that would orphan and leak the actual storage objects in the S3 backend. Instead, invoke the storage API within Postgres via the http extension.

Enable the http extension for the extensions schema in the Dashboard. Then, define the following SQL functions in the SQL Editor to delete storage objects via the API:


_34
create or replace function delete_storage_object(bucket text, object text, out status int, out content text)
_34
returns record
_34
language 'plpgsql'
_34
security definer
_34
as $$
_34
declare
_34
project_url text := '<YOURPROJECTURL>';
_34
service_role_key text := '<YOURSERVICEROLEKEY>'; -- full access needed
_34
url text := project_url||'/storage/v1/object/'||bucket||'/'||object;
_34
begin
_34
select
_34
into status, content
_34
result.status::int, result.content::text
_34
FROM extensions.http((
_34
'DELETE',
_34
url,
_34
ARRAY[extensions.http_header('authorization','Bearer '||service_role_key)],
_34
NULL,
_34
NULL)::extensions.http_request) as result;
_34
end;
_34
$$;
_34
_34
create or replace function delete_avatar(avatar_url text, out status int, out content text)
_34
returns record
_34
language 'plpgsql'
_34
security definer
_34
as $$
_34
begin
_34
select
_34
into status, content
_34
result.status, result.content
_34
from public.delete_storage_object('avatars', avatar_url) as result;
_34
end;
_34
$$;

Next, add a trigger that removes any obsolete avatar whenever the profile is updated or deleted:


_32
create or replace function delete_old_avatar()
_32
returns trigger
_32
language 'plpgsql'
_32
security definer
_32
as $$
_32
declare
_32
status int;
_32
content text;
_32
avatar_name text;
_32
begin
_32
if coalesce(old.avatar_url, '') <> ''
_32
and (tg_op = 'DELETE' or (old.avatar_url <> new.avatar_url)) then
_32
-- extract avatar name
_32
avatar_name := old.avatar_url;
_32
select
_32
into status, content
_32
result.status, result.content
_32
from public.delete_avatar(avatar_name) as result;
_32
if status <> 200 then
_32
raise warning 'Could not delete avatar: % %', status, content;
_32
end if;
_32
end if;
_32
if tg_op = 'DELETE' then
_32
return old;
_32
end if;
_32
return new;
_32
end;
_32
$$;
_32
_32
create trigger before_profile_changes
_32
before update of avatar_url or delete on public.profiles
_32
for each row execute function public.delete_old_avatar();

Finally, delete the public.profile row before a user is deleted. If this step is omitted, you won't be able to delete users without first manually deleting their avatar image.


_14
create or replace function delete_old_profile()
_14
returns trigger
_14
language 'plpgsql'
_14
security definer
_14
as $$
_14
begin
_14
delete from public.profiles where id = old.id;
_14
return old;
_14
end;
_14
$$;
_14
_14
create trigger before_delete_user
_14
before delete on auth.users
_14
for each row execute function public.delete_old_profile();

At this stage you have a fully functional application!