Merge pull request #9664 from supabase/master

Prod deploy
This commit is contained in:
Jonathan Summers-Muir authored and GitHub committed 2022-10-19 12:22:50 +08:00
commit 96f7ccc322
28 files changed
+1131 -643

No files matched your search

-27
View File
@@ -1,27 +0,0 @@
name: Deploy studio app to production on vercel
on:
push:
branches:
- studio
paths:
- 'studio/**'
jobs:
deploy:
runs-on: ubuntu-18.04
timeout-minutes: 10
steps:
- uses: actions/checkout@v2
# remove ./studio/pages/api folder before deploying to vercel
- uses: JesseTG/rm@v1.0.2
with:
path: ./studio/pages/api
- uses: amondnet/vercel-action@v19
with:
vercel-token: ${{ secrets.VERCEL_TOKEN }} # Required
github-comment: false
vercel-args: '--prod -A .vercel/production.json'
vercel-org-id: team_E6KJ1W561hMTjon1QSwOh0WO #Required
vercel-project-id: Qmd7Mw8yFW8SbtvTWFV9uyRzw9P1rJLmgtHjSezywhtYec #Required
working-directory: ./studio #Your Working Directory, Optional
vercel-project-name: app
@@ -1,27 +0,0 @@
name: Deploy studio app to staging on vercel
on:
push:
branches:
- master
paths:
- 'studio/**'
jobs:
deploy:
runs-on: ubuntu-18.04
timeout-minutes: 10
steps:
- uses: actions/checkout@v2
# remove ./studio/pages/api folder before deploying to vercel
- uses: JesseTG/rm@v1.0.2
with:
path: ./studio/pages/api
- uses: amondnet/vercel-action@v19
with:
vercel-token: ${{ secrets.VERCEL_TOKEN }} # Required
github-comment: false
vercel-args: '--prod -A .vercel/staging.json'
vercel-org-id: team_E6KJ1W561hMTjon1QSwOh0WO #Required
vercel-project-id: QmcmhbiAtCMFTAHCuGgQscNbke4TzgWULECctNcKmxWCoT #Required
working-directory: ./studio #Your Working Directory, Optional
vercel-project-name: staging-app
+3
View File
@@ -16,6 +16,9 @@ The CLI is still under development, but it contains all the functionality for wo
- CI/CD for releasing to production: [`supabase db push`](https://supabase.com/docs/reference/cli/usage#supabase-db-push)
- Manage your Supabase projects: [`supabase projects`](https://supabase.com/docs/reference/cli/usage#supabase-projects)
- Generate types directly from your database schema: [`supabase gen types`](https://supabase.com/docs/reference/cli/usage#supabase-gen)
- A [community-supported GitHub Action](https://github.com/lyqht/generate-supabase-db-types-github-action) to generate TypeScript types
- Shell autocomplete: [`supabase completion`](https://supabase.com/docs/reference/cli/usage#supabase-completion)
- A [community-supported Fig autocomplete spec](https://fig.io/manual/supabase) for macOS terminal
## Additional Links
@@ -31,7 +31,8 @@ This library supports the following tooling versions:
- Node.js: `^10.13.0 || >=12.0.0`
- Next.js: `>=10`
Optionally, install **React Auth Helpers** for components and hooks that can be used across all React-based frameworks.
Additionally, install the **React Auth Helpers** for components and hooks that can be used across all React-based frameworks.
```sh
npm install @supabase/auth-helpers-react
```
@@ -48,7 +49,7 @@ This library supports the following tooling versions:
- Node.js: `^10.13.0 || >=12.0.0`
- Next.js: `>=10`
Optionally, install **React Auth Helpers** for components and hooks that can be used across all React-based frameworks.
Additionally, install the **React Auth Helpers** for components and hooks that can be used across all React-based frameworks.
```sh
yarn add @supabase/auth-helpers-react
@@ -61,23 +62,30 @@ yarn add @supabase/auth-helpers-react
Retrieve your project URL and anon key in your project's [API settings](https://app.supabase.com/project/_/settings/api) in the Dashboard to set up the following environment variables. For local development you can set them in a `.env.local` file. See an [example](https://github.com/supabase/auth-helpers/blob/main/examples/nextjs/.env.local.example).
```bash
NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key
```bash title=".env.local"
NEXT_PUBLIC_SUPABASE_URL=YOUR_SUPABASE_URL
NEXT_PUBLIC_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY
```
## Basic Setup
<Tabs
defaultValue="js"
values={[
{label: 'JavaScript', value: 'js'},
{label: 'TypeScript', value: 'ts'},
]}>
<TabItem value="js">
Wrap your `pages/_app.js` component with the `SessionContextProvider` component:
```jsx title="pages/_app.js"
import React from 'react'
import { useRouter } from 'next/router'
import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'
import { SessionContextProvider } from '@supabase/auth-helpers-react'
function MyApp({ Component, pageProps }: AppProps) {
function MyApp({ Component, pageProps }) {
const router = useRouter()
// Create a new supabase browser client on every first render.
const [supabaseClient] = useState(() => createBrowserSupabaseClient())
return (
@@ -85,58 +93,105 @@ function MyApp({ Component, pageProps }: AppProps) {
supabaseClient={supabaseClient}
initialSession={pageProps.initialSession}
>
<button
onClick={async () => {
await supabaseClient.auth.signOut()
router.push('/')
}}
>
Logout
</button>
<Component {...pageProps} />
</SessionContextProvider>
)
}
```
</TabItem>
<TabItem value="ts">
Wrap your `pages/_app.tsx` component with the `SessionContextProvider` component:
```jsx title="pages/_app.tsx"
import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'
// highlight-next-line
import { SessionContextProvider, Session } from '@supabase/auth-helpers-react'
function MyApp({
Component,
pageProps,
}: AppProps<{
// highlight-next-line
initialSession: Session,
}>) {
// Create a new supabase browser client on every first render.
const [supabaseClient] = useState(() => createBrowserSupabaseClient())
return (
<SessionContextProvider
supabaseClient={supabaseClient}
initialSession={pageProps.initialSession}
>
<Component {...pageProps} />
</SessionContextProvider>
)
}
```
</TabItem>
</Tabs>
You can now determine if a user is authenticated by checking that the `user` object returned by the `useUser()` hook is defined.
## Usage with TypeScript
You can pass types that were [generated with the Supabase CLI](/docs/reference/javascript/typescript-support#generating-types) to the Supabase Client to get enhanced type safety and auto completion:
```js
// Creating a new supabase client object:
import { Database } from '../db_types';
### Browser client
const [supabaseClient] = useState(() =>
createBrowserSupabaseClient<Database>()
);
```ts
// Creating a new supabase client object:
import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'
import { Database } from '../database.types'
const supabaseClient = createBrowserSupabaseClient<Database>()
```
```js
```ts
// Retrieving a supabase client object from the SessionContext:
import { useSupabaseClient } from '@supabase/auth-helpers-react';
import { Database } from '../db_types';
import { useSupabaseClient } from '@supabase/auth-helpers-react'
import { Database } from '../database.types'
const supabaseClient = useSupabaseClient<Database>();
const supabaseClient = useSupabaseClient<Database>()
```
### Server client
```ts
// Creating a new supabase server client object (e.g. in API route):
import type { NextApiRequest, NextApiResponse } from 'next'
import type { Database } from 'types_db'
export default async (req: NextApiRequest, res: NextApiResponse) => {
const supabaseServerClient = createServerSupabaseClient<Database>({
req,
res,
})
const {
data: { user },
} = await supabaseServerClient.auth.getUser()
res.status(200).json({ name: user?.name ?? '' })
}
```
## Client-side data fetching with RLS
For [row level security](https://supabase.com/docs/learn/auth-deep-dive/auth-row-level-security) to work properly when fetching data client-side, you need to make sure to use the `supabaseClient` from the `useSessionContext` hook and only run your query once the user is defined client-side in the `useUser()` hook:
For [row level security](https://supabase.com/docs/learn/auth-deep-dive/auth-row-level-security) to work properly when fetching data client-side, you need to make sure to use the `supabaseClient` from the `useSupabaseClient` hook and only run your query once the user is defined client-side in the `useUser()` hook:
```js
import { Auth, ThemeSupa } from '@supabase/auth-ui-react'
import { useUser, useSessionContext } from '@supabase/auth-helpers-react'
import { useUser, useSupabaseClient } from '@supabase/auth-helpers-react'
import { useEffect, useState } from 'react'
const LoginPage = () => {
const { isLoading, session, error, supabaseClient } = useSessionContext()
const supabaseClient = useSupabaseClient()
const user = useUser()
const [data, setData] = useState()
// highlight-start
useEffect(() => {
async function loadData() {
const { data } = await supabaseClient.from('test').select('*')
@@ -145,19 +200,17 @@ const LoginPage = () => {
// Only run query once user is logged in.
if (user) loadData()
}, [user])
// highlight-end
if (!user)
return (
<>
{error && <p>{error.message}</p>}
<Auth
redirectTo="http://localhost:3000/"
appearance={{ theme: ThemeSupa }}
supabaseClient={supabaseClient}
providers={['google', 'github']}
socialLayout="horizontal"
/>
</>
<Auth
redirectTo="http://localhost:3000/"
appearance={{ theme: ThemeSupa }}
supabaseClient={supabaseClient}
providers={['google', 'github']}
socialLayout="horizontal"
/>
)
return (
@@ -174,7 +227,7 @@ const LoginPage = () => {
export default LoginPage
```
### Server-side rendering (SSR) - withPageAuth
## Server-side rendering (SSR) - withPageAuth
If you wrap your `getServerSideProps` with `withPageAuth` your props object will be augmented with the user object.
@@ -191,7 +244,7 @@ export const getServerSideProps = withPageAuth({ redirectTo: '/login' })
If there is no authenticated user, they will be redirect to your home page, unless you specify the `redirectTo` option.
You can pass in your own `getServerSideProps` method, the props returned from this will be merged with the
user props. You can also access the user session data by calling `getUser` inside of this method, eg:
user props. You can also access the user session data by calling `supabase.auth.getUser()` inside of this method, eg:
```js title="pages/protected-page.js"
import { withPageAuth } from '@supabase/auth-helpers-nextjs'
@@ -212,7 +265,7 @@ export const getServerSideProps = withPageAuth({
})
```
### Server-side data fetching with RLS
## Server-side data fetching with RLS
Both `withApiAuth` and `withPageAuth` return a supabase client that you can use to run [row level security](https://supabase.com/docs/learn/auth-deep-dive/auth-row-level-security) authenticated queries server-side:
@@ -245,44 +298,62 @@ export const getServerSideProps = withPageAuth({
})
```
### Server-side data fetching to OAuth APIs using `provider_token`
## Server-side data fetching to OAuth APIs using `provider_token`
When using third-party auth providers, sessions are initiated with an additional `provider_token` field which is persisted as an HTTPOnly cookie upon logging in to enabled usage on the server side. The `provider_token` can be used to make API requests to the OAuth provider's API endpoints on behalf of the logged-in user. In the following example, we fetch the user's full profile from the third-party API during SSR using their id and auth token:
```js
import { User, withPageAuth, getUser } from '@supabase/auth-helpers-nextjs'
interface Profile {
/* ... */
}
import { User, withPageAuth } from '@supabase/auth-helpers-nextjs'
export default function ProtectedPage({
user,
data,
allRepos,
}: {
user: User,
profile: Profile,
allRepos: any,
}) {
return <div>Protected content</div>
return (
<>
<div>Protected content for {user.email}</div>
<p>Data fetched with provider token:</p>
<pre>{JSON.stringify(allRepos, null, 2)}</pre>
<p>user:</p>
<pre>{JSON.stringify(user, null, 2)}</pre>
</>
)
}
export const getServerSideProps = withPageAuth({
redirectTo: '/',
async getServerSideProps(ctx) {
// Retrieve provider_token from cookies
const provider_token = ctx.req.cookies['sb-provider-token']
// Get logged in user's third-party id from metadata
const { user } = await getUser(ctx)
const userId = user?.user_metadata.provider_id
const profile: Profile = await (
await fetch(`https://api.example.com/users/${userId}`, {
method: 'GET',
headers: {
Authorization: `Bearer ${provider_token}`,
},
})
async getServerSideProps(ctx, supabase) {
const {
data: { session },
error,
} = await supabase.auth.getSession()
if (error) {
throw error
}
if (!session) {
return { props: {} }
}
// Retrieve provider_token & logged in user's third-party id from metadata
const { provider_token, user } = session
const userId = user.user_metadata.user_name
const allRepos = await (
await fetch(
`https://api.github.com/search/repositories?q=user:${userId}`,
{
method: 'GET',
headers: {
Authorization: `token ${provider_token}`,
},
}
)
).json()
return { props: { profile } }
return { props: { allRepos, user } }
},
})
```
@@ -355,6 +426,7 @@ export const config = {
</button>
```
- The `supabaseClient` and `supabaseServerClient` have been removed in favor of the `createBrowserSupabaseClient` and `createServerSupabaseClient` methods. This allows you to provide the CLI-generated types to the client:
```js
// client-side
import type { Database } from 'types_db';
@@ -373,12 +445,14 @@ export const config = {
res.status(200).json({ name: user?.name ?? '' })
}
```
- The `UserProvider` has been replaced by the `SessionContextProvider`. Make sure to wrap your `pages/_app.js` componenent with the `SessionContextProvider`. Then, throughout your application you can use the `useSessionContext` hook to get the `session` and the `useSupabaseClient` hook to get an authenticated `supabaseClient`.
- The `useUser` hook now returns the `user` object or `null`.
- Usage with TypeScript: You can pass types that were [generated with the Supabase CLI](/docs/reference/javascript/typescript-support#generating-types) to the Supabase Client to get enhanced type safety and auto completion:
```js
// Creating a new supabase client object:
import { Database } from '../db_types';
import { Database } from '../database.types';
const [supabaseClient] = useState(() =>
createBrowserSupabaseClient<Database>()
@@ -388,7 +462,7 @@ export const config = {
```js
// Retrieving a supabase client object from the SessionContext:
import { useSupabaseClient } from '@supabase/auth-helpers-react';
import { Database } from '../db_types';
import { Database } from '../database.types';
const supabaseClient = useSupabaseClient<Database>();
```
@@ -65,12 +65,14 @@ async function signInWithWorkOS() {
const { data, error } = await supabase.auth.signInWithOAuth(
{
provider: 'workos',
options: {
queryParams: {
connection: '<your_connection>',
organization: '<your_organization',
provider: '<your_provider>',
}
}
},
{
connection: '<your_connection>',
organization: '<your_organization',
provider: '<your_provider>',
}
)
}
```
@@ -0,0 +1,175 @@
---
id: dhiwise
title: 'DhiWise'
description: 'Get started with Supabase and DhiWise. Convert your Figma designs into Flutter apps, store data, and authenticate your users'
---
import select from "/img/guides/integrations/dhiwise/select.png"
import create from "/img/guides/integrations/dhiwise/create.png"
This guide explains how to connect Supabase backend to DhiWise Flutter application quickly.
[DhiWise](https://www.dhiwise.com/) is a Developer tool to convert Figma designs into React and Flutter applications. It lets you quickly integrate Databases and APIs into your React and Flutter Apps.
If you don't have a DhiWise account, create one [here](https://app.dhiwise.com).
DhiWise supports easy Supabase Integration in just five steps.
Let's get started!
## Step 1: SignIn to Supabase
Go to [Supabase](https://supabase.com/), Click `Sign In`, and create a new account by authenticating with **GitHub**. If you already have an account, you will be logged in.
## Step 2: Create a new project in Supabase
Click on `New project` from the Dashboard and select an organization. If you don't have an organization, create one using `+ New organization.`
- Give your Supabase project a `name.`
- Enter a secure `Database Password.`
- Choose the `region` where your app's backend is hosted.
- Click `Create new project.`
![New Project](/img/guides/integrations/dhiwise/newProj.png)
## Step 3: Find the API key and URL
Once your project is created, you can access the API Key and URL string, Or if you already have an account go to your `organization-> app-> settings-> API`.
![auth keys](/img/guides/integrations/dhiwise/authKeys.png)
## Step 4: Integrations
There are two ways you can integrate Supabase into your DhiWise Flutter applications.
### Authentication
You can integrate `Supabase Email/Password SignUp` or `Supabase Email/Password SignIn` on your components.
- Open the screen of your flutter application
- Go to the component on which you want to add authentication
- on the `onClick` method - select `authentication`
- From the list, If you want SignUp - select `SignUp with Email/Password`; otherwise, select `SignIn with Email/Password` from Supabase Auth section
![Auth](/img/guides/integrations/dhiwise/auth.gif)
And that's it. Supabase authentication will be added to the selected component.
After downloading the application source code,
1. Add Supabase URL and Supabase public key inside ***lib/core/utils/initial_bindings*** file.
2. For additional details, refer ***https://supabase.com/docs/guides/with-flutter***
### Working with Data
When you first integrate Supabase in your DhiWise Flutter application, You will be asked to add [Supabase auth key and URL](##step-3-find-the-api-key-and-url). When you add them, all the tables available in your Supabase project will be synced in DhiWise. You can integrate Select and Create queries on your Flutter screen for a particular table in DhiWise.
<h3> Select records </h3>
#### **Step 1:**
Select the screen from the screen list where you want to integrate Supabase.
#### **Step 2:**
Next, go to the view where you want to add Integration, and from the suggestion box for the `onClick` property, choose `Supabase integration,` which will take you to the Integration screen. Where you will be asked to `Enter function name.` Enter the name of your function and click `Submit.`
#### **Step 3:**
After submitting the function name, you will be asked to select a type of Supabase integration. To retrieve data from Supabase, choose `select.`
#### **Step 4:**
Next, select the table from which you want to fetch records from the listed Tables.
#### **Step 5:**
Select the type of integration
| Type | Description |
| --- | --- |
| **Single** | Used to fetch a single record from the database. |
| **Multiple** | Used to fetch multiple records from the database. |
:::info
For Multiple types, you need to set `data limit,` `order by, and `order.`
:::
#### **Step 6:**
You will be redirected to the API Integration screen, where you can set request and response.
For request binding, the below types are supported. Also, Select the operator for comparison before moving forward.
| Type | Description |
| --- | --- |
| **View** | Select any component from your screen. |
| **Constant** | Select a constant you've created in your app. |
| **Get from preference** | Select the key you want to fetch from preference. |
| **Navigation argument** | Select data that's been passed from one screen to another. |
For response binding, the below types are supported.
| Type | Description |
| --- | --- |
| **View** | Select any component from the screen. |
| **Save to preference** | Storing the data to preference. |
#### **Select 7:**
`Handle action` - Select the action you wish to take once the Supabase call has either been accepted successfully or refused due to an error.
Available action for On success and On error are,
1. [Show Alert](https://docs.dhiwise.com/docs/flutter/show-alert)
2. [Navigation](https://docs.dhiwise.com/docs/flutter/navigation)
#### **Step 8:**
Finally, you have added Supabase to your application to fetch records on your screen!
:::tip Example
Suppose you want to fetch records from Supabase and populate the item list on your screen. You can integrate Supabase as discussed above and bind the response with your list view.
:::
<h3> Create records </h3>
#### **Step 1:**
Choose the screen you wish to integrate Supabase for from the list of screens.
#### **Step 2:**
Next, switch to the component you want to add Integration, and on the `onClick` property, choose `Supabase integration,` which will take you to its integration screen, where you will be asked to **Enter function name**, which will be used in generated code. Enter the name for it and click `Submit`
#### **Step 3:**
After submitting the function name, you will be asked to select a type of Supabase integration. For example, to create a record in Supabase, choose `Create.`
#### **Step 4:**
Next, select the table where you want to create a record from the listed Tables.
#### **Step 5:**
If you want to create a Single record, Select **Select**. Otherwise, **Multiple**.
#### **Step 6:**
Now, you will be redirected to the API Integration screen, where you can set request and response.
For request binding, the below types are supported.
| Type | Description |
| --- | --- |
| **View** | Select any component from the screen |
| **Constant** | Select a constant you've created in your app.|
| **Get from preference** | Select the key you want to fetch from preference. |
| **Navigation argument** | Select data that's been passed from one screen to another. |
For response binding, the below types are supported.
| Type | Description |
| --- | --- |
| **View** | Select any component from the screen |
| **Save to preference** | Storing the data to preference. |
#### **Select 7:**
`Handle action` - Select the action you wish to take once the Supabase call has either been accepted successfully or refused due to an error.
Available action for On success and On error are,
1. [Show Alert](https://docs.dhiwise.com/docs/flutter/show-alert)
2. [Navigation](https://docs.dhiwise.com/docs/flutter/navigation)
#### **Step 9:**
Finally, you have added Supabase to your application to create records from your screen data!
## Resources
- [DhiWise Official Website](https://dhiwise.com)
- [DhiWise Documentation](https://docs.dhiwise.com)
@@ -0,0 +1,34 @@
---
id: integrations
title: 'Supabase Marketplace'
description: 'Integrations and Partners'
---
The Supabase Marketplace brings together all the tools you need to extend your Supabase project. This includes:
- [Experts](https://supabase.com/partners/experts) - partners to help you build and support your Supabase project.
- [Integrations](https://supabase.com/partners/integrations) - extend your projects with external Auth, Caching, Hosting, and Low-code tools.
## Build an integration
Supabase provides several integration points:
- The [Postgres connection](/docs/guides/database/connecting-to-postgres). Anything that works with Postgres also works with Supabase projects.
- The [Project REST API](/docs/guides/api#rest-api) & client libraries.
- The [Project GraphQL API](/docs/guides/api#graphql-api).
- The [Platform API](/docs/reference/api).
## List your integration
[Apply to the Partners program](https://supabase.com/partners/integrations#become-a-partner) to list your integration in the Partners marketplace and in the Supabase docs.
Integrations are assessed on the following criteria:
- **Business viability**
While we welcome everyone to built an integration, we only list companies that are deemed to be long-term viable. This includes an official business registration and bank account, meaningful revenue, or Venture Capital backing. We require this criteria to ensure the health of the marketplace.
- **Compliance**
Integrations should not infringe on the Supabase brand/trademark. In short, you cannot use "Supabase" in the name. As the listing appears on the Supabase domain, we don't want to mislead developers into thinking that an integration is an official product.
- **Service Level Agreements**
All listings are required to have their own Terms and Conditions, Privacy Policy, and Acceptable Use Policy, and the company must have resources to meet their SLAs.
- **Maintainability**
All integrations are required to be maintained and functional with Supabase, and the company may be assessed on your ability to remain functional over a long time horizon.
@@ -103,7 +103,7 @@ const channel = supabase.channel('calc-latency', {
})
channel.subscribe(async (status) => {
if (status === 'SUBSCRIBED) {
if (status === 'SUBSCRIBED') {
const begin = performance.now()
await channel.send({
+479 -175
View File
@@ -61,6 +61,7 @@ Now we are going to set up the database schema. We can use the "User Management
or you can just copy/paste the SQL from below and run it yourself.
<Tabs
groupId="language"
defaultValue="dashboard"
values={[
{label: 'Dashboard', value: 'dashboard'},
@@ -85,51 +86,59 @@ or you can just copy/paste the SQL from below and run it yourself.
<TabItem value="sql">
```sql
-- Create a table for public "profiles"
-- Create a table for public profiles
create table profiles (
id uuid references auth.users not null,
id uuid references auth.users not null primary key,
updated_at timestamp with time zone,
username text unique,
full_name text,
avatar_url text,
website text,
primary key (id),
unique(username),
constraint username_length check (char_length(username) >= 3)
);
-- Set up Row Level Security (RLS)
-- See https://supabase.com/docs/guides/auth/row-level-security for more details.
alter table profiles
enable row level security;
alter table profiles enable row level security;
create policy "Public profiles are viewable by everyone." on profiles
for select using (true);
create policy "Public profiles are viewable by everyone."
on profiles for select
using ( true );
create policy "Users can insert their own profile." on profiles
for insert with check (auth.uid() = id);
create policy "Users can insert their own profile."
on profiles for insert
with check ( auth.uid() = id );
create policy "Users can update own profile." on profiles
for update using (auth.uid() = id);
create policy "Users can update own profile."
on profiles for update
using ( auth.uid() = id );
-- Set up Realtime!
begin;
drop publication if exists supabase_realtime;
create publication supabase_realtime;
commit;
alter publication supabase_realtime add table profiles;
-- This trigger automatically creates a profile entry when a new user signs up via Supabase Auth.
-- See https://supabase.com/docs/guides/auth/managing-user-data#using-triggers for more details.
create function public.handle_new_user()
returns trigger as $$
begin
insert into public.profiles (id, full_name, avatar_url)
values (new.id, new.raw_user_meta_data->>'full_name', new.raw_user_meta_data->>'avatar_url');
return new;
end;
$$ language plpgsql security definer;
create trigger on_auth_user_created
after insert on auth.users
for each row execute procedure public.handle_new_user();
-- Set up Storage!
insert into storage.buckets (id, name)
values ('avatars', 'avatars');
values ('avatars', 'avatars');
create policy "Avatar images are publicly accessible."
on storage.objects for select
using ( bucket_id = 'avatars' );
-- Set up access controls for storage.
-- See https://supabase.com/docs/guides/storage#policy-examples for more details.
create policy "Avatar images are publicly accessible." on storage.objects
for select using (bucket_id = 'avatars');
create policy "Anyone can upload an avatar."
on storage.objects for insert
with check ( bucket_id = 'avatars' );
create policy "Anyone can upload an avatar." on storage.objects
for insert with check (bucket_id = 'avatars');
create policy "Anyone can update their own avatar." on storage.objects
for update using ( auth.uid() = owner ) with check (bucket_id = 'avatars');
```
@@ -163,12 +172,32 @@ Let's start building the Next.js app from scratch.
We can use [`create-next-app`](https://nextjs.org/docs/getting-started) to initialize
an app called `supabase-nextjs`:
<Tabs
groupId="language"
defaultValue="js"
values={[
{label: 'JavaScript', value: 'js'},
{label: 'TypeScript', value: 'ts'},
]}>
<TabItem value="js">
```bash
npx create-next-app supabase-nextjs --use-npm
npx create-next-app@latest --use-npm supabase-nextjs
cd supabase-nextjs
```
Then let's install the only additional dependency: [supabase-js](https://github.com/supabase/supabase-js)
</TabItem>
<TabItem value="ts">
```bash
npx create-next-app@latest --ts --use-npm supabase-nextjs
cd supabase-nextjs
```
</TabItem>
</Tabs>
Then install the Supabase client library: [supabase-js](https://github.com/supabase/supabase-js)
```bash
npm install @supabase/supabase-js
@@ -182,93 +211,148 @@ NEXT_PUBLIC_SUPABASE_URL=YOUR_SUPABASE_URL
NEXT_PUBLIC_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY
```
Now that we have the API credentials in place, let's create a helper file to initialize the Supabase client.
These variables will be exposed on the browser, and that's completely fine since we have
[Row Level Security](/docs/guides/auth#row-level-security) enabled on our Database.
```js title="utils/supabaseClient.js"
import { createClient } from '@supabase/supabase-js'
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
export const supabase = createClient(supabaseUrl, supabaseAnonKey)
```
And one optional step is to update the CSS file `styles/globals.css` to make the app look nice.
You can find the full contents of this file [here](https://raw.githubusercontent.com/supabase/examples/main/supabase-js-v2/user-management/nextjs-ts-user-management/styles/globals.css).
You can find the full contents of this file [here](https://raw.githubusercontent.com/supabase/supabase/master/examples/user-management/nextjs-ts-user-management/styles/globals.css).
### Set up a Login component
Let's set up a React component to manage logins and sign ups.
We'll use Magic Links, so users can sign in with their email without using passwords.
#### Supabase Auth Helpers
```jsx title="components/Auth.js"
import { useState } from 'react'
import { supabase } from '../utils/supabaseClient'
Next.js is a highly versatile framework offering pre-rendering at build time (SSG), server-side rendering at request time (SSR), API routes, and middleware edge-functions.
export default function Auth() {
const [loading, setLoading] = useState(false)
const [email, setEmail] = useState('')
It can be challenging to authenticate your users in all these different environments, that's why we've created the [Supabase Auth Helpers](https://supabase.com/docs/guides/auth/auth-helpers/nextjs) to make user management and data fetching within Next.js as easy as possible.
const handleLogin = async (email) => {
try {
setLoading(true)
const { error } = await supabase.auth.signInWithOtp({ email })
if (error) throw error
alert('Check your email for the login link!')
} catch (error) {
alert(error.error_description || error.message)
} finally {
setLoading(false)
}
}
Install the auth helpers for React and Next.js
```bash
npm install @supabase/auth-helpers-react @supabase/auth-helpers-nextjs
```
<Tabs
groupId="language"
defaultValue="js"
values={[
{label: 'JavaScript', value: 'js'},
{label: 'TypeScript', value: 'ts'},
]}>
<TabItem value="js">
Wrap your `pages/_app.js` component with the `SessionContextProvider` component:
```jsx title="pages/_app.js"
import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'
import { SessionContextProvider } from '@supabase/auth-helpers-react'
function MyApp({ Component, pageProps }) {
const router = useRouter()
const [supabaseClient] = useState(() => createBrowserSupabaseClient())
return (
<div className="row flex-center flex">
<div className="col-6 form-widget">
<h1 className="header">Supabase + Next.js</h1>
<p className="description">
Sign in via magic link with your email below
</p>
<div>
<input
className="inputField"
type="email"
placeholder="Your email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div>
<button
onClick={(e) => {
e.preventDefault()
handleLogin(email)
}}
className="button block"
disabled={loading}
>
<span>{loading ? 'Loading' : 'Send magic link'}</span>
</button>
</div>
</div>
<SessionContextProvider
supabaseClient={supabaseClient}
initialSession={pageProps.initialSession}
<Component {...pageProps} />
</SessionContextProvider>
)
}
```
</TabItem>
<TabItem value="ts">
Wrap your `pages/_app.tsx` component with the `SessionContextProvider` component:
```jsx title="pages/_app.tsx"
import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'
// highlight-next-line
import { SessionContextProvider, Session } from '@supabase/auth-helpers-react'
function MyApp({
Component,
pageProps,
}: AppProps<{
// highlight-next-line
initialSession: Session,
}>) {
const [supabaseClient] = useState(() => createBrowserSupabaseClient())
return (
<SessionContextProvider
supabaseClient={supabaseClient}
initialSession={pageProps.initialSession}
>
<Component {...pageProps} />
</SessionContextProvider>
)
}
```
See the [Auth Helpers docs](/docs/guides/auth/auth-helpers/nextjs#usage-with-typescript) for more details on usage with TypeScript.
</TabItem>
</Tabs>
#### Supabase Auth UI
We can use the [Supabase Auth UI](https://supabase.com/docs/guides/auth/auth-helpers/auth-ui) a pre-built React component for authenticating users via OAuth, email, and magic links.
Install the Supabase Auth UI for React
```bash
npm install @supabase/auth-ui-react
```
Add the `Auth` component to your home page
```jsx title="pages/index.js"
import type { NextPage } from 'next'
import { Auth, ThemeSupa } from '@supabase/auth-ui-react'
import { useSession, useSupabaseClient } from '@supabase/auth-helpers-react'
const Home: NextPage = () => {
const session = useSession()
const supabase = useSupabaseClient()
return (
<div className="container" style={{ padding: '50px 0 100px 0' }}>
{!session ? (
<Auth
supabaseClient={supabase}
appearance={{ theme: ThemeSupa }}
theme="dark"
/>
) : (
<p>Account page will go here.</p>
)}
</div>
)
}
export default Home
```
### Account page
After a user is signed in we can allow them to edit their profile details and manage their account.
Let's create a new component for that called `Account.js`.
<Tabs
groupId="language"
defaultValue="js"
values={[
{label: 'JavaScript', value: 'js'},
{label: 'TypeScript', value: 'ts'},
]}>
<TabItem value="js">
```jsx title="components/Account.js"
Let's create a new component for that called `Account.js` within a `components` folder.
```tsx title="components/Account.js"
import { useState, useEffect } from 'react'
import { supabase } from '../utils/supabaseClient'
import { useUser, useSupabaseClient } from '@supabase/auth-helpers-react'
export default function Account({ session }) {
const supabase = useSupabaseClient()
const user = useUser()
const [loading, setLoading] = useState(true)
const [username, setUsername] = useState(null)
const [website, setWebsite] = useState(null)
@@ -278,27 +362,9 @@ export default function Account({ session }) {
getProfile()
}, [session])
async function getCurrentUser() {
const {
data: { session },
error,
} = await supabase.auth.getSession()
if (error) {
throw error
}
if (!session?.user) {
throw new Error('User not logged in')
}
return session.user
}
async function getProfile() {
try {
setLoading(true)
const user = await getCurrentUser()
let { data, error, status } = await supabase
.from('profiles')
@@ -316,7 +382,8 @@ export default function Account({ session }) {
setAvatarUrl(data.avatar_url)
}
} catch (error) {
alert(error.message)
alert('Error loading user data!')
console.log(error)
} finally {
setLoading(false)
}
@@ -325,23 +392,21 @@ export default function Account({ session }) {
async function updateProfile({ username, website, avatar_url }) {
try {
setLoading(true)
const user = await getCurrentUser()
const updates = {
id: user.id,
username,
website,
avatar_url,
updated_at: new Date(),
updated_at: new Date().toISOString(),
}
let { error } = await supabase.from('profiles').upsert(updates)
if (error) {
throw error
}
if (error) throw error
alert('Profile updated!')
} catch (error) {
alert(error.message)
alert('Error updating the data!')
console.log(error)
} finally {
setLoading(false)
}
@@ -354,7 +419,7 @@ export default function Account({ session }) {
<input id="email" type="text" value={session.user.email} disabled />
</div>
<div>
<label htmlFor="username">Name</label>
<label htmlFor="username">Username</label>
<input
id="username"
type="text"
@@ -395,63 +460,176 @@ export default function Account({ session }) {
}
```
</TabItem>
<TabItem value="ts">
Let's create a new component for that called `Account.tsx` within a `components` folder.
```tsx title="components/Account.tsx"
import { useState, useEffect } from 'react'
import {
useUser,
useSupabaseClient,
Session,
} from '@supabase/auth-helpers-react'
import { Database } from '../utils/database.types'
type Profiles = Database['public']['Tables']['profiles']['Row']
export default function Account({ session }: { session: Session }) {
const supabase = useSupabaseClient<Database>()
const user = useUser()
const [loading, setLoading] = useState(true)
const [username, setUsername] = useState<Profiles['username']>(null)
const [website, setWebsite] = useState<Profiles['website']>(null)
const [avatar_url, setAvatarUrl] = useState<Profiles['avatar_url']>(null)
useEffect(() => {
getProfile()
}, [session])
async function getProfile() {
try {
setLoading(true)
if (!user) throw new Error('No user')
let { data, error, status } = await supabase
.from('profiles')
.select(`username, website, avatar_url`)
.eq('id', user.id)
.single()
if (error && status !== 406) {
throw error
}
if (data) {
setUsername(data.username)
setWebsite(data.website)
setAvatarUrl(data.avatar_url)
}
} catch (error) {
alert('Error loading user data!')
console.log(error)
} finally {
setLoading(false)
}
}
async function updateProfile({
username,
website,
avatar_url,
}: {
username: Profiles['username']
website: Profiles['website']
avatar_url: Profiles['avatar_url']
}) {
try {
setLoading(true)
if (!user) throw new Error('No user')
const updates = {
id: user.id,
username,
website,
avatar_url,
updated_at: new Date().toISOString(),
}
let { error } = await supabase.from('profiles').upsert(updates)
if (error) throw error
alert('Profile updated!')
} catch (error) {
alert('Error updating the data!')
console.log(error)
} finally {
setLoading(false)
}
}
return (
<div className="form-widget">
<div>
<label htmlFor="email">Email</label>
<input id="email" type="text" value={session.user.email} disabled />
</div>
<div>
<label htmlFor="username">Username</label>
<input
id="username"
type="text"
value={username || ''}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div>
<label htmlFor="website">Website</label>
<input
id="website"
type="website"
value={website || ''}
onChange={(e) => setWebsite(e.target.value)}
/>
</div>
<div>
<button
className="button primary block"
onClick={() => updateProfile({ username, website, avatar_url })}
disabled={loading}
>
{loading ? 'Loading ...' : 'Update'}
</button>
</div>
<div>
<button
className="button block"
onClick={() => supabase.auth.signOut()}
>
Sign Out
</button>
</div>
</div>
)
}
```
</TabItem>
</Tabs>
### Launch!
Now that we have all the components in place, let's update `pages/index.js`:
```jsx title="pages/index.js"
import { useState, useEffect } from 'react'
import { supabase } from '../utils/supabaseClient'
import Auth from '../components/Auth'
import type { NextPage } from 'next'
import { Auth, ThemeSupa } from '@supabase/auth-ui-react'
import { useSession, useSupabaseClient } from '@supabase/auth-helpers-react'
// highlight-next-line
import Account from '../components/Account'
export default function Home() {
const [isLoading, setIsLoading] = useState(true)
const [session, setSession] = useState(null)
useEffect(() => {
let mounted = true
async function getInitialSession() {
const {
data: { session },
} = await supabase.auth.getSession()
// only update the react state if the component is still mounted
if (mounted) {
if (session) {
setSession(session)
}
setIsLoading(false)
}
}
getInitialSession()
const { subscription } = supabase.auth.onAuthStateChange(
(_event, session) => {
setSession(session)
}
)
return () => {
mounted = false
subscription?.unsubscribe()
}
}, [])
const Home: NextPage = () => {
const session = useSession()
const supabase = useSupabaseClient()
return (
<div className="container" style={{ padding: '50px 0 100px 0' }}>
{!session ? (
<Auth />
<Auth
supabaseClient={supabase}
appearance={{ theme: ThemeSupa }}
theme="dark"
/>
) : (
<Account key={session.user.id} session={session} />
// highlight-next-line
<Account session={session} />
)}
</div>
)
}
export default Home
```
Once that's done, run this in a terminal window:
@@ -462,8 +640,6 @@ npm run dev
And then open the browser to [localhost:3000](http://localhost:3000) and you should see the completed app.
![Supabase User demo](/img/supabase-react-demo.png)
## Bonus: Profile photos
Every Supabase project is configured with [Storage](/docs/guides/storage) for managing large files like
@@ -471,14 +647,23 @@ photos and videos.
### Create an upload widget
Let's create an avatar for the user so that they can upload a profile photo.
We can start by creating a new component:
Let's create an avatar widget for the user so that they can upload a profile photo. We can start by creating a new component:
<Tabs
groupId="language"
defaultValue="js"
values={[
{label: 'JavaScript', value: 'js'},
{label: 'TypeScript', value: 'ts'},
]}>
<TabItem value="js">
```jsx title="components/Avatar.js"
import { useEffect, useState } from 'react'
import { supabase } from '../utils/supabaseClient'
import React, { useEffect, useState } from 'react'
import { useSupabaseClient } from '@supabase/auth-helpers-react'
export default function Avatar({ url, size, onUpload }) {
export default function Avatar({ uid, url, size, onUpload }) {
const supabase = useSupabaseClient()
const [avatarUrl, setAvatarUrl] = useState(null)
const [uploading, setUploading] = useState(false)
@@ -497,11 +682,11 @@ export default function Avatar({ url, size, onUpload }) {
const url = URL.createObjectURL(data)
setAvatarUrl(url)
} catch (error) {
console.log('Error downloading image: ', error.message)
console.log('Error downloading image: ', error)
}
}
async function uploadAvatar(event) {
const uploadAvatar = async (event) => {
try {
setUploading(true)
@@ -511,12 +696,12 @@ export default function Avatar({ url, size, onUpload }) {
const file = event.target.files[0]
const fileExt = file.name.split('.').pop()
const fileName = `${Math.random()}.${fileExt}`
const fileName = `${uid}.${fileExt}`
const filePath = `${fileName}`
let { error: uploadError } = await supabase.storage
.from('avatars')
.upload(filePath, file)
.upload(filePath, file, { upsert: true })
if (uploadError) {
throw uploadError
@@ -524,7 +709,8 @@ export default function Avatar({ url, size, onUpload }) {
onUpload(filePath)
} catch (error) {
alert(error.message)
alert('Error uploading avatar!')
console.log(error)
} finally {
setUploading(false)
}
@@ -566,6 +752,120 @@ export default function Avatar({ url, size, onUpload }) {
}
```
</TabItem>
<TabItem value="ts">
```tsx title="components/Avatar.tsx"
import React, { useEffect, useState } from 'react'
import { useSupabaseClient } from '@supabase/auth-helpers-react'
import { Database } from '../utils/database.types'
type Profiles = Database['public']['Tables']['profiles']['Row']
export default function Avatar({
uid,
url,
size,
onUpload,
}: {
uid: string
url: Profiles['avatar_url']
size: number
onUpload: (url: string) => void
}) {
const supabase = useSupabaseClient<Database>()
const [avatarUrl, setAvatarUrl] = useState<Profiles['avatar_url']>(null)
const [uploading, setUploading] = useState(false)
useEffect(() => {
if (url) downloadImage(url)
}, [url])
async function downloadImage(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) {
console.log('Error downloading image: ', error)
}
}
const uploadAvatar: React.ChangeEventHandler<HTMLInputElement> = async (
event
) => {
try {
setUploading(true)
if (!event.target.files || event.target.files.length === 0) {
throw new Error('You must select an image to upload.')
}
const file = event.target.files[0]
const fileExt = file.name.split('.').pop()
const fileName = `${uid}.${fileExt}`
const filePath = `${fileName}`
let { error: uploadError } = await supabase.storage
.from('avatars')
.upload(filePath, file, { upsert: true })
if (uploadError) {
throw uploadError
}
onUpload(filePath)
} catch (error) {
alert('Error uploading avatar!')
console.log(error)
} finally {
setUploading(false)
}
}
return (
<div>
{avatarUrl ? (
<img
src={avatarUrl}
alt="Avatar"
className="avatar image"
style={{ height: size, width: size }}
/>
) : (
<div
className="avatar no-image"
style={{ height: size, width: size }}
/>
)}
<div style={{ width: size }}>
<label className="button primary block" htmlFor="single">
{uploading ? 'Uploading ...' : 'Upload'}
</label>
<input
style={{
visibility: 'hidden',
position: 'absolute',
}}
type="file"
id="single"
accept="image/*"
onChange={uploadAvatar}
disabled={uploading}
/>
</div>
</div>
)
}
```
</TabItem>
</Tabs>
### Add the new widget
And then we can add the widget to the Account page:
@@ -580,6 +880,7 @@ return (
<div className="form-widget">
{/* Add to the body */}
<Avatar
uid={user.id}
url={avatar_url}
size={150}
onUpload={(url) => {
@@ -596,5 +897,8 @@ return (
At this stage you have a fully functional application!
- See the complete [example on GitHub](https://github.com/supabase/supabase/tree/master/examples/user-management/nextjs-ts-user-management) and deploy it to Vercel.
- Explore the [Auth Helpers for Next.js](https://supabase.com/docs/guides/auth/auth-helpers/nextjs).
- Explore the [pre-built Auth UI for React](https://supabase.com/docs/guides/auth/auth-helpers/auth-ui).
- Got a question? [Ask here](https://github.com/supabase/supabase/discussions).
- Sign in: [app.supabase.com](https://app.supabase.com)
+3 -3
View File
@@ -271,9 +271,9 @@ interface Props {
const Account: Component<Props> = ({ session }) => {
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)
const [username, setUsername] = createSignal<string | null>(null)
const [website, setWebsite] = createSignal<string | null>(null)
const [avatarUrl, setAvatarUrl] = createSignal<string | null>(null)
createEffect(() => {
getProfile()
+199 -298
View File
@@ -24,7 +24,7 @@ By the end of this guide you'll have an app which allows users to login and upda
### GitHub
Whenever you get stuck at any point, take a look at [this repo](https://github.com/zernonia/supabase-vue-3).
Whenever you get stuck at any point, take a look at [this repo](https://github.com/supabase/examples/tree/main/supabase-js-v2/user-management/vue3-user-management).
## Project set up
@@ -182,102 +182,141 @@ const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY
export const supabase = createClient(supabaseUrl, supabaseAnonKey)
```
And one optional step is to update the CSS file `src/assets/main.css` to make the app look nice.
You can find the full contents of this file [here](https://raw.githubusercontent.com/supabase/examples/main/supabase-js-v2/user-management/react-user-management/src/index.css).
```javascript title="src/main.js"
import { createApp } from 'vue'
import App from './App.vue'
import './assets/main.css'
createApp(App).mount('#app')
```
Optionally, update [src/style.css](https://raw.githubusercontent.com/supabase/examples/main/supabase-js-v2/user-management/vue3-user-management/src/style.css) to style the app.
### Set up a Login component
Let's set up a Vue component to manage logins and sign ups. We'll use Magic Links, so users can sign in with their email without using passwords.
```html title="/src/components/Auth.vue"
<script setup>
import { ref } from 'vue'
import { supabase } from '../supabase'
const loading = ref(false)
const email = ref('')
const handleLogin = async () => {
try {
loading.value = true
const { error } = await supabase.auth.signInWithOtp({ email: email.value })
if (error) throw error
alert('Check your email for the login link!')
} catch (error) {
if (error instanceof Error) {
alert(error.message)
}
} finally {
loading.value = false
}
}
</script>
<template>
<form class="row flex-center flex" @submit.prevent="handleLogin">
<div class="col-6 form-widget">
<h1 class="header">Supabase + Vue 3</h1>
<p class="description">Sign in via magic link with your email below</p>
<div>
<input
class="inputField"
type="email"
placeholder="Your email"
v-model="email"
/>
<input class="inputField" type="email" placeholder="Your email" v-model="email" />
</div>
<div>
<input
type="submit"
class="button block"
:value="loading ? 'Loading' : 'Send magic link'"
:disabled="loading"
/>
<input type="submit" class="button block" :value="loading ? 'Loading' : 'Send magic link'"
:disabled="loading" />
</div>
</div>
</form>
</template>
<script>
import { ref } from 'vue'
import { supabase } from '../supabase'
export default {
setup() {
const loading = ref(false)
const email = ref('')
const handleLogin = async () => {
try {
loading.value = true
const { error } = await supabase.auth.signIn({ email: email.value })
if (error) throw error
alert('Check your email for the login link!')
} catch (error) {
alert(error.error_description || error.message)
} finally {
loading.value = false
}
}
return {
loading,
email,
handleLogin,
}
},
}
</script>
```
### User store
To access the user information in other places, we use a reactive store. Create a new file called `store.js` and utilize Vue 3 `reactive` functionalities.
```javascript title="src/store.js"
import { reactive } from 'vue'
export const store = reactive({
user: {},
})
```
### Account page
After a user is signed in we can allow them to edit their profile details and manage their account.
Let's create a new component for that called `Profile.vue`.
Let's create a new component for that called `Account.vue`.
```html title="src/components/Account.vue"
<script setup>
import { supabase } from '../supabase'
import { onMounted, ref, toRefs } from 'vue'
const props = defineProps(['session'])
const { session } = toRefs(props)
const loading = ref(true)
const username = ref('')
const website = ref('')
const avatar_url = ref('')
onMounted(() => {
getProfile()
})
async function getProfile() {
try {
loading.value = true
const { user } = session.value
let { data, error, status } = await supabase
.from('profiles')
.select(`username, website, avatar_url`)
.eq('id', user.id)
.single()
if (error && status !== 406) throw error
if (data) {
username.value = data.username
website.value = data.website
avatar_url.value = data.avatar_url
}
} catch (error) {
alert(error.message)
} finally {
loading.value = false
}
}
async function updateProfile() {
try {
loading.value = true
const { user } = session.value
const updates = {
id: user.id,
username: username.value,
website: website.value,
avatar_url: avatar_url.value,
updated_at: new Date(),
}
let { error } = await supabase.from('profiles').upsert(updates)
if (error) throw error
} catch (error) {
alert(error.message)
} finally {
loading.value = false
}
}
async function signOut() {
try {
loading.value = true
let { error } = await supabase.auth.signOut()
if (error) throw error
} catch (error) {
alert(error.message)
} finally {
loading.value = false
}
}
</script>
```html title="src/components/Profile.vue"
<template>
<form class="form-widget" @submit.prevent="updateProfile">
<div>
<label for="email">Email</label>
<input id="email" type="text" :value="store.user.email" disabled />
<input id="email" type="text" :value="session.user.email" disabled />
</div>
<div>
<label for="username">Name</label>
@@ -289,12 +328,8 @@ Let's create a new component for that called `Profile.vue`.
</div>
<div>
<input
type="submit"
class="button primary block"
:value="loading ? 'Loading ...' : 'Update'"
:disabled="loading"
/>
<input type="submit" class="button primary block" :value="loading ? 'Loading ...' : 'Update'"
:disabled="loading" />
</div>
<div>
@@ -304,98 +339,6 @@ Let's create a new component for that called `Profile.vue`.
</div>
</form>
</template>
<script>
import { supabase } from '../supabase'
import { store } from '../store'
import { onMounted, ref } from 'vue'
export default {
setup() {
const loading = ref(true)
const username = ref('')
const website = ref('')
const avatar_url = ref('')
async function getProfile() {
try {
loading.value = true
store.user = supabase.auth.user()
let { data, error, status } = await supabase
.from('profiles')
.select(`username, website, avatar_url`)
.eq('id', store.user.id)
.single()
if (error && status !== 406) throw error
if (data) {
username.value = data.username
website.value = data.website
avatar_url.value = data.avatar_url
}
} catch (error) {
alert(error.message)
} finally {
loading.value = false
}
}
async function updateProfile() {
try {
loading.value = true
store.user = supabase.auth.user()
const updates = {
id: store.user.id,
username: username.value,
website: website.value,
avatar_url: avatar_url.value,
updated_at: new Date(),
}
let { error } = await supabase.from('profiles').upsert(updates, {
returning: 'minimal', // Don't return the value after inserting
})
if (error) throw error
} catch (error) {
alert(error.message)
} finally {
loading.value = false
}
}
async function signOut() {
try {
loading.value = true
let { error } = await supabase.auth.signOut()
if (error) throw error
} catch (error) {
alert(error.message)
} finally {
loading.value = false
}
}
onMounted(() => {
getProfile()
})
return {
store,
loading,
username,
website,
avatar_url,
updateProfile,
signOut,
}
},
}
</script>
```
### Launch!
@@ -403,37 +346,31 @@ Let's create a new component for that called `Profile.vue`.
Now that we have all the components in place, let's update `App.vue`:
```html title="src/App.vue"
<script setup>
import { onMounted, ref } from 'vue'
import Account from './components/Account.vue'
import Auth from './components/Auth.vue'
import { supabase } from './supabase'
const session = ref()
onMounted(() => {
supabase.auth.getSession().then(({ data }) => {
session.value = data.session
})
supabase.auth.onAuthStateChange((_, _session) => {
session.value = _session
})
})
</script>
<template>
<div class="container" style="padding: 50px 0 100px 0">
<Profile v-if="store.user" />
<Account v-if="session" :session="session" />
<Auth v-else />
</div>
</template>
<script>
import { store } from './store'
import { supabase } from './supabase'
import Auth from './components/Auth.vue'
import Profile from './components/Profile.vue'
export default {
components: {
Auth,
Profile,
},
setup() {
store.user = supabase.auth.user()
supabase.auth.onAuthStateChange((_, session) => {
store.user = session.user
})
return {
store,
}
},
}
</script>
```
Once that's done, run this in a terminal window:
@@ -442,7 +379,7 @@ Once that's done, run this in a terminal window:
npm run dev
```
And then open the browser to [localhost:3000](http://localhost:3000) and you should see the completed app.
And then open the browser to [localhost:5173](http://localhost:5173) and you should see the completed app.
![Supabase Vue 3](/img/supabase-vue-3-demo.png)
@@ -455,132 +392,96 @@ Every Supabase project is configured with [Storage](/docs/guides/storage) for ma
Let's create an avatar for the user so that they can upload a profile photo. We can start by creating a new component:
```html title="src/components/Avatar.vue"
<script setup>
import { ref, toRefs, watch } from 'vue'
import { supabase } from '../supabase'
const prop = defineProps(['path', 'size'])
const { path, size } = toRefs(prop)
const emit = defineEmits(['upload', 'update:path'])
const uploading = ref(false)
const src = ref('')
const files = ref()
const downloadImage = async () => {
try {
const { data, error } = await supabase.storage
.from('avatars')
.download(path.value)
if (error) throw error
src.value = URL.createObjectURL(data)
} catch (error) {
console.error('Error downloading image: ', error.message)
}
}
const uploadAvatar = async (evt) => {
files.value = evt.target.files
try {
uploading.value = true
if (!files.value || files.value.length === 0) {
throw new Error('You must select an image to upload.')
}
const file = files.value[0]
const fileExt = file.name.split('.').pop()
const filePath = `${Math.random()}.${fileExt}`
let { error: uploadError } = await supabase.storage
.from('avatars')
.upload(filePath, file)
if (uploadError) throw uploadError
emit('update:path', filePath)
emit('upload')
} catch (error) {
alert(error.message)
} finally {
uploading.value = false
}
}
watch(path, () => {
if (path.value) downloadImage()
})
</script>
<template>
<div>
<img
v-if="src"
:src="src"
alt="Avatar"
class="avatar image"
:style="{ height: size, width: size }"
/>
<div
v-else
class="avatar no-image"
:style="{ height: size, width: size }"
/>
<img v-if="src" :src="src" alt="Avatar" class="avatar image"
:style="{ height: size + 'em', width: size + 'em' }" />
<div v-else class="avatar no-image" :style="{ height: size + 'em', width: size + 'em' }" />
<div :style="{ width: size }">
<div :style="{ width: size + 'em' }">
<label class="button primary block" for="single">
{{ uploading ? "Uploading ..." : "Upload" }}
</label>
<input
style="visibility: hidden; position: absolute"
type="file"
id="single"
accept="image/*"
@change="uploadAvatar"
:disabled="uploading"
/>
<input style="visibility: hidden; position: absolute" type="file" id="single" accept="image/*"
@change="uploadAvatar" :disabled="uploading" />
</div>
</div>
</template>
<script>
import { ref, toRefs, watch } from 'vue'
import { supabase } from '../supabase'
export default {
props: {
path: String,
},
emits: ['upload', 'update:path'],
setup(prop, { emit }) {
const { path } = toRefs(prop)
const size = ref('10em')
const uploading = ref(false)
const src = ref('')
const files = ref()
const downloadImage = async () => {
try {
const { data, error } = await supabase.storage
.from('avatars')
.download(path.value)
if (error) throw error
src.value = URL.createObjectURL(data)
} catch (error) {
console.error('Error downloading image: ', error.message)
}
}
const uploadAvatar = async (evt) => {
files.value = evt.target.files
try {
uploading.value = true
if (!files.value || files.value.length === 0) {
throw new Error('You must select an image to upload.')
}
const file = files.value[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
emit('update:path', filePath)
emit('upload')
} catch (error) {
alert(error.message)
} finally {
uploading.value = false
}
}
watch(path, () => {
if (path.value) downloadImage()
})
return {
size,
uploading,
src,
files,
uploadAvatar,
}
},
}
</script>
```
### Add the new widget
And then we can add the widget to the Account page:
```html title="src/Profile.vue"
```html title="src/components/Account.vue"
<script>
// Import the new component
import Avatar from './Avatar.vue'
</script>
<template>
<form class="form-widget" @submit.prevent="updateProfile">
<!-- Add to body -->
<Avatar v-model:path="avatar_url" @upload="updateProfile" />
<Avatar v-model:path="avatar_url" @upload="updateProfile" size="10" />
<!-- Other form elements -->
</form>
</template>
<script>
// Import the new component
import Avatar from './Avatar.vue'
//
components: {
Avatar,
}
</script>
```
## Next steps
+44 -16
View File
@@ -215,22 +215,50 @@ const sidebars = {
label: 'Integrations',
collapsed: true,
items: [
'guides/integrations/appsmith',
'guides/integrations/auth0',
'guides/integrations/authsignal',
'guides/integrations/clerk',
'guides/integrations/dashibase',
'guides/integrations/directus',
'guides/integrations/draftbit',
'guides/integrations/pgmustard',
'guides/integrations/plasmic',
'guides/integrations/polyscale',
'guides/integrations/prisma',
'guides/integrations/sequin',
'guides/integrations/snaplet',
'guides/integrations/stytch',
'guides/integrations/supertokens',
'guides/integrations/vercel',
'guides/integrations/integrations',
{
type: 'category',
label: 'Auth',
collapsed: true,
items: [
'guides/integrations/auth0',
'guides/integrations/authsignal',
'guides/integrations/clerk',
'guides/integrations/stytch',
'guides/integrations/supertokens',
],
},
{
type: 'category',
label: 'Caching / Offline-first',
collapsed: true,
items: ['guides/integrations/polyscale'],
},
{
type: 'category',
label: 'Developer Tools',
collapsed: true,
items: [
'guides/integrations/pgmustard',
'guides/integrations/prisma',
'guides/integrations/sequin',
'guides/integrations/snaplet',
'guides/integrations/vercel',
],
},
{
type: 'category',
label: 'Low-code',
collapsed: true,
items: [
'guides/integrations/appsmith',
'guides/integrations/dashibase',
'guides/integrations/dhiwise',
'guides/integrations/directus',
'guides/integrations/draftbit',
'guides/integrations/plasmic',
],
},
],
},
],
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

+1 -5
View File
@@ -49,11 +49,7 @@ const DPA = () => {
("DPA").
</p>
<p>
You can download the latest DPA document through our{' '}
<Link href="https://security.supabase.com/">security portal</Link>, or by
submitting your email here.
</p>
<p>You can download our latest DPA document by submitting your email here.</p>
{formSubmitted ? (
<p className="text-brand-900">
+1 -5
View File
@@ -18,11 +18,7 @@ const SOC2 = () => {
getting certified for SOC2 Type 2 and HIPAA next.
</p>
<p>
You can request for our latest SOC 2 document either through our{' '}
<Link href="https://security.supabase.com/">security portal</Link>, or by submitting
your request here.
</p>
<p>You can request for our latest SOC 2 document by submitting your request here.</p>
<SOC2RequestForm />
</div>
+1 -1
View File
@@ -126,7 +126,7 @@ In addition to internal security reviews, we use various tools to scan our code
<h3 className="text-3xl">Security Portal</h3>
Access more of Supabase’s security on our Security Portal, such as penetration testing and audit reports.
Access more of Supabase’s security information on our Security Portal, such as penetration testing and audit reports.
<Link passHref href="https://security.supabase.com">
<Button type="default" size="medium" as="a" className="no-underline" target="_blank">
+21
View File
@@ -3711,6 +3711,13 @@ pages:
not():
$ref: '@supabase/postgrest-js.PostgrestFilterBuilder.not'
notes: |
not() expects you to use the raw PostgREST syntax for the filter values.
```ts
.not('id', 'in', '(5,6,7)') // Use `()` for `in` filter
.not('arraycol', 'cs', '{"a","b"}') // Use `cs` for `contains()`, `{}` for array values
```
examples:
- name: With `select()`
description: |
@@ -3768,6 +3775,13 @@ pages:
or():
$ref: '@supabase/postgrest-js.PostgrestFilterBuilder.or'
notes: |
or() expects you to use the raw PostgREST syntax for the filter names and values.
```ts
.or('id.in.(5,6,7), arraycol.cs.{"a","b"}') // Use `()` for `in` filter, `{}` for array values and `cs` for `contains()`.
.or('id.in.(5,6,7), arraycol.cd.{"a","b"}') // Use `cd` for `containedBy()`
```
examples:
- name: With `select()`
description: |
@@ -3939,6 +3953,13 @@ pages:
filter():
$ref: '@supabase/postgrest-js.PostgrestFilterBuilder.filter'
notes: |
filter() expects you to use the raw PostgREST syntax for the filter values.
```ts
.filter('id', 'in', '(5,6,7)') // Use `()` for `in` filter
.filter('arraycol', 'cs', '{"a","b"}') // Use `cs` for `contains()`, `{}` for array values
```
examples:
- name: With `select()`
description: |
@@ -16,7 +16,11 @@ const Landing = () => {
const { error } = await auth.signInWithOAuth({
provider: 'github',
options: {
redirectTo: `${process.env.NEXT_PUBLIC_SITE_URL}?auth=true`,
redirectTo: `${
process.env.NEXT_PUBLIC_VERCEL_ENV === 'preview'
? process.env.NEXT_PUBLIC_VERCEL_URL
: process.env.NEXT_PUBLIC_SITE_URL
}?auth=true`,
},
})
if (error) throw error
@@ -78,7 +78,7 @@ const NewProjectPanel: FC<Props> = ({}) => {
</a>
</Link>
<Link href="https://supabase.com/docs/guides/database">
<a>
<a target="_blank" rel="noreferrer">
<Button type="default" icon={<IconExternalLink size={14} />}>
About Database
</Button>
@@ -120,7 +120,7 @@ const NewProjectPanel: FC<Props> = ({}) => {
</a>
</Link>
<Link href="https://supabase.com/docs/guides/auth">
<a>
<a target="_blank" rel="noreferrer">
<Button
className="translate-y-[1px]"
icon={<IconExternalLink size={14} />}
@@ -154,7 +154,7 @@ const NewProjectPanel: FC<Props> = ({}) => {
</a>
</Link>
<Link href="https://supabase.com/docs/guides/storage">
<a>
<a target="_blank" rel="noreferrer">
<Button
className="translate-y-[1px]"
icon={<IconExternalLink size={14} />}
@@ -189,7 +189,7 @@ const NewProjectPanel: FC<Props> = ({}) => {
</a>
</Link>
<Link href="https://supabase.com/docs/guides/functions">
<a>
<a target="_blank" rel="noreferrer">
<Button
className="translate-y-[1px]"
icon={<IconExternalLink size={14} />}
@@ -217,7 +217,7 @@ const NewProjectPanel: FC<Props> = ({}) => {
</div>
<div className="flex items-center space-x-2">
<Link href="https://supabase.com/docs/guides/realtime">
<a>
<a target="_blank" rel="noreferrer">
<Button
className="translate-y-[1px]"
icon={<IconExternalLink size={14} />}
@@ -258,7 +258,7 @@ const NewProjectPanel: FC<Props> = ({}) => {
</a>
</Link>
<Link href="https://supabase.com/docs/guides/api">
<a>
<a target="_blank" rel="noreferrer">
<Button className="translate-y-[1px]" type="default" icon={<IconExternalLink />}>
About APIs
</Button>
@@ -212,7 +212,7 @@ const ColumnEditor: FC<Props> = ({
disabled={!isUndefined(columnFields?.foreignKey)}
description={
<Link href="https://supabase.com/docs/guides/database/tables#data-types">
<a>
<a target="_blank" rel="noreferrer">
<Button
as="span"
type="text"
@@ -319,7 +319,7 @@ const ColumnManagement: FC<Props> = ({
</Button>
)}
<Link href="https://supabase.com/docs/guides/database/tables#data-types">
<a>
<a target="_blank" rel="noreferrer">
<Button
type="text"
className="text-scale-1000 hover:text-scale-1200"
@@ -90,7 +90,7 @@ const NotificationActions: FC<Props> = ({
})}
{changelogLink && (
<Link href={changelogLink}>
<a>
<a target="_blank" rel="noreferrer">
<Button as="span" type="default" icon={<IconExternalLink size={12} strokeWidth={2} />}>
More info
</Button>
@@ -129,7 +129,7 @@ export const formatNotificationText = (
{upgrade.changelog_link && (
<div className="!ml-4">
<Link href={upgrade.changelog_link}>
<a>
<a target="_blank" rel="noreferrer">
<IconExternalLink
className="cursor-pointer text-scale-1000 hover:text-scale-1200 transition"
size={12}
+5 -1
View File
@@ -61,7 +61,11 @@ const UnauthorizedLanding = () => {
auth.signInWithOAuth({
provider: 'github',
options: {
redirectTo: `${process.env.NEXT_PUBLIC_SITE_URL}?${params.toString()}`,
redirectTo: `${
process.env.NEXT_PUBLIC_VERCEL_ENV === 'preview'
? process.env.NEXT_PUBLIC_VERCEL_URL
: process.env.NEXT_PUBLIC_SITE_URL
}?${params.toString()}`,
},
})
}