The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
runs prettier
jscyo438f22f42d7b
diff --git a/web/docs/guides/integrations/supertokens.mdx b/web/docs/guides/integrations/supertokens.mdxindex 44413be87d6..e36c6d96cf9 100644--- a/web/docs/guides/integrations/supertokens.mdx+++ b/web/docs/guides/integrations/supertokens.mdx@@ -1,7 +1,7 @@---id: supertokenstitle: 'SuperTokens'-description: "Create a Next.js application secured by SuperTokens and PostgreSQL Row Level Security."+description: 'Create a Next.js application secured by SuperTokens and PostgreSQL Row Level Security.'---[SuperTokens](https://www.supertokens.com) is an open source authentication solution which provides many stratergies for authenticating and managing users. You can use the managed service for easy setup or you can self host the solution to have complete control over your data.@@ -11,23 +11,25 @@ In this guide we will build a simple web application using SuperTokens, SupabaseWe will use Supabase to store and authorize access to user data. Supabase makes it simple to setup Row Level Security(RLS) policies which ensure users can only read and write data that belongs to them.### Demo App-You can find a demo app using SuperTokens, Supabase and Nexts.js on [Github](https://github.com/supertokens/supertokens-auth-react/tree/master/examples/with-supabase)+You can find a demo app using SuperTokens, Supabase and Nexts.js on [Github](https://github.com/supertokens/supertokens-auth-react/tree/master/examples/with-supabase)## Step 1: Create a new Supabase project+From your [Supabase dashboard](https://app.supabase.io/), click `New project`.Enter a `Name` for your Supabase project.Enter a secure `Database Password`.-Select the same `Region` you host your app's backend in.+Select the same `Region` you host your app's backend in.Click `Create new project`.## Step 2: Creating tables in Supabase+From the sidebar menu in the [Supabase dashboard](https://app.supabase.io/), click `Table editor`, then `New table`.Enter `users` as the `Name` field.@@ -45,11 +47,10 @@ Click `Save` to create the new table.-## Step 3: Setup your Next.js App with SuperTokens.Since the scope of this guide is limited to the intergration between SuperTokens and Supabase, you can refer to the SuperTokens website to see [how to setup your Next.js app with SuperTokens](https://supertokens.com/docs/thirdpartyemailpassword/nextjs/about).-+Once you finish setting up your app, you will be greeted with the following screen@@ -58,9 +59,9 @@ Once you finish setting up your app, you will be greeted with the following screIn our Nextjs app when a user signs up, we want to store the user's email in Supabase. We would then retrieve this email from Supabase and display it on our frontend.-To use the Supabase client to query the database we will need to create a JWT signed with your Supabase app's signing secret. This JWT will also need to contain the user's userId so Supabase knows an authenticated user is making the request.+To use the Supabase client to query the database we will need to create a JWT signed with your Supabase app's signing secret. This JWT will also need to contain the user's userId so Supabase knows an authenticated user is making the request.-To create this flow we will need to modify SuperTokens so that, when a user signs up or signs in, a JWT signed with Supabase's signing secret is created and attached to the user's session. Attaching the JWT to the user's session will allow us to retrieve the Supabase JWT on the frontend and backend (post session verification), using which we can query Supabase.+To create this flow we will need to modify SuperTokens so that, when a user signs up or signs in, a JWT signed with Supabase's signing secret is created and attached to the user's session. Attaching the JWT to the user's session will allow us to retrieve the Supabase JWT on the frontend and backend (post session verification), using which we can query Supabase.We want to create a Supabase JWT when we are creating a SuperTokens' session. This can be done by overriding the `createNewSession` function in your backend config.@@ -120,26 +121,29 @@ As seen above, we will be using the `jsonwebtoken` library to create a JWT signeWe will be storing this token in the `accessTokenPayload` which will essentially allow us to access the `supabase_token` on the frontend and backend whilst the user is logged in.-## Step 5: Creating a Supabase client+## Step 5: Creating a Supabase clientCreate a new file called `utils/supabase.ts` and add the following:```ts// utils/supabase.ts-import { createClient } from "@supabase/supabase-js";+import { createClient } from '@supabase/supabase-js'const getSupabase = (access_token) => {- const supabase = createClient(process.env.NEXT_PUBLIC_SUPABASE_URL, process.env.NEXT_PUBLIC_SUPABASE_KEY);+ const supabase = createClient(+ process.env.NEXT_PUBLIC_SUPABASE_URL,+ process.env.NEXT_PUBLIC_SUPABASE_KEY+ )- supabase.auth.session = () => ({- access_token- });+ supabase.auth.session = () => ({+ access_token,+ })- return supabase;-};+ return supabase+}-export { getSupabase };+export { getSupabase }```This will be our client for talking to Supabase. We can pass it an `access_token` and it will be attached to our request. This `access_token` is the same as the `supabase_token` we had created earlier.@@ -253,81 +257,79 @@ Now that our backend is setup we can modify our frontend to retrieve the user's```tsx// pages/index.tsx-import React, { useState, useEffect } from "react";-import Head from "next/head";-import styles from "../styles/Home.module.css";-import ThirdPartyEmailPassword from "supertokens-auth-react/recipe/thirdpartyemailpassword";-import dynamic from "next/dynamic";-import { useSessionContext } from "supertokens-auth-react/recipe/session";-import { getSupabase } from "../utils/supabase";+import React, { useState, useEffect } from 'react'+import Head from 'next/head'+import styles from '../styles/Home.module.css'+import ThirdPartyEmailPassword from 'supertokens-auth-react/recipe/thirdpartyemailpassword'+import dynamic from 'next/dynamic'+import { useSessionContext } from 'supertokens-auth-react/recipe/session'+import { getSupabase } from '../utils/supabase'const ThirdPartyEmailPasswordAuthWrapper = dynamic(- new Promise<typeof ThirdPartyEmailPassword.ThirdPartyEmailPasswordAuth>((res) =>- res(ThirdPartyEmailPassword.ThirdPartyEmailPasswordAuth)- ),- { ssr: false }-);+ new Promise<typeof ThirdPartyEmailPassword.ThirdPartyEmailPasswordAuth>((res) =>+ res(ThirdPartyEmailPassword.ThirdPartyEmailPasswordAuth)+ ),+ { ssr: false }+)export default function Home() {- return (- // We will wrap the ProtectedPage component with the ThirdPartyEmailPasswordAuthWrapper so only an- // authenticated user can access it. This will also allow us to access the users session information- // within the component.- <ThirdPartyEmailPasswordAuthWrapper>- <ProtectedPage />- </ThirdPartyEmailPasswordAuthWrapper>- );+ return (+ // We will wrap the ProtectedPage component with the ThirdPartyEmailPasswordAuthWrapper so only an+ // authenticated user can access it. This will also allow us to access the users session information+ // within the component.+ <ThirdPartyEmailPasswordAuthWrapper>+ <ProtectedPage />+ </ThirdPartyEmailPasswordAuthWrapper>+ )}function ProtectedPage() {- // retrieve the authenticated user's accessTokenPayload and userId from the sessionContext- const { accessTokenPayload, userId } = useSessionContext();-- const [userEmail, setEmail] = useState("");- useEffect(() => {- async function getUserEmail() {- // retrieve the supabase client who's JWT contains users userId, this will be- // used by supabase to check that the user can only access table entries which contain their own userId- const supabase = getSupabase(accessTokenPayload.supabase_token);-- // retrieve the user's name from the users table whose email matches the email in the JWT- const { data } = await supabase.from("users").select("email").eq("user_id", userId);-- if (data.length > 0) {- setEmail(data[0].email);- }- }- getUserEmail();- }, []);-- return (- <div className={styles.container}>- <Head>- <title>SuperTokens 💫</title>- <link rel="icon" href="/favicon.ico" />- </Head>-- <main className={styles.main}>- <p className={styles.description}>- You are authenticated with SuperTokens! (UserId: {userId})- <br />- Your email retrieved from Supabase: {userEmail}- </p>- </main>- </div>- );+ // retrieve the authenticated user's accessTokenPayload and userId from the sessionContext+ const { accessTokenPayload, userId } = useSessionContext()++ const [userEmail, setEmail] = useState('')+ useEffect(() => {+ async function getUserEmail() {+ // retrieve the supabase client who's JWT contains users userId, this will be+ // used by supabase to check that the user can only access table entries which contain their own userId+ const supabase = getSupabase(accessTokenPayload.supabase_token)++ // retrieve the user's name from the users table whose email matches the email in the JWT+ const { data } = await supabase.from('users').select('email').eq('user_id', userId)++ if (data.length > 0) {+ setEmail(data[0].email)+ }+ }+ getUserEmail()+ }, [])++ return (+ <div className={styles.container}>+ <Head>+ <title>SuperTokens 💫</title>+ <link rel="icon" href="/favicon.ico" />+ </Head>++ <main className={styles.main}>+ <p className={styles.description}>+ You are authenticated with SuperTokens! (UserId: {userId})+ <br />+ Your email retrieved from Supabase: {userEmail}+ </p>+ </main>+ </div>+ )}-```As seen above we will be using SuperTokens `useSessionContext` hook to retrieve the authenticated user's `userId` and `accessTokenPayload`. Using React's `useEffect` hook we can use the Supabase client to retrieve the user's email from Supabase using the JWT retrieved from the user's `accessTokenPayload` and their `userId`.-## Step 8: Create Policies to enforce Row Level Security for Select and Insert requestsTo enforce Row Level Security for the `Users` table we will need to create policies for Select and Insert requests.-These polices will retrieve the userId from the JWT and check if it matches the userId in the Supabase table+These polices will retrieve the userId from the JWT and check if it matches the userId in the Supabase tableTo do this we will need a PostgreSQL function to extract the userId from the JWT.@@ -381,7 +383,6 @@ Similar to the previous policy we are calling the PostgreSQL function we createdClick `Review` and then `Save policy`.-## Step 9: Test your changesYou can now sign up and you should see the following screen:@@ -397,5 +398,3 @@ If you navigate to your table you should see a new row with the user's `user_id`- [SuperTokens](https://supertokens.com/) official website.- [SuperTokens community](https://supertokens.com/discord).- [SuperTokens documentation](https://supertokens.com/docs/guides).--