Update tabs for auth helpers

This commit is contained in:
Joshen Lim committed 2022-11-02 00:08:29 +07:00
1 parent 3d528c45b3
commit 07b9da2836
3 files changed
+189 -274

No files matched your search

@@ -13,14 +13,12 @@ This submodule provides convenience helpers for implementing user authentication
## Install the Next.js helper library
<Tabs
groupId="install"
defaultValue="npm"
values={[
{label: 'npm', value: 'npm'},
{label: 'Yarn', value: 'yarn'},
]}>
<TabItem value="npm">
scrollable
size="small"
type="underlined"
defaultActiveId="npm"
>
<TabPanel id="npm" label="npm">
```sh
npm install @supabase/auth-helpers-nextjs
@@ -37,8 +35,8 @@ Additionally, install the **React Auth Helpers** for components and hooks that c
npm install @supabase/auth-helpers-react
```
</TabItem>
<TabItem value="yarn">
</TabPanel>
<TabPanel id="yarn" label="Yarn">
```sh
yarn add @supabase/auth-helpers-nextjs
@@ -55,7 +53,7 @@ Additionally, install the **React Auth Helpers** for components and hooks that c
yarn add @supabase/auth-helpers-react
```
</TabItem>
</TabPanel>
</Tabs>
## Set up environment variables
@@ -70,12 +68,12 @@ 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">
scrollable
size="small"
type="underlined"
defaultActiveId="js"
>
<TabPanel id="js" label="JavaScript">
Wrap your `pages/_app.js` component with the `SessionContextProvider` component:
@@ -99,8 +97,8 @@ function MyApp({ Component, pageProps }) {
}
```
</TabItem>
<TabItem value="ts">
</TabPanel>
<TabPanel id="ts" label="TypeScript">
Wrap your `pages/_app.tsx` component with the `SessionContextProvider` component:
@@ -130,7 +128,7 @@ function MyApp({
}
```
</TabItem>
</TabPanel>
</Tabs>
You can now determine if a user is authenticated by checking that the `user` object returned by the `useUser()` hook is defined.
@@ -272,13 +270,7 @@ Both `withApiAuth` and `withPageAuth` return a supabase client that you can use
```js
import { User, withPageAuth } from '@supabase/auth-helpers-nextjs'
export default function ProtectedPage({
user,
data,
}: {
user: User,
data: any,
}) {
export default function ProtectedPage({ user, data }: { user: User, data: any }) {
return (
<>
<div>Protected content for {user.email}</div>
@@ -305,13 +297,7 @@ When using third-party auth providers, sessions are initiated with an additional
```js
import { User, withPageAuth } from '@supabase/auth-helpers-nextjs'
export default function ProtectedPage({
user,
allRepos,
}: {
user: User,
allRepos: any,
}) {
export default function ProtectedPage({ user, allRepos }: { user: User, allRepos: any }) {
return (
<>
<div>Protected content for {user.email}</div>
@@ -342,15 +328,12 @@ export const getServerSideProps = withPageAuth({
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}`,
},
}
)
await fetch(`https://api.github.com/search/repositories?q=user:${userId}`, {
method: 'GET',
headers: {
Authorization: `token ${provider_token}`,
},
})
).json()
return { props: { allRepos, user } }
@@ -13,14 +13,12 @@ This submodule provides convenience helpers for implementing user authentication
## Install the Remix helper library
<Tabs
groupId="install"
defaultValue="npm"
values={[
{label: 'npm', value: 'npm'},
{label: 'Yarn', value: 'yarn'},
]}>
<TabItem value="npm">
scrollable
size="small"
type="underlined"
defaultActiveId="npm"
>
<TabPanel id="npm" label="npm">
```sh
npm install @supabase/auth-helpers-remix
@@ -30,8 +28,8 @@ This library supports the following tooling versions:
- Remix: `>=1.7.2`
</TabItem>
<TabItem value="yarn">
</TabPanel>
<TabPanel id="yarn" label="Yarn">
```sh
yarn add @supabase/auth-helpers-remix
@@ -41,7 +39,7 @@ This library supports the following tooling versions:
- Remix: `>=1.7.2`
</TabItem>
</TabPanel>
</Tabs>
## Set up environment variables
@@ -56,12 +54,12 @@ SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY
## Loader
<Tabs
defaultValue="js"
values={[
{label: 'JavaScript', value: 'js'},
{label: 'TypeScript', value: 'ts'},
]}>
<TabItem value="js">
scrollable
size="small"
type="underlined"
defaultActiveId="js"
>
<TabPanel id="js" label="JavaScript">
Loader functions run on the server immediately before the component is rendered. They respond to all GET requests on a route. You can create an authenticated Supabase client by calling the `createServerClient` function and passing it your `SUPABASE_URL`, `SUPABASE_ANON_KEY`, and a `Request` and `Response`.
@@ -95,8 +93,8 @@ export const loader = async ({ request }) => {
> Supabase will set cookie headers to manage the user's auth session, therefore, the `response.headers` must be returned from the `Loader` function.
</TabItem>
<TabItem value="ts">
</TabPanel>
<TabPanel id="ts" label="TypeScript">
Loader functions run on the server immediately before the component is rendered. You can create an authenticated Supabase client by calling the `createServerClient` function and passing it your `SUPABASE_URL`, `SUPABASE_ANON_KEY`, and a `Request` and `Response`.
@@ -104,11 +102,7 @@ Loader functions run on the server immediately before the component is rendered.
import { LoaderFunction, json } from '@remix-run/node' // change this import to whatever runtime you are using
import { createServerClient } from '@supabase/auth-helpers-remix'
export const loader: LoaderFunction = async ({
request,
}: {
request: Request,
}) => {
export const loader: LoaderFunction = async ({ request }: { request: Request }) => {
const response = new Response()
const supabaseClient = createServerClient(
process.env.SUPABASE_URL,
@@ -129,18 +123,18 @@ export const loader: LoaderFunction = async ({
> Supabase will set cookie headers to manage the user's auth session, therefore, the `response.headers` must be returned from the `Loader` function.
</TabItem>
</TabPanel>
</Tabs>
## Action
<Tabs
defaultValue="js"
values={[
{label: 'JavaScript', value: 'js'},
{label: 'TypeScript', value: 'ts'},
]}>
<TabItem value="js">
scrollable
size="small"
type="underlined"
defaultActiveId="js"
>
<TabPanel id="js" label="JavaScript">
Action functions run on the server and respond to HTTP requests to a route, other than GET - POST, PUT, PATCH, DELETE etc. You can create an authenticated Supabase client by calling the `createServerClient` function and passing it your `SUPABASE_URL`, `SUPABASE_ANON_KEY`, and a `Request` and `Response`.
@@ -170,8 +164,8 @@ export const action = async ({ request }) => {
> Supabase will set cookie headers to manage the user's auth session, therefore, the `response.headers` must be returned from the `Action` function.
</TabItem>
<TabItem value="ts">
</TabPanel>
<TabPanel id="ts" label="TypeScript">
Action functions run on the server and respond to HTTP requests to a route, other than GET - POST, PUT, PATCH, DELETE etc. You can create an authenticated Supabase client by calling the `createServerClient` function and passing it your `SUPABASE_URL`, `SUPABASE_ANON_KEY`, and a `Request` and `Response`.
@@ -179,11 +173,7 @@ Action functions run on the server and respond to HTTP requests to a route, othe
import { ActionFunction, json } from '@remix-run/node' // change this import to whatever runtime you are using
import { createServerClient } from '@supabase/auth-helpers-remix'
export const action: ActionFunction = async ({
request,
}: {
request: Request,
}) => {
export const action: ActionFunction = async ({ request }: { request: Request }) => {
const response = new Response()
const supabaseClient = createServerClient(
@@ -205,7 +195,7 @@ export const action: ActionFunction = async ({
> Supabase will set cookie headers to manage the user's auth session, therefore, the `response.headers` must be returned from the `Action` function.
</TabItem>
</TabPanel>
</Tabs>
## Session and User
@@ -229,13 +219,12 @@ const user = session?.user
## Client-side
<Tabs
defaultValue="js"
values={[
{label: 'JavaScript', value: 'js'},
{label: 'TypeScript', value: 'ts'},
]}
scrollable
size="small"
type="underlined"
defaultActiveId="js"
>
<TabItem value="js">
<TabPanel id="js" label="JavaScript">
In order to use the Supabase client in the browser - fetching data in `useEffect` or subscribing to realtime events - we need to do a little more plumbing. Remix does not include a way to make environment variables available to the browser, so we need to pipe them through from a `loader` function in our `root.jsx` route and attach them to the `window`.
@@ -283,10 +272,7 @@ import {
ScrollRestoration,
useLoaderData,
} from '@remix-run/react'
import {
createBrowserClient,
createServerClient,
} from '@supabase/auth-helpers-remix'
import { createBrowserClient, createServerClient } from '@supabase/auth-helpers-remix'
export const meta = () => ({
charset: 'utf-8',
@@ -331,9 +317,8 @@ export default function App() {
Now we can call `createBrowserClient` in our components to fetch data client-side, or subscribe to realtime events - changes in the database.
</TabItem>
<TabItem value="ts">
</TabPanel>
<TabPanel id="ts" label="TypeScript">
In order to use the Supabase client in the browser - fetching data in `useEffect` or subscribing to realtime events - we need to do a little more plumbing. Remix does not include a way to make environment variables available to the browser, so we need to pipe them through from a `loader` function in our `root.tsx` route and attach them to the `window`.
@@ -381,10 +366,7 @@ import {
ScrollRestoration,
useLoaderData,
} from '@remix-run/react'
import {
createBrowserClient,
createServerClient,
} from '@supabase/auth-helpers-remix'
import { createBrowserClient, createServerClient } from '@supabase/auth-helpers-remix'
export const meta: MetaFunction = () => ({
charset: 'utf-8',
@@ -429,7 +411,7 @@ export default function App() {
Now we can call `createBrowserClient` in our components to fetch data client-side, or subscribe to realtime events - changes in the database.
</TabItem>
</TabPanel>
</Tabs>
## Authentication
@@ -449,12 +431,12 @@ Given this Remix `<Form />` component.
### Signing Up
<Tabs
defaultValue="js"
values={[
{label: 'JavaScript', value: 'js'},
{label: 'TypeScript', value: 'ts'},
]}>
<TabItem value="js">
scrollable
size="small"
type="underlined"
defaultActiveId="js"
>
<TabPanel id="js" label="JavaScript">
Any of the [supported authentication strategies from `supabase-js`](https://supabase.com/docs/reference/javascript/auth-signup) will work server-side. This is how you would handle simple `email` and `password` auth.
@@ -485,9 +467,8 @@ export const action = async ({ request }) => {
}
```
</TabItem>
<TabItem value="ts">
</TabPanel>
<TabPanel id="ts" label="TypeScript">
Any of the [supported authentication strategies from `supabase-js`](https://supabase.com/docs/reference/javascript/auth-signup) will work server-side. This is how you would handle simple `email` and `password` auth.
@@ -522,18 +503,18 @@ export const action: ActionFunction = async ({
};
```
</TabItem>
</TabPanel>
</Tabs>
### Login
<Tabs
defaultValue="js"
values={[
{label: 'JavaScript', value: 'js'},
{label: 'TypeScript', value: 'ts'},
]}>
<TabItem value="js">
scrollable
size="small"
type="underlined"
defaultActiveId="js"
>
<TabPanel id="js" label="JavaScript">
Any of the [supported authentication strategies from `supabase-js`](https://supabase.com/docs/reference/javascript/auth-signinwithpassword) will work server-side. This is how you would handle simple `email` and `password` auth.
@@ -564,9 +545,8 @@ export const action = async ({ request }) => {
}
```
</TabItem>
<TabItem value="ts">
</TabPanel>
<TabPanel id="ts" label="TypeScript">
Any of the [supported authentication strategies from `supabase-js`](https://supabase.com/docs/reference/javascript/auth-signinwithpassword) will work server-side. This is how you would handle simple `email` and `password` auth.
@@ -601,18 +581,18 @@ export const action: ActionFunction = async ({
};
```
</TabItem>
</TabPanel>
</Tabs>
### Logout
<Tabs
defaultValue="js"
values={[
{label: 'JavaScript', value: 'js'},
{label: 'TypeScript', value: 'ts'},
]}>
<TabItem value="js">
scrollable
size="small"
type="underlined"
defaultActiveId="js"
>
<TabPanel id="js" label="JavaScript">
```jsx
export const action = async ({ request }) => {
@@ -638,9 +618,8 @@ export const action = async ({ request }) => {
}
```
</TabItem>
<TabItem value="ts">
</TabPanel>
<TabPanel id="ts" label="TypeScript">
```jsx
export const action: ActionFunction = async ({
@@ -670,7 +649,7 @@ export const action: ActionFunction = async ({
};
```
</TabItem>
</TabPanel>
</Tabs>
## Subscribe to realtime events
@@ -689,13 +668,9 @@ export default function SubscribeToRealtime() {
)
const channel = supabaseClient
.channel('test')
.on(
'postgres_changes',
{ event: 'INSERT', schema: 'public', table: 'test' },
(payload) => {
setData((data) => [...data, payload.new])
}
)
.on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'test' }, (payload) => {
setData((data) => [...data, payload.new])
})
.subscribe()
return () => {
@@ -15,28 +15,25 @@ This submodule provides convenience helpers for implementing user authentication
This library supports Node.js `^16.15.0`.
<Tabs
groupId="install"
defaultValue="npm"
values={[
{label: 'npm', value: 'npm'},
{label: 'Yarn', value: 'yarn'},
]}>
<TabItem value="npm">
scrollable
size="small"
type="underlined"
defaultActiveId="npm"
>
<TabPanel id="npm" label="npm">
```sh
npm install @supabase/auth-helpers-sveltekit
```
</TabItem>
<TabItem value="yarn">
</TabPanel>
<TabPanel id="yarn" label="Yarn">
```sh
yarn add @supabase/auth-helpers-sveltekit
```
</TabItem>
</TabPanel>
</Tabs>
## Getting Started
@@ -63,14 +60,10 @@ import { env } from '$env/dynamic/public'
// or use the static env
// import { PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY } from '$env/static/public';
export const supabaseClient = createClient(
env.PUBLIC_SUPABASE_URL,
env.PUBLIC_SUPABASE_ANON_KEY,
{
persistSession: false,
autoRefreshToken: false,
}
)
export const supabaseClient = createClient(env.PUBLIC_SUPABASE_URL, env.PUBLIC_SUPABASE_ANON_KEY, {
persistSession: false,
autoRefreshToken: false,
})
setupSupabaseHelpers({
supabaseClient,
@@ -378,13 +371,9 @@ export const actions: Actions = {
const email = formData.get('email') as string
const password = formData.get('password') as string
const { data, error } = await supabaseClient.auth.api.signInWithEmail(
email,
password,
{
redirectTo: `${url.origin}/logging-in`,
}
)
const { data, error } = await supabaseClient.auth.api.signInWithEmail(email, password, {
redirectTo: `${url.origin}/logging-in`,
})
if (error || !data) {
if (error?.status === 400) {
@@ -470,13 +459,12 @@ The environment variable prefix is now `PUBLIC_` instead of `VITE_` (e.g., `VITE
### Set up the Supabase client {#migration-set-up-supabase-client}
<Tabs
groupId="version"
values={[
{label: '0.6.11 and below', value: 'older'},
{label: '0.7.0', value: 'latest'},
]}>
<TabItem value="older">
scrollable
size="small"
type="underlined"
defaultActiveId="older"
>
<TabPanel id="older" label="0.6.11 and below">
```js title="src/lib/db.ts"
import { createSupabaseClient } from '@supabase/auth-helpers-sveltekit';
@@ -489,9 +477,8 @@ const { supabaseClient } = createSupabaseClient(
export { supabaseClient };
```
</TabItem>
<TabItem value="latest">
</TabPanel>
<TabPanel id="latest" label="0.7.0">
```js title="src/lib/db.ts"
import { createClient } from '@supabase/supabase-js'
@@ -502,14 +489,10 @@ import { env } from '$env/dynamic/public'
// import { PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY } from '$env/static/public';
export const supabaseClient = createClient(
env.PUBLIC_SUPABASE_URL,
env.PUBLIC_SUPABASE_ANON_KEY,
{
persistSession: false,
autoRefreshToken: false,
}
)
export const supabaseClient = createClient(env.PUBLIC_SUPABASE_URL, env.PUBLIC_SUPABASE_ANON_KEY, {
persistSession: false,
autoRefreshToken: false,
})
setupSupabaseHelpers({
supabaseClient,
@@ -519,19 +502,18 @@ setupSupabaseHelpers({
})
```
</TabItem>
</TabPanel>
</Tabs>
### Initialize the client {#migration-initialize-client}
<Tabs
groupId="version"
values={[
{label: '0.6.11 and below', value: 'older'},
{label: '0.7.0', value: 'latest'},
]}>
<TabItem value="older">
scrollable
size="small"
type="underlined"
defaultActiveId="older"
>
<TabPanel id="older" label="0.6.11 and below">
```html title="src/routes/__layout.svelte"
<script>
@@ -545,9 +527,8 @@ setupSupabaseHelpers({
</SupaAuthHelper>
```
</TabItem>
<TabItem value="latest">
</TabPanel>
<TabPanel id="latest" label="0.7.0">
The `@supabase/auth-helpers-svelte` library is no longer required as the `@supabase/auth-helpers-sveltekit` library handles all the client-side code.
@@ -569,19 +550,18 @@ The `@supabase/auth-helpers-svelte` library is no longer required as the `@supab
<slot />
```
</TabItem>
</TabPanel>
</Tabs>
### Set up hooks {#migration-set-up-hooks}
<Tabs
groupId="version"
values={[
{label: '0.6.11 and below', value: 'older'},
{label: '0.7.0', value: 'latest'},
]}>
<TabItem value="older">
scrollable
size="small"
type="underlined"
defaultActiveId="older"
>
<TabPanel id="older" label="0.6.11 and below">
```ts title="src/hooks.ts"
import { handleAuth } from '@supabase/auth-helpers-sveltekit'
@@ -600,9 +580,8 @@ export const getSession: GetSession = async (event) => {
}
```
</TabItem>
<TabItem value="latest">
</TabPanel>
<TabPanel id="latest" label="0.7.0">
```ts title="src/hooks.server.ts"
// make sure the supabase instance is initialized on the server
@@ -625,19 +604,18 @@ import { sequence } from '@sveltejs/kit/hooks'
export const handle = sequence(auth(), yourHandler)
```
</TabItem>
</TabPanel>
</Tabs>
### Typings {#migration-typings}
<Tabs
groupId="version"
values={[
{label: '0.6.11 and below', value: 'older'},
{label: '0.7.0', value: 'latest'},
]}>
<TabItem value="older">
scrollable
size="small"
type="underlined"
defaultActiveId="older"
>
<TabPanel id="older" label="0.6.11 and below">
```ts title="src/app.d.ts"
/// <reference types="@sveltejs/kit" />
@@ -660,9 +638,8 @@ declare namespace App {
}
```
</TabItem>
<TabItem value="latest">
</TabPanel>
<TabPanel id="latest" label="0.7.0">
```ts title="src/app.d.ts"
/// <reference types="@sveltejs/kit" />
@@ -684,19 +661,18 @@ declare namespace App {
}
```
</TabItem>
</TabPanel>
</Tabs>
### Check the user on the client
<Tabs
groupId="version"
values={[
{label: '0.6.11 and below', value: 'older'},
{label: '0.7.0', value: 'latest'},
]}>
<TabItem value="older">
scrollable
size="small"
type="underlined"
defaultActiveId="older"
>
<TabPanel id="older" label="0.6.11 and below">
```html title="src/routes/index.svelte"
<script>
@@ -711,9 +687,8 @@ declare namespace App {
{/if}
```
</TabItem>
<TabItem value="latest">
</TabPanel>
<TabPanel id="latest" label="0.7.0">
```html title="src/routes/+page.svelte"
<script>
@@ -728,26 +703,22 @@ declare namespace App {
{/if}
```
</TabItem>
</TabPanel>
</Tabs>
### withPageAuth
<Tabs
groupId="version"
values={[
{label: '0.6.11 and below', value: 'older'},
{label: '0.7.0', value: 'latest'},
]}>
<TabItem value="older">
scrollable
size="small"
type="underlined"
defaultActiveId="older"
>
<TabPanel id="older" label="0.6.11 and below">
```html title="src/routes/protected-route.svelte"
<script lang="ts" context="module">
import {
supabaseServerClient,
withPageAuth,
} from '@supabase/auth-helpers-sveltekit'
import { supabaseServerClient, withPageAuth } from '@supabase/auth-helpers-sveltekit'
import type { Load } from './__types/protected-page'
export const load: Load = async ({ session }) =>
@@ -757,9 +728,7 @@ declare namespace App {
user: session.user,
},
async () => {
const { data } = await supabaseServerClient(session.accessToken)
.from('test')
.select('*')
const { data } = await supabaseServerClient(session.accessToken).from('test').select('*')
return { props: { data, user: session.user } }
}
)
@@ -777,9 +746,8 @@ declare namespace App {
<pre>{JSON.stringify(user, null, 2)}</pre>
```
</TabItem>
<TabItem value="latest">
</TabPanel>
<TabPanel id="latest" label="0.7.0">
```html title="src/routes/protected-route/+page.svelte"
<script lang="ts">
@@ -801,39 +769,31 @@ import { withAuth } from '@supabase/auth-helpers-sveltekit'
import { redirect } from '@sveltejs/kit'
import type { PageLoad } from './$types'
export const load: PageLoad = withAuth(
async ({ session, getSupabaseClient }) => {
if (!session.user) {
throw redirect(303, '/')
}
const { data: tableData } = await getSupabaseClient()
.from('test')
.select('*')
return { tableData, user: session.user }
export const load: PageLoad = withAuth(async ({ session, getSupabaseClient }) => {
if (!session.user) {
throw redirect(303, '/')
}
)
const { data: tableData } = await getSupabaseClient().from('test').select('*')
return { tableData, user: session.user }
})
```
</TabItem>
</TabPanel>
</Tabs>
### withApiAuth
<Tabs
groupId="version"
values={[
{label: '0.6.11 and below', value: 'older'},
{label: '0.7.0', value: 'latest'},
]}>
<TabItem value="older">
scrollable
size="small"
type="underlined"
defaultActiveId="older"
>
<TabPanel id="older" label="0.6.11 and below">
```ts title="src/routes/api/protected-route.ts"
import {
supabaseServerClient,
withApiAuth,
} from '@supabase/auth-helpers-sveltekit'
import { supabaseServerClient, withApiAuth } from '@supabase/auth-helpers-sveltekit'
import type { RequestHandler } from './__types/protected-route'
interface TestTable {
@@ -848,9 +808,7 @@ interface GetOutput {
export const GET: RequestHandler<GetOutput> = async ({ locals, request }) =>
withApiAuth({ user: locals.user }, async () => {
// Run queries with RLS on the server
const { data } = await supabaseServerClient(request)
.from('test')
.select('*')
const { data } = await supabaseServerClient(request).from('test').select('*')
return {
status: 200,
@@ -859,9 +817,8 @@ export const GET: RequestHandler<GetOutput> = async ({ locals, request }) =>
})
```
</TabItem>
<TabItem value="latest">
</TabPanel>
<TabPanel id="latest" label="0.7.0">
```ts title="src/routes/api/protected-route/+server.ts"
import type { RequestHandler } from './$types';
@@ -886,7 +843,7 @@ export const GET: RequestHandler = withAuth(async ({ session, getSupabaseClient
);
```
</TabItem>
</TabPanel>
</Tabs>
## Additional Links