Skip to content

feat: Supabase-js V2 upgrade #293

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 23 commits into from
Oct 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ on:
push:
branches:
- main
- next
workflow_dispatch:

jobs:
Expand Down
118 changes: 118 additions & 0 deletions examples/nextjs/db_types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
export type Json =
| string
| number
| boolean
| null
| { [key: string]: Json }
| Json[];

export interface Database {
public: {
Tables: {
partners: {
Row: {
id: number;
slug: string;
type: Database['public']['Enums']['partner_type'];
category: string;
developer: string;
title: string;
description: string;
logo: string;
images: string[];
video: string;
overview: string;
website: string;
docs: string;
approved: boolean;
};
Insert: {
id?: number;
slug?: string;
type?: Database['public']['Enums']['partner_type'];
category?: string;
developer?: string;
title?: string;
description?: string;
logo?: string;
images?: string[];
video?: string;
overview?: string;
website?: string;
docs?: string;
approved?: boolean;
};
Update: {
id?: number;
slug?: string;
type?: Database['public']['Enums']['partner_type'];
category?: string;
developer?: string;
title?: string;
description?: string;
logo?: string;
images?: string[];
video?: string;
overview?: string;
website?: string;
docs?: string;
approved?: boolean;
};
};
partner_contacts: {
Row: {
id: number;
type: Database['public']['Enums']['partner_type'];
company: string;
country: string;
details?: string;
email: string;
first: string;
last: string;
phone?: string;
size?: number;
title?: string;
website: string;
};
Insert: {
id?: number;
type?: Database['public']['Enums']['partner_type'];
company?: string;
country?: string;
details?: string;
email?: string;
first?: string;
last?: string;
phone?: string;
size?: number;
title?: string;
website?: string;
};
Update: {
id?: number;
type?: Database['public']['Enums']['partner_type'];
company?: string;
country?: string;
details?: string;
email?: string;
first?: string;
last?: string;
phone?: string;
size?: number;
title?: string;
website?: string;
};
};
};
Views: {};
Functions: {
derive_label_sort_from_label: {
Args: { label: string };
Returns: string;
};
};
Enums: {
partner_type: 'technology' | 'expert';
};
};
}
8 changes: 5 additions & 3 deletions examples/nextjs/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { withMiddlewareAuth } from '@supabase/auth-helpers-nextjs';

export const middleware = withMiddlewareAuth({
redirectTo: '/login',
redirectTo: '/',
authGuard: {
isPermitted: async (user) => user.email?.endsWith('@example.com') ?? false,
isPermitted: async (user) => {
return user.email?.endsWith('@gmail.com') ?? false;
},
redirectTo: '/insufficient-permissions'
}
});

export const config = {
matcher: ['/middleware-protected/:path*']
matcher: '/middleware-protected'
};
1 change: 1 addition & 0 deletions examples/nextjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"dependencies": {
"@supabase/auth-helpers-nextjs": "workspace:*",
"@supabase/auth-helpers-react": "workspace:*",
"@supabase/auth-ui-react": "^0.1.8",
"next": "^12.2.5",
"react": "17.0.2",
"react-dom": "17.0.2"
Expand Down
34 changes: 25 additions & 9 deletions examples/nextjs/pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,33 @@
import '../styles/globals.css';
import { useRouter } from 'next/router';
import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs';
import { SessionContextProvider } from '@supabase/auth-helpers-react';
import type { AppProps } from 'next/app';
import { UserProvider } from '@supabase/auth-helpers-react';
import { supabaseClient } from '@supabase/auth-helpers-nextjs';
import Link from 'next/link';
import { useState } from 'react';
import { Database } from '../db_types';
import '../styles/globals.css';

function MyApp({ Component, pageProps }: AppProps) {
const router = useRouter();
const [supabaseClient] = useState(() =>
createBrowserSupabaseClient<Database>()
);

return (
<UserProvider supabaseClient={supabaseClient}>
<Link href="/api/auth/logout">
<a>Logout</a>
</Link>
<SessionContextProvider
supabaseClient={supabaseClient}
initialSession={pageProps.initialSession}
>
<button
onClick={async () => {
await supabaseClient.auth.signOut();
router.push('/');
}}
>
Logout
</button>

<Component {...pageProps} />
</UserProvider>
</SessionContextProvider>
);
}

Expand Down
6 changes: 0 additions & 6 deletions examples/nextjs/pages/api/auth/[...supabase].ts

This file was deleted.

11 changes: 0 additions & 11 deletions examples/nextjs/pages/api/force-refresh.ts

This file was deleted.

11 changes: 3 additions & 8 deletions examples/nextjs/pages/api/protected-route.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
// pages/api/protected-route.ts
import {
withApiAuth,
supabaseServerClient
} from '@supabase/auth-helpers-nextjs';
import { withApiAuth } from '@supabase/auth-helpers-nextjs';

export default withApiAuth(async function ProtectedRoute(req, res) {
export default withApiAuth(async function ProtectedRoute(req, res, supabase) {
// Run queries with RLS on the server
const { data } = await supabaseServerClient({ req, res })
.from('test')
.select('*');
const { data } = await supabase.from('test').select('*');
res.json(data);
});
30 changes: 18 additions & 12 deletions examples/nextjs/pages/github-provider-token.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
// pages/protected-page.js
import {
User,
withPageAuth,
getUser,
getProviderToken
} from '@supabase/auth-helpers-nextjs';
import { User, withPageAuth } from '@supabase/auth-helpers-nextjs';
import Link from 'next/link';

export default function ProtectedPage({
Expand All @@ -31,12 +26,22 @@ export default function ProtectedPage({

export const getServerSideProps = withPageAuth({
redirectTo: '/',
async getServerSideProps(ctx) {
// Retrieve provider_token from cookies
const provider_token = getProviderToken(ctx);
// Get logged in user's third-party id from metadata
const { user } = await getUser(ctx);
const userId = user?.user_metadata.user_name;
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://github.com/api/search/repositories?q=user:${userId}`,
Expand All @@ -48,6 +53,7 @@ export const getServerSideProps = withPageAuth({
}
)
).json();

return { props: { allRepos, user } };
}
});
40 changes: 28 additions & 12 deletions examples/nextjs/pages/index.tsx
Original file line number Diff line number Diff line change
@@ -1,36 +1,52 @@
import { useUser } from '@supabase/auth-helpers-react';
import { supabaseClient } from '@supabase/auth-helpers-nextjs';
import {
useSessionContext,
useSupabaseClient
} from '@supabase/auth-helpers-react';
import { Auth, ThemeSupa } from '@supabase/auth-ui-react';
import type { NextPage } from 'next';
import Link from 'next/link';
import { useEffect, useState } from 'react';
import { Database } from '../db_types';

const LoginPage: NextPage = () => {
const { isLoading, user, error } = useUser();
const { isLoading, session, error } = useSessionContext();
const supabaseClient = useSupabaseClient<Database>();

const [data, setData] = useState(null);

useEffect(() => {
async function loadData() {
const { data } = await supabaseClient.from('test').select('*').single();
setData(data);
}
if (user) loadData();
}, [user]);

if (!user)
loadData();
}, [supabaseClient]);

if (!session)
return (
<>
{error && <p>{error.message}</p>}
{isLoading ? <h1>Loading...</h1> : <h1>Loaded!</h1>}
<button
onClick={() => {
supabaseClient.auth.signIn(
{ provider: 'github' },
{ redirectTo: 'http://localhost:3000'}
);
supabaseClient.auth.signInWithOAuth({
provider: 'github',
options: { scopes: 'repo', redirectTo: 'http://localhost:3000' }
});
}}
>
Login with github
</button>
<Auth
redirectTo="http://localhost:3000/"
appearance={{ theme: ThemeSupa }}
// view="update_password"
supabaseClient={supabaseClient}
providers={['google', 'github']}
// scopes={{github: 'repo'}} // TODO: enable scopes in Auth component.
socialLayout="horizontal"
/>
</>
);

Expand All @@ -41,15 +57,15 @@ const LoginPage: NextPage = () => {
<Link href="/protected-page">supabaseServerClient</Link>] |{' '}
<button
onClick={() =>
supabaseClient.auth.update({ data: { test5: 'updated' } })
supabaseClient.auth.updateUser({ data: { test5: 'updated' } })
}
>
Update
</button>
</p>
{isLoading ? <h1>Loading...</h1> : <h1>Loaded!</h1>}
<p>user:</p>
<pre>{JSON.stringify(user, null, 2)}</pre>
<pre>{JSON.stringify(session, null, 2)}</pre>
<p>client-side data fetching with RLS</p>
<pre>{JSON.stringify(data, null, 2)}</pre>
</>
Expand Down
19 changes: 10 additions & 9 deletions examples/nextjs/pages/profile.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
// pages/profile.js
import { withPageAuth, User } from '@supabase/auth-helpers-nextjs';
import { withPageAuth } from '@supabase/auth-helpers-nextjs';
import { useSessionContext } from '@supabase/auth-helpers-react';
import Link from 'next/link';

export default function Profile({
user,
error
}: {
user: User;
error: string;
}) {
if (user)
export default function Profile() {
const { error, session } = useSessionContext();

if (session?.user) {
const { user } = session;

return (
<>
<p>
Expand All @@ -20,6 +19,8 @@ export default function Profile({
<pre>{JSON.stringify(user, null, 2)}</pre>
</>
);
}

return <p>{error}</p>;
}

Expand Down
Loading