Getting Started

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

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.

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

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

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

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

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
}

At this stage you have a fully functional application!