diff --git a/apps/reference/docs/about.md b/apps/reference/docs/about.md deleted file mode 100644 index 5aebf386295..00000000000 --- a/apps/reference/docs/about.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -id: about -title: Introduction -description: 'What is Supabase?' -slug: / -hide_table_of_contents: true ---- - -Guides here diff --git a/apps/reference/docs/about.mdx b/apps/reference/docs/about.mdx new file mode 100755 index 00000000000..13ed94d8911 --- /dev/null +++ b/apps/reference/docs/about.mdx @@ -0,0 +1,155 @@ +--- +id: about +title: Introduction +description: 'What is Supabase?' +slug: / +hide_table_of_contents: true +--- + +import ThemedImage from '@theme/ThemedImage' +import AngularLogo from '@site/static/img/libraries/angular-icon.svg' +import ExpoLogo from '@site/static/img/libraries/expo-icon.svg' +import DartLogo from '@site/static/img/libraries/dart-icon.svg' +import JavascriptLogo from '@site/static/img/libraries/javascript-icon.svg' +import NextjsDarkLogo from '@site/static/img/libraries/nextjs-dark-icon.svg' +import NextjsLightLogo from '@site/static/img/libraries/nextjs-light-icon.svg' +import ReactLogo from '@site/static/img/libraries/react-icon.svg' +import SolidJSLogo from '@site/static/img/libraries/solidjs-icon.svg' +import RedwoodJsLogo from '@site/static/img/libraries/redwoodjs-icon.svg' +import SvelteLogo from '@site/static/img/libraries/svelte-icon.svg' +import VuejsLogo from '@site/static/img/libraries/vuejs-icon.svg' + +import useBaseUrl from '@docusaurus/useBaseUrl' +import Link from '@docusaurus/Link' +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' +const frameworks = [ + { + name: 'Angular', + logo: AngularLogo, + href: '/docs/guides/with-angular', + }, + { + name: 'Expo', + logo: ExpoLogo, + href: 'https://github.com/supabase/supabase/tree/master/examples/todo-list/expo-todo-list', + }, + { name: 'Flutter', logo: DartLogo, href: '/docs/guides/with-flutter' }, + { + name: 'JavaScript', + logo: JavascriptLogo, + href: 'https://github.com/supabase/supabase/tree/master/examples/auth/javascript-auth', + }, + { + name: 'Next.js', + themed: true, + logo: { + dark: '/img/libraries/nextjs-dark-icon.svg', + light: '/img/libraries/nextjs-light-icon.svg', + }, + href: '/docs/guides/with-nextjs', + }, + { name: 'React', logo: ReactLogo, href: '/docs/guides/with-react' }, + { name: 'RedwoodJS', logo: RedwoodJsLogo, href: '/docs/guides/with-redwoodjs' }, + { name: 'SolidJS', logo: SolidJSLogo, href: '/docs/guides/with-solidjs' }, + { name: 'Svelte', logo: SvelteLogo, href: '/docs/guides/with-svelte' }, + { name: 'Vue', logo: VuejsLogo, href: '/docs/guides/with-vue-3' }, +] + +Supabase is an open source Firebase alternative providing all the backend features you need to build a product. +You can use it completely, or just the features you need. + +[Start a project](https://app.supabase.com) with the hosted platform or learn how to [host Supabase](/docs/guides/hosting/overview) yourself. + +## Learn about features + +
+
+ {/* Database */} +
+ +
+

Database

+

A dedicated, scalable Postgres database.

+
+ +
+ {/* API */} +
+ +
+

Auto-generated APIs

+

Instantly generate APIs for your database.

+
+ +
+ {/* Functions */} +
+ +
+

Edge Functions

+

Server-side functions, distributed globally.

+
+ +
+ {/* Auth */} +
+ +
+

Auth

+

User management with Row Level Security.

+
+ +
+ {/* Storage */} +
+ +
+

File Storage

+

Store, organize, and serve large files.

+
+ +
+ {/* Observability */} +
+ +
+

Observability

+

Monitor and debug your infrastucture.

+
+ +
+ {/* */} +
+
+ +## Start with a framework + +Supabase is just Postgres, which makes it compatible with a large number of tools and frameworks. + +
+
+ {frameworks.map((x) => ( +
+ +
+ {x.logo && !x.themed ? ( + + ) : ( + + )} +

{x.name}

+
+ +
+ ))} +
+
diff --git a/apps/reference/docs/architecture.mdx b/apps/reference/docs/architecture.mdx new file mode 100755 index 00000000000..c65037a76f0 --- /dev/null +++ b/apps/reference/docs/architecture.mdx @@ -0,0 +1,17 @@ +--- +id: architecture +title: Architecture +description: 'Supabase design and architecture' +# hide_table_of_contents: true +--- + +Supabase is open source. Wherever possible, we use and support existing tools rather than developing from scratch. +We choose open source tools which are scalable and we make them simple to use. + +![Supabase Architecture](/img/supabase-architecture.png) + +Supabase is not a 1-to-1 mapping of Firebase. While we are building many of the features that Firebase offers, we are not going about it the same way. + +Our technological choices are quite different from Firebase. Everything we use is open source. Wherever possible, we use and support existing tools rather than developing from scratch. + +Most notably, we use Postgres rather than a NoSQL store. This choice was deliberate. We believe that no other database offers the scalability and functionality required to compete with Firebase. diff --git a/apps/reference/docs/company/aup.md b/apps/reference/docs/company/aup.md new file mode 100644 index 00000000000..5e02cae3a8a --- /dev/null +++ b/apps/reference/docs/company/aup.md @@ -0,0 +1,52 @@ +--- +id: aup +title: Acceptable Use Policy +--- + +`Last Modified: 15 April 2021` + +This Acceptable Use Policy (this “Policy”) describes prohibited uses of the web services offered by Supabase, Inc. and its affiliates (the “Services”) and the website located at https://supabase.com (the “Supabase Site”). The examples described in this Policy are not exhaustive. We may modify this Policy at any time by posting a revised version on the Supabase Site. By using the Services or accessing the Supabase Site, you agree to the latest version of this Policy. If you violate the Policy or authorize or help others to do so, we may suspend or terminate your use of the Services. + +## No Illegal, Harmful, or Offensive Use or Content + +You may not use, or encourage, promote, facilitate or instruct others to use, the Services or Supabase Site for any illegal, harmful, fraudulent, infringing or offensive use, or to transmit, store, display, distribute or otherwise make available content that is illegal, harmful, fraudulent, infringing or offensive. Prohibited activities or content include: + +- **Illegal, Harmful or Fraudulent Activities.** Any activities that are illegal, that violate the rights of others, or that may be harmful to others, our operations or reputation, including disseminating, promoting or facilitating child pornography, offering or disseminating fraudulent goods, services, schemes, or promotions, make-money-fast schemes, ponzi and pyramid schemes, phishing, or pharming. +- **Infringing Content.** Content that infringes or misappropriates the intellectual property or proprietary rights of others. +- **Offensive Content.** Content that is defamatory, obscene, abusive, invasive of privacy, or otherwise objectionable, including content that constitutes child pornography, relates to bestiality, or depicts non-consensual sex acts. +- **Harmful Content.** Content or other computer technology that may damage, interfere with, surreptitiously intercept, or expropriate any system, program, or data, including viruses, Trojan horses, worms, time bombs, or cancelbots. +- **Platform compliance.** Any activities that are deemed unacceptable by the platforms used by the Supabase Site and Services, including [AWS](https://aws.amazon.com/aup/). + +## No Security Violations + +You may not use the Services to violate the security or integrity of any network, computer or communications system, software application, or network or computing device (each, a “System”). Prohibited activities include: + +- **Unauthorized Access.** Accessing or using any System without permission, including attempting to probe, scan, or test the vulnerability of a System or to breach any security or authentication measures used by a System. +- **Interception.** Monitoring of data or traffic on a System without permission. +- **Falsification of Origin.** Forging TCP-IP packet headers, e-mail headers, or any part of a message describing its origin or route. The legitimate use of aliases and anonymous remailers is not prohibited by this provision. + +## No Network Abuse + +You may not make network connections to any users, hosts, or networks unless you have permission to communicate with them. Prohibited activities include: + +- **Monitoring or Crawling.** Monitoring or crawling of a System that impairs or disrupts the System being monitored or crawled. +- **Denial of Service (DoS).** Inundating a target with communications requests so the target either cannot respond to legitimate traffic or responds so slowly that it becomes ineffective. +- **Intentional Interference.** Interfering with the proper functioning of any System, including any deliberate attempt to overload a system by mail bombing, news bombing, broadcast attacks, or flooding techniques. +- **Operation of Certain Network Services.** Operating network services like open proxies, open mail relays, or open recursive domain name servers. +- **Avoiding System Restrictions.** Using manual or electronic means to avoid any use limitations placed on a System, such as access and storage restrictions. + +## No E-Mail or Other Message Abuse + +You will not distribute, publish, send, or facilitate the sending of unsolicited mass e-mail or other messages, promotions, advertising, or solicitations (like “spam”), including commercial advertising and informational announcements. You will not alter or obscure mail headers or assume a sender’s identity without the sender’s explicit permission. You will not collect replies to messages sent from another internet service provider if those messages violate this Policy or the acceptable use policy of that provider. + +## Our Monitoring and Enforcement + +We reserve the right, but do not assume the obligation, to investigate any violation of this Policy or misuse of the Services or Supabase Site. We may: + +- investigate violations of this Policy or misuse of the Services or Supabase Site; or +- remove, disable access to, or modify any content or resource that violates this Policy or any other agreement we have with you for use of the Services or the Supabase Site. + +We may report any activity that we suspect violates any law or regulation to appropriate law enforcement officials, regulators, or other appropriate third parties. Our reporting may include disclosing appropriate customer information. We also may cooperate with appropriate law enforcement agencies, regulators, or other appropriate third parties to help with the investigation and prosecution of illegal conduct by providing network and systems information related to alleged violations of this Policy. +Reporting of Violations of this Policy + +If you become aware of any violation of this Policy, you will immediately notify us and provide us with assistance, as requested, to stop or remedy the violation. To report any violation of this Policy, please contact us at support@supabase.io. diff --git a/apps/reference/docs/company/privacy.md b/apps/reference/docs/company/privacy.md new file mode 100644 index 00000000000..2d5e6ab833b --- /dev/null +++ b/apps/reference/docs/company/privacy.md @@ -0,0 +1,292 @@ +--- +id: privacy +title: Privacy Policy +--- + +`Last modified: 27 March 2021` + +Thank you for your interest in Supabase, Inc., ("**_Supabase_**," "**_we_**", "**_our_**" or "**_us_**"). Supabase provides a suite of open source tools, stitched together to build a seamless developer experience. This Privacy Notice explains how information about you, that directly identifies you, or that makes you identifiable ("**_personal information_**") is collected, used and disclosed by Supabase in connection with our website at [supabase.com](https://supabase.com) (the "**_Site_**") and our services offered in connection with the Site (collectively with the Site, the "**_Service_**"). + +We may also provide you with additional privacy notices or disclosures where the scope of the inquiry, request, or personal information we require falls outside the scope of this Privacy Notice. In that case, the additional Privacy Notice or disclosures will govern how we may process the information you provide at that time. Please note that this Privacy Notice does not cover or apply to our processing of information about our employees or contractors. + +This Policy explains how we use your personal information when we act as a data controller. As far as you use our Service as a natural person, we are the controller of your personal information. We are responsible for, and control, the processing of your personal information. + +Wherever our customers use our Service to submit, manage, or otherwise use content relating to our customers’ end users ("**_Customer Data_**") during the provision of our Service, we have contractually committed ourselves to only process such information on behalf and under the instruction of the respective customer, who is the data controller. This Privacy Notice does not apply to such processing and we recommend you read the Privacy Notice of the respective customer, if their processing concerns your personal information. + +## Region-specific Disclosures + +- **California - Your California Privacy Rights:** If you are a California resident, California Civil Code Section 1798.83 permits you to request information regarding the disclosure of personal information to third parties for their direct marketing purposes during the immediately preceding calendar year. Note we do not share your personal information with third parties for their own marketing purposes. +- **Nevada:** Chapter 603A of the Nevada Revised Statutes permits a Nevada resident to opt out of future sales of certain covered information that a website operator has collected or will collect about the resident. Note we do not sell your personal information within the meaning of Chapter 603A. However, if you would still like to submit such a request, please contact us at support@supabase.io. +- **European Economic Area, United Kingdom or Switzerland:** If you are located in the European Economic Area ("**_EEA_**"), United Kingdom or Switzerland, or otherwise engage with Supabase’s European operations, please see the **Privacy Disclosures for the European Economic Area, United Kingdom and Switzerland** for additional European-specific privacy disclosures, including what constitutes your personal information, the lawful bases we rely on to process your personal information, how we use cookies when you access our Sites from the EEA, UK or Switzerland and your rights in respect of your personal information. + +**Note for International Visitors:** Personal information may be transferred to, stored and processed in a country other than the one in which it was collected. For example, the Sites are primarily hosted in and provided from the United States. Please note the country to which personal data is transferred may not provide the same level of protection for personal information as the country from which it was transferred. + +## 1. Information we collect and our use + +We collect personal information in connection with your visits to and use of the Service. This collection includes information that you provide in connection with the Service, information from third parties, and information that is collected automatically such as through the use of cookies and other technologies. + +### Information That You Provide + +We collect personal information from you. The categories of information we collect can include: + +- **_Registration information._** We collect personal and/or business information that you provide when you register for an account at the Site. This information may include your name, email address, GitHub username. We use this information to administer your account, provide you with the relevant services and information, communicate with you regarding your account, the Site and for customer support purposes. +- **_Information collected through the Use of the Service._** After registration, you may create, upload or transmit files, documents, videos, images, data or information as part of your use of the Service (collectively, "**_User Content_**"). User Content and any information contained in the User Content, including personal information you may have included, is stored and collected as part of the Service. You have full control of the information included in the User Content. +- **_Payment information._** If you make a purchase or payment on the Site, such as for a subscription, we collect transactional information provided in connection with your purchase or payment. Please note that we use third party payment processors, including Stripe, to process payments made to us. As such, we do not retain any personally identifiable financial information such as credit card numbers. Rather, all such information is provided directly by you to our third-party processor. The payment processor’s use of your personal information is governed by their privacy notice. To view Stripe’s privacy notice, please visit: . +- **_Communications._** If you communicate with us through any paper or electronic form, we may collect your name, email address, mailing address, phone number, or any other personal information you choose to provide to us. We use this information to investigate and respond to your inquiries, and to communicate with you, to enhance the services we offer to our users and to manage and grow our organization. If you register for our newsletters or updates, we may communicate with you by email. To unsubscribe from promotional messages, please follow the instructions within our messages and review the **Control Over Your Information** section below. If you become a contributor, we may also collect your GitHub name and feature you on our website. +- **_Inquiries and Feedback._** If you contact us, we will collect the information that you provide us, such as your contact information and the contents of your communication with us. + +You are free to choose which personal information you want to provide to us or whether you want to provide us with personal information at all. However, some information, such as your name, address, payment transaction information, and information on your requested Services may be necessary for the performance of our contractual obligations. + +### Information from Third Party Sources + +We may receive personal information about you from our business partners and service providers and combine this information with other data we collect from you. The third-parties may include website and service operators, payment processors, marketing partners, and shipping providers. The information may include contact information, demographic information, information about your communications and related activities, and information about your orders. We may use this information to administer and facilitate our services, your orders and our marketing activities. + +- **_Single Sign-On._** We use single sign-on ("**SSO**") such as GitHub to allow a user to authenticate their account using one set of login information. We will have access to certain information from those third parties in accordance with the authorization procedures determined by those third parties, including, for example, your name, username, email address, language preference, and profile picture. We use this information to operate, maintain, and provide to you the features and functionality of the Service. We may also send you service-related emails or messages (e.g., account verification, purchase confirmation, customer support, changes or updates to features of the Site, technical and security notices). +- **_Social Media._** When you interact with our Site through various social media, such as when you click on the social media icon on the Site, follow us on a social media site, or post a comment to one of our pages, we may receive information from the social network such as your profile information, profile picture, gender, user name, user ID associated with your social media account, age range, language, country, and any other information you permit the social network to share with third parties. The data we receive is dependent upon your privacy settings with the social network. We use this information to operate, maintain, and provide to you the features and functionality of the Service, as well as to communicate directly with you, such as to send you email messages about products and services that may be of interest to you. +- **_Employment Applications._** If you apply for employment, we collect your contact and demographic information, educational and work history, employment interests, information obtained during interviews and any other information you choose to provide. We use the information provided to evaluate your candidacy for employment, to communicate with you during the application process and to facilitate the onboarding process. +- **_Information from Other Sources._** We may obtain information from other sources, including through third-party information providers, our shareholders, customers, or through transactions such as mergers and acquisitions. We may combine this information with other information we collect from or about you. In these cases, our Privacy Notice governs the handling of the combined personal information. We use this information to operate, maintain, and provide to you the features and functionality of the Service, as well as to communicate directly with you, such as to send you email messages about products and services that may be of interest to you. + +### Other Uses of Personal Information + +In addition to the uses described above, we may collect and use personal information for the following purposes: + +- For our business activities, including to operate the Service and to provide you with the features and functionality of the Service; +- To communicate with you and respond to your requests, such as to respond to your questions, contact you about changes to the Service, and communicate about account related matters; +- For marketing and advertising purposes, such as to market to you or offer you with information and updates on our products or services we think that you may be interested in. While we may use your personal information in this manner, please note that we do not use User Content to serve you ads, and we will never share User Content with any third parties for marketing or advertising purposes, unless you have explicitly submitted it to us for that purpose; +- For analytics and research purposes; +- To enforce our **Terms of Service**, to resolve disputes, to carry out our obligations and enforce our rights, and to protect our business interests and the interests and rights of third parties; +- To comply with contractual and legal obligations and requirements; +- To fulfill any other purpose for which you provide personal information; and +- For any other lawful purpose, or other purpose that you consent to. + +## 2. How we share personal information + +We may share your personal information in the instances described below. For further information on your choices regarding your information, see **Control Over Your Information**. + +- We may share your personal information with third-party service providers or business partners who help us deliver or improve our Site or services, or who perform services on our behalf, which are subject to reasonable confidentiality terms, and may include processing payments, providing web hosting services, or providing analytics. +- Third parties as required by law or subpoena or if we reasonably believe that such action is necessary to (a) comply with the law and the reasonable requests of law enforcement; (b) to enforce our **Terms of Service** or other agreements or to protect the security or integrity of the Supabase services, including to prevent harm or financial loss, or in connection with preventing fraud or illegal activity; and/or (c) to exercise or protect the rights, property, or personal safety of Supabase, our Customers, visitors, or others. +- We may share with other companies and brands owned or controlled by Supabase, and other companies owned by or under common ownership as Supabase. These companies will use your personal information in the same way as we can under this Privacy Notice. +- We may transfer any information we collect in the event we sell or transfer all or a portion of our business or assets (including any shares in the company) or any portion or combination of our products, services, businesses and/or assets. Should such a transaction occur (whether a divestiture, merger, acquisition, bankruptcy, dissolution, reorganization, liquidation, or similar transaction or proceeding), we will use reasonable efforts to ensure that any transferred information is treated in a manner consistent with this Privacy Notice. +- We may disclose your information publicly or with another third party with your prior authorization. +- With others in an aggregated or otherwise anonymized form that does not reasonably identify you directly as an individual. + +## 3. Control over your information + +### Email Communications + +From time to time, we may send you emails regarding updates to our Service, products or services, notices about our organization, or information about products/services we offer (or promotional offers from third parties) that we think may be of interest to you. If you wish to unsubscribe from such emails, simply click the "unsubscribe link" provided at the bottom of the email communication. Note that you cannot unsubscribe from certain services-related email communications (e.g., account verification, confirmations of transactions, technical or legal notices). + +### Modifying Account Information + +If you have an online account with us, you have the ability to modify certain information in your account (e.g., your contact information) through the account options provided on the Site. If there is personal information in your User Content, you can use the features and functionality of the Service to edit or delete the personal information or User Content. Not all personal information is maintained in a format that you can access or change. If you would like to request access to, or correction or deletion of personal information, you may send your request to us at the email provided below. We will review your request and may require you to provide additional information to identify yourself, but we do not promise that we will be able to satisfy your request. + +## 4. How We Use Cookies and Other Tracking Technology to Collect Information + +We, and our third-party partners, automatically collect certain types of usage information when you visit our Site, read our emails, or otherwise engage with us.  We typically collect this information through a variety of tracking technologies, including cookies, web beacons, embedded scripts, location-identifying technologies, file information, and similar technology (collectively, "**tracking technologies**"). + +We, and our third-party partners, use tracking technologies to automatically collect usage and device information, such as: + +- Information about your device and its software, such as your IP address, browser type, Internet service provider, device type/model/manufacturer, operating system, date and time stamp, and a unique ID that allows us to uniquely identify your browser or your account (including, for example, a persistent device identifier), and other such information. +- When you access our sites from a mobile device, we may collect unique identification numbers associated with your device or our mobile application mobile carrier, device type, model and manufacturer, mobile device operating system brand and model, and depending on your mobile device settings, we may be able to approximate a device’s location by analyzing other information, like an IP address. +- Information about the way you access and use our services, for example, the site from which you came and the site to which you are going when you leave our services, the pages you visit, the links you click, whether you open emails or click the links contained in emails, whether you access the services from multiple devices, and other actions you take on the Sites. + +We use the data collected through tracking technologies to:  (a) remember information so that you will not have to re-enter it during your visit or the next time you visit the site; (b) provide custom content and information; (c) identify you across multiple devices; (d) provide and monitor the effectiveness of our services; (e) monitor aggregate metrics such as total number of visitors, traffic, usage, and demographic patterns on our Site; (f) diagnose or fix technology problems; and (g) to provide, plan for, and enhance our services. + +**Note we do not engage in online targeted advertising.** + +**Cookies and Other Tracking Technologies Opt-Out.** Depending on your browser or mobile device, you may be able to set your browser to delete or notify you of cookies and other tracking technology by actively managing the settings on your browser or mobile device. + +If you would prefer not to accept cookies, most browsers will allow you to: (i) change your browser settings to notify you when you receive a cookie, which lets you choose whether or not to accept it; (ii) disable existing cookies; or (iii) set your browser to automatically reject cookies. Please note that doing so may negatively impact your experience using the sites, as some features and services on our sites may not work properly. Depending on your mobile device and operating system, you may not be able to delete or block all cookies. You may also set your e-mail options to prevent the automatic downloading of images that may contain technologies that would allow us to know whether you have accessed our e-mail and performed certain functions with it. + +## 5. Data Retention and Security + +We will retain your personal information for the length of time needed to fulfill the purposes outlined in this Privacy Notice, unless a longer retention period is required or permitted by law. We store data on servers in the U.S. or any other country in which Supabase or its affiliates, subsidiaries, agents or contractors maintain facilities. If you are located in the European Union or other regions with laws governing data collection and use that may differ from U.S. law, please note that your personal information may be transferred to a country and jurisdiction that does not have the same data protection laws as your jurisdiction. When you register for use with Supabase you have the option of where you store your information and we will not transfer it without providing information to you in advance. + +Supabase cares about the security of your information and uses commercially reasonable physical, technical and organizational measures designed to preserve the integrity and security of all information we collect. However, no security system is impenetrable, and we cannot guarantee the security of our systems 100%. In the event that any information under our control is compromised as a result of a breach of security, we will take reasonable steps to investigate the situation and where appropriate, notify those individuals whose information may have been compromised and take other steps, in accordance with any applicable laws and regulations. + +## 6. Links to Third-Party Websites and Services + +For your convenience, our Site may provide links to third-party websites or services that we do not own or operate. We are not responsible for the practices employed by any websites or services linked to or from the services, including the information or content contained within them. Your browsing and interaction on any other website or service are subject to the applicable third party’s rules and policies, not ours. If you are using a third-party website or service, you do so at your own risk. We encourage you to review the privacy policies of any site or service before providing any personal information. + +## 7. Children’s Privacy + +Our services are not intended for children under the age of 13. We do not knowingly solicit or collect personal information from children under the age of 13. If we learn that any personal information has been collected inadvertently from a child under 13, we will delete the information as soon as possible. If you believe that we might have collected information from a child under 13, please contact us at privacy@supabase.io. + +## 8. Changes to Privacy Notice + +We reserve the right to change this Privacy Notice from time to time in our sole discretion. We will notify you about material changes in the way we treat personal data by sending a notice to the primary email address specified in your Supabase account and/or by placing a prominent notice on our Site. It is your responsibility to review this Privacy Notice periodically. When we do change the Privacy Notice, we will also revise the "last modified" date. + +## 9. Contact Us + +For additional inquiries about this Privacy Notice, please send us an email at privacy@supabase.io. + +This Privacy Notice was last modified on 27th March 2021 + +## Privacy disclosures for the European economic area, United Kingdom, and Switzerland. + +While we are primarily based in the United States, Supabase maintains operations in Europe and may direct our services to individuals located in the European Economic Area ("**_EEA_**"), United Kingdom and Switzerland, including through our Site [supabase.com](/) (collectively, our "**_European Services_**"). The following disclosures ("**_Privacy Disclosures_**") apply to our processing of personal data in connection with our European Services. + +Supabase, Inc. is the data controller responsible for the processing of personal data in connection with our European Services. This means that we determine and are responsible for how your personal information is used. + +**Personal Data:** When we use the term "personal data" in this section, we mean information relating to an identified or identifiable natural person. + +### 1. Personal data we collect from you when you use the Supabase European Services, and how we use it. + +We collect the categories of personal data that you voluntarily submit directly to us when you use the European Services, as set forth in our Privacy Notice under the section entitled **Information We Collect and Our Use**. The table at **Annex 1** sets out in detail the categories of personal data we collect about you and how we use that information when you use the European Services, as well as the legal basis which we rely on to process the personal information and recipients of that personal information. + +### 2. Information we collect about you automatically. + +We also automatically collect personal information indirectly about how you access and use the European Services, and information about the device you use to access the European Services. For example, we may collect: + +(a) information about the features you use and the pages you view on the European Services; + +(b) information about your device (such as your IP address, device identifier, device type, model and manufacturer); and + +(c) information about your usage patterns (such as how often you use the Supabase European Services and your language settings). + +We use this information to provide you the features and functionality of the European Services, to monitor and improve the European Services and to develop new services. + +The table at **Annex 2** sets out further information about the categories of personal information we collect about you automatically and how we use that information. The table also lists the legal basis which we rely on to process the personal information and recipients of that personal information. + +We may link or combine the personal information we collect about you and the information we collect automatically. + +We may anonymise and aggregate any of the personal information we collect (so that it does not directly identify you). We may use anonymised information for purposes that include testing our IT systems, research, data analysis, improving the Supabase European Services. We may also share such anonymised and aggregated information with others. + +### 3. How long will we store your personal information + +We will usually store the personal information we collect about you for no longer than necessary for the purposes set out in Annex 1 and Annex 2, in accordance with our legal obligations and legitimate business interests. + +The criteria used to determine the period for which personal information about you will be retained varies depending on the legal basis under which we process the personal information: + +1. **Legitimate Interests.** Where we are processing personal information based on our legitimate interests, we generally will retain such information for a reasonable period of time based on the particular interest, taking into account the fundamental interests and the rights and freedoms of data subjects. +2. **Consent.** Where we are processing personal information based on your consent, we generally will retain the information until you withdraw your consent, or otherwise for the period of time necessary to fulfill the underlying agreement with you or provide you with the applicable service for which we process that personal information. +3. **Contract.** Where we are processing personal information based on contract, we generally will retain the information for the duration of the contract plus some additional limited period of time that is necessary to comply with law or that represents the statute of limitations for legal claims that could arise from the contractual relationship. +4. **Legal Obligation.** Where we are processing personal information based on a legal obligation, we generally will retain the information for the period of time necessary to fulfill the legal obligation. +5. **Legal Claim.** We may need to apply a "legal hold" that retains information beyond our typical retention period where we face threat of legal claim.  In that case, we will retain the information until the hold is removed, which typically means the claim or threat of claim has been resolved. + +In all cases, in addition to the purposes and legal bases, we consider the amount, nature and sensitivity of the personal information, as well as the potential risk of harm from unauthorized use or disclosure of your personal information. + +### 4. Recipients of Personal Information + +In addition to the recipients listed in Annexes 1 and 2, we may also share your personal information with the following (as required in accordance with the uses set out in Annexes 1 and 2): + +1. **Service providers and advisors**: we may share your personal information with third party vendors and other service providers that perform services for us or on our behalf, which may include providing professional services, such as legal and accounting services, mailing, email or chat services, fraud prevention, web hosting, or providing analytic services. +2. **Affiliates**. Other companies owned by or under common ownership as Supabase, including our subsidiaries (i.e., any organization we own or control) and our ultimate holding company (i.e., any organization that owns or controls us) and any subsidiaries it owns. These companies will use your personal information in the same way as we can under these Privacy Disclosures. +3. **Purchasers and third parties in connection with a business transaction**: your personal information may be disclosed to third parties in connection with a transaction, such as a merger, sale of assets or shares, reorganization, financing, change of control or acquisition of all or a portion of our business. +4. **Law enforcement, regulators and other parties for legal reasons**: we may share your personal information with third parties as required by law or if we reasonably believe that such action is necessary to (i) comply with the law and the reasonable requests of law enforcement; (ii) detect and investigate illegal activities and breaches of agreements, including our Terms; and/or (iii) exercise or protect the rights, property, or personal safety of Supabase, its users or others. + +### 5. Marketing and Advertising + +From time to time we may contact you with information about our services, including sending you marketing messages and asking for your feedback on our services. Most marketing messages we send will be by email. For some marketing messages, we may use personal information we collect about you to help us determine the most relevant marketing information to share with you. + +We will only send you marketing messages if you have given us your consent to do so. You can withdraw your consent at a later date by clicking on the unsubscribe link at the bottom of our marketing emails or by updating your preferences via your account on the Site. + +### 6. Storing and transferring your personal information + +**Security**. We implement appropriate technical and organizational measures to protect your personal information against accidental or unlawful destruction, loss, change or damage. All personal information we collect will be stored by our cloud hosting provider on secure servers. We will never send you unsolicited emails or contact you by phone requesting credit or debit card information or national identification numbers. + +**International Transfers of your Personal Information**. The personal information we collect may be transferred to and stored in countries outside of the jurisdiction you are in where we and our third party service providers have operations. If you are located in the EEA, United Kingdom or Switzerland, your personal information may be processed outside of those regions, including in the United States. + +In the event of such a transfer, we ensure that: (i) the personal information is transferred to countries recognized as offering an equivalent level of protection; or (ii) the transfer is made pursuant to appropriate safeguards, such as standard data protection clauses adopted by the European Commission. + +If you wish to enquire further about these safeguards used, please contact us using the details set out at the end of these Privacy Disclosures. + +### 7. Profiling + +We may analyze personal data we have collected about you to create a profile of your interests and send product updates. We may also use personal data about you to detect and reduce fraud. + +### 8. Your rights in respect of your personal information + +In accordance with applicable privacy law, you have the following rights in respect of your personal information that we hold: + +1. **Right of access**. You have the right to obtain: + 1. confirmation of whether, and where, we are processing your personal information; + 2. information about the categories of personal information we are processing, the purposes for which we process your personal information and information as to how we determine applicable retention periods; + 3. information about the categories of recipients with whom we may share your personal information; and + 4. a copy of the personal information we hold about you. +2. **Right of portability**. You have the right, in certain circumstances, to receive a copy of the personal information you have provided to us in a structured, commonly used, machine-readable format that supports re-use, or to request the transfer of your personal data to another person. +3. **Right to rectification**. You have the right to obtain rectification of any inaccurate or incomplete personal information we hold about you without undue delay. +4. **Right to erasure**. You have the right, in some circumstances, to require us to erase your personal information without undue delay if the continued processing of that personal information is not justified. +5. **Right to restriction**. You have the right, in some circumstances, to require us to limit the purposes for which we process your personal information if the continued processing of the personal information in this way is not justified, such as where the accuracy of the personal information is contested by you. +6. **Right to withdraw consent**. There are certain circumstances where we require your consent to process your personal information. In these instances, and if you have provided consent, you have the right to withdraw your consent. If you withdraw your consent, this will not affect the lawfulness of our use of your personal information before your withdrawal. + +**You also have the right to object to any processing based on our legitimate interests where there are grounds relating to your particular situation. There may be compelling reasons for continuing to process your personal information, and we will assess and inform you if that is the case. You can object to marketing activities for any reason.** + +You also have the right to lodge a complaint to your local data protection authority. If you are based in the European Union, information about how to contact your local data protection authority is available [here](http://ec.europa.eu/justice/data-protection/bodies/authorities/index_en.htm). If you are based in the UK or Switzerland, your local data protection authorities are the UK Information Commissioner's Office () and the Swiss Federal Data Protection and Information Commissioner (). + +If you wish to exercise one of these rights, please contact us using the contact details at the end of these Privacy Disclosures. + +Due to the confidential nature of data processing we may ask you to provide proof of identity when exercising the above rights. This can be done by providing a scanned copy of a valid identity document or a signed photocopy of a valid identity document. + +### 9. Cookies and similar technologies used on our European Services + +Our European Services uses cookies and similar technologies such as pixels and Local Storage Objects (LSOs) like HTML5 (together "**_cookies_**") to distinguish you from other users of our European Services. This helps us to provide you with a good experience when you browse our European Services and also allows us to monitor and analyse how you use and interact with our European Services so that we can continue to improve our European Services. + +Cookies are pieces of code that allow for personalization of our European Services experience by saving your information such as user ID and other preferences. A cookie is a small data file that we transfer to your computer's hard disk for record-keeping purposes. + +We use the following types of cookies: + +1. **Strictly necessary cookies**. These are cookies that are required for the operation of our European Services. They include, for example, cookies that enable you to log into secure areas of our European Services. + +Please see **Annex 3** for more information about the cookies we use on the European Services. + +Most browsers also allow you to change your cookie settings to block certain cookies. Depending on your mobile device and operating system, you may not be able to delete or block all cookies. Please note that if you choose to refuse all cookies you may not be able to use the full functionality of our European Services. These settings will typically be found in the "options" or "preferences" menu of your browser. In order to understand these settings, the following links may be helpful, otherwise you should use the "Help" option in your browser for more details. + +- [Cookie settings in Internet Explorer](https://support.microsoft.com/en-gb/help/278835/how-to-delete-cookie-files-in-internet-explorer) +- [Cookie settings in Firefox](http://support.mozilla.org/en-US/kb/cookies) +- [Cookie settings in Chrome](https://support.google.com/chrome/answer/95647?hl=en) +- [Cookies settings in Safari web](https://support.apple.com/en-gb/guide/safari/manage-cookies-and-website-data-sfri11471/mac) and [iOS](https://support.apple.com/en-gb/HT201265). + +If you would like to find out more about cookies and other similar technologies, please visit [allaboutcookies.org](http://www.allaboutcookies.org). + +Please note that deleting or blocking cookies may not be effective for all types of tracking technologies, such as Local Storage Objects (LSOs) like HTML5. + +### 10. Tracking technologies used in our emails + +Our emails may contain tracking pixels that identify if and when you have opened an email that we have sent you, how many times you have read it and whether you have clicked on any links in that email. This helps us measure the effectiveness of our marketing email campaigns, make the emails we send to you more relevant to your interests and to understand if you have opened and read any important administrative emails we might send you. + +Most popular email clients will allow you to block these pixels by disabling certain external images in emails. You can do this through the settings on your email client – these generally give you the option of choosing whether emails will display "remote images", "remote content" or "images" by default. + +Some browsers also give you the option of downloading and installing extensions that block pixels and other tracking technologies. + +## Annex 1 – Personal information you provide to us + +| **Category of Personal Information** | **How we may use the Personal Information** | **Legal Bases for Processing** | **Recipients of Personal Information** | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Contact information**, such as first name, last name and email address. | We may use this information to set up and authenticate your account on the Service. | The processing is necessary for the performance of a contract with you and to take steps prior to entering into a contract with you, namely our Terms of Service. |

We may share this information with the following service providers through the provision of the Service: Segment, Auth0, Stripe, Intercom, Hubspot, Mixpanel, Notion, Slack, Amazon Web Services, and BigQuery (Google Cloud).

| +| | We may use this information to communicate with you, including sending service-related communications. | The processing is necessary for the performance of a contract with you, namely our Terms of Service. | | +| | We may use this information to deal with enquiries and complaints made by or about you relating to the Service. | The processing is necessary for our legitimate interests, namely administering the Service, and for communicating with you effectively to respond to your queries or complaints. | | +| | We may use this information in connection with providing you with marketing communications in accordance with your preferences. | We will only use your personal information in this way to the extent you have given us consent to do so. | | +| **Your registration / account information** such as your full name, email, and password. |

We may use this information to create your account on the Service.

|

The processing is necessary for the performance of a contract with you.

|

We may share this information with the following service providers through the provision of the Service: Segment, Auth0, Stripe, Amazon Web Services.

| +| |

We use this information to deal with enquiries and complaints made by or about you relating to the Service.

| The processing is necessary for our legitimate interests, namely for communicating with our members effectively to respond to any queries or complaints. | | +| **Payment transaction information.** When you make a purchase, we may collect information such as your billing address and other information such as date and time of your transaction. |

We may use this information to process your orders through the Service.

| The processing is necessary for the performance of a contract. |

We may share this information with the following service providers through the provision of the Service: Stripe, and Amazon Web Services.

| +| | We may use this information to verify your identity in connection with the detection and prevention of fraud or financial crime. | The processing is necessary for our and third partiers' legitimate interests, namely the detection and prevention of fraud and financial crime. | | +| **Approximate Location information.** When you visit our Service, we may collect information about your location. This information may be derived from WiFi positioning or your IP address. | We may use information to present the Service to you on your device. | The processing is necessary for performance of a contract with you. |

We may share this information with the following service providers through the provision of the Service: Sentry, BigQuery (Google Cloud), and Amazon Web Services.

| +| | We may use this information to localise features of the Service. | The processing is necessary for our legitimate interest, namely localising features of the Service and tailoring the Service so that it is more relevant to our users. | | +| | We may use this information to determine content that may be of interest to you. | The processing is necessary for our legitimate interests, namely tailoring the Service so that it is more relevant to you. | | +| **Chat, comments and opinions.** When you contact us directly, e.g. by email or phone we will record your comments and opinions. | We may use this information to address your questions, issues and concerns. | The processing is necessary for our legitimate interests, namely communicating with you and responding to queries, complaints and concerns. |

We may share this information with the following service providers through the provision of the Service: Intercom, Hubspot, Google Gsuite, and Slack.

| +| | We may use this information to improve the Service. | The processing is necessary for our legitimate interests (to develop and improve our service). | | +| **Information received from third parties, such as social networks.** If you interact with us through a social network, we may receive information from the social network such as your name, profile information, and any other information you permit the social network to share with third parties. We use single sign-on ("**_SSO_**") such as GitHub to allow a user to authenticate their account using one set of login information. The data we receive is dependent on your privacy settings with the social network. | We may use this information to reshare content created through the use of the Service | The processing is necessary for our legitimate interests (to develop our service and inform our marketing strategy) | We may share this information with the following service providers through the provision of the Service: Auth0 and Slack. | +| |

We may use this information to authenticate you and allow you to access the Service.

| The processing is necessary for the performance of a contract with you. | | +| **Your preferences**, such as preferences set for notifications, marketing communications, how the Service is displayed and the active functionalities on the Service. |

We use this information to provide notifications, send news, alerts and marketing communications and provide the Service in accordance with your choices.

|

The processing is necessary for our legitimate interest, namely ensuring the user receives the correct marketing and other communications, and that this is displayed in accordance with the user's preferences.

| We may share this information with the following service providers through the provision of the Service: Segment, Intercom and Hubspot. | +| |

We use this information to ensure that we comply with our legal obligation to send only those marketing communications to which you have consented.

| The processing is necessary for compliance with a legal obligation to which we are subject. | | + +## Annex 2 – Personal information collected automatically + +| **Category of personal information** | **How we may use it** | **Legal basis for the processing** | **Recipients of Personal Data** | +| :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Approximate location information.** Other than information you choose to provide to us, we do not collect information about your precise location. Your device’s IP address may however help us determine an approximate location. | We may use information you provide to us about your location to monitor and detect fraud or suspicious activity in relation to your Supabase account. | The processing is necessary for our legitimate interests, namely to protect our business and your account from fraud and other illegal activities. |

**Approximate location information:** We may share this information with the following service providers through the provision of the Service: Sentry, BigQuery (Google Cloud), and Amazon Web Services.

**Information about how you access and use the Service.** We may share this information with the following service providers through the provision of the Service: Segment, Mixpanel, Intercom, Hubspot, BigQuery (Google Cloud), and Amazon Web Services.

**Log files and information about your device.** We may share this information with the following service providers through the provision of the Service: Segment, Mixpanel, Intercom, Hubspot, Sentry, BigQuery (Google Cloud), and Amazon Web Services.

| +| | We may use this information to tailor how the Service is displayed to you (such as the language in which it is provided to you). | The processing is necessary for our legitimate interest, namely tailoring our service so that it is more relevant to our users. | | +| **Information about how you access and use the Service.** For example, how frequently you access the Service, the time you access the Service and how long you use it for, the approximate location that you access the Service from, the site from which you came and the site to which you are going when you leave our website, the website pages you visit, the links you click, whether you open emails or click the links contained in emails, whether you access the Service from multiple devices, and other actions you take on the Service. |

We may use information about how you use and connect to the Service to present the Service to you on your device.

| The processing is necessary for our legitimate interests, namely to tailor the Service to the user. | | +| | We may use this information to determine products and services that may be of interest to you for marketing purposes. | The processing is necessary for our legitimate interests, namely to inform our direct marketing. | | +| |

We may use this information to monitor and improve the Service and business, resolve issues and to inform the development of new products and services.

| The processing is necessary for our legitimate interests, namely to monitor and resolve issues with the Service and to improve the Service generally. | | +| **Log files and information about your device.** We also collect information about the tablet, smartphone or other electronic device you use to connect to the Service. This information can include details about the, operating systems, browsers and applications connected to the Service through the device and your IP address. |

We may use information about how you use and connect to the Service to present the Service to you on your device.

| The processing is necessary for our legitimate interests, namely to tailor the Service to the user. | | +| |

We may use this information to monitor and improve the Service and business, resolve issues and to inform the development of new products and services.

| The processing is necessary for our legitimate interests, namely to monitor and resolve issues with the Service and to improve the Service generally. | | + +## Annex 3 - Cookies + +| **Cookie Name** | **Type of cookie** | **How long does the cookie stay on my device?** | **Purpose of the cookie** | +| :----------------------------- | :----------------- | :---------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +|

a0:session

| Strictly necessary | 1 Day | Authentication Purposes. | +|

a0:state

| Strictly necessary | 2 Hours | Authentication Purposes. | +|

youtube-nocookie

| Strictly necessary | Persistent |

Privacy-enhanced cookie, essential for embedded videos. [Link.](https://support.google.com/youtube/answer/171780)

Privacy Enhanced Mode allows you to embed YouTube videos without using cookies that track viewing behavior. This means no activity is collected to personalize the viewing experience.

| diff --git a/apps/reference/docs/company/sla.md b/apps/reference/docs/company/sla.md new file mode 100644 index 00000000000..00cbf36e740 --- /dev/null +++ b/apps/reference/docs/company/sla.md @@ -0,0 +1,88 @@ +--- +id: sla +title: Service Level Agreement +--- + +The following Service Level Agreement, which is incorporated into and forms part of the Subscription Agreement between Supabase, Inc. ("Supabase") and Customer (the "Agreement"), will apply to the Services for Enterprise Customers specified in an Order Form during the applicable Subscription Term: + +## Platform + +### 1. Uptime Commitment + +Supabase will provide Actual Availability for at least ninety-nine and nine tenths percent (99.9%) of the total time in each calendar month during the Subscription Term, as measured by Supabase (the **"Uptime Commitment"**). + +### 2. Service Credits + +If the Uptime Commitment is not met during any particular calendar month during the Subscription Term, then Customer will be eligible for a service credit ("Service Credit"), provided that Customer reports to Supabase such failure to meet the Uptime Commitment and requests such Service Credit in accordance with this Exhibit. The amount of any Service Credit due hereunder shall be calculated as follows: +X \* Y, where X = the total fees due from Customer to Supabase for the affected Services for the relevant calendar month (regardless of when billed or payable), and Y = the Credit Percentage corresponding with the Actual Availability provided (as a percentage of total time) for the relevant calendar month, as set forth in the table below. + +| Actual Availability | Credit Percentage | +| -------------------------------------------------- | ----------------- | +| Less than 99.9% but greater than or equal to 99.0% | 10% | +| Less than 99.0% but greater than or equal to 98.0% | 15% | +| Less than 98.0% but greater than or equal to 96.0% | 20% | +| Less than 96.0% | 30% | + +### 3. Credit Requests and Payment + +To request a Service Credit, Customer must send an email to Supabase at support@supabase.io within thirty (30) days of the end of the month in which the Uptime Commitment was not met. Customer must include either its account ID or registered email address, and the previously reported dates and times that there was no Service Availability. If Supabase confirms that Customer is eligible for a Service Credit, Supabase will issue a credit to Customer’s account within thirty (30) days. Service Credits are not refunds, cannot be exchanged into a cash amount, and may only be used against future billing charges. Except as set forth in Section 4 below, the Service Credits shall be Customer’s sole and exclusive remedy, and Supabase’s sole and exclusive liability, for any failure by Supabase to meet the Uptime Commitment. + +### 4. Definitions + +All capitalized words used but not defined in this Service Level Agreement have the meaning set forth in the Agreement. + +#### 4.1 Scheduled Availability + +"Scheduled Availability" means the time, in minutes, that the applicable Services are generally accessible and available to Customer’s Permitted Users. + +#### 4.2 Unscheduled Downtime + +"Unscheduled Downtime" means the time, in minutes, that the applicable Services are not generally accessible and available to Customer’s Permitted Users, excluding inaccessibility or unavailability due to Customer’s or Permitted Users’ acts or omissions, force majeure events, scheduled maintenance disclosed with at least 24 hours’ notice by email, hacking or virus attacks, or reasonable emergency maintenance. + +#### 4.3 Actual Availability + +"Actual Availability" means Scheduled Availability less Unscheduled Downtime. + +## Support + +Supabase Support Service Level Agreements. + +### 1. Urgent + +**Critical Issue** + +Defect resulting in full or partial system outage or a condition that makes Supabase unusable +or unavailable in production for all of Customer’s Users. + +### 2. High + +**Significant Business Disruption** + +Issue resulting in a situation meaning major functionality is impacted and +significant performance degradation is experienced. Issue impacts significant proportion of user base and / or major +Supabase functionality. + +### 3. Normal + +**Minor Feature or Functional Issue / General Question** + +Issue results in a component of Supabase not +performing as expected or documented. An inquiry by a Customer representative regarding a general technical issue +or general question. + +### 4. Low + +**Minor Issue / Feature Request** + +An Information request about Supabase or feature request. + +## Target response times + +| Severity Level | Standard | Priority | Priority Plus | +| -------------- | ------------------------------------- | ------------------------------------- | -------------------------------------- | +| 1. Urgent | 1 business hour
24/7 × 365 | 1 business hour
24/7 × 365 | 1 business hour
24/7 × 365 | +| 2. High | 4 business hours
Monday - Friday | 2 business hours
Monday - Friday | 2 business hours
24/7 × 365 | +| 3. Normal | 1 business day
Monday - Friday | 1 business day
Monday - Friday | 12 business hours
Monday - Friday | +| 4. Low | 2 business days
Monday - Friday | 2 business days
Monday - Friday | 1 business day
Monday - Friday | + +Business hours are from 6am to 6pm (local time), except where otherwise stated. diff --git a/apps/reference/docs/company/terms.md b/apps/reference/docs/company/terms.md new file mode 100644 index 00000000000..60fd3ce9eb4 --- /dev/null +++ b/apps/reference/docs/company/terms.md @@ -0,0 +1,235 @@ +--- +id: terms +title: Terms of Service +--- + +`Last Modified: 20 November 2020` + +These Customer Terms and Conditions (this "**Agreement**"), effective as of the date on which you click a button or check a box (or something similar) acknowledging your acceptance of this Agreement (the "**Effective Date**"), is by and between Supabase, Inc., a Delaware corporation with offices located at 970 Toa Payoh North #07-04, Singapore 318992 ("**Supabase**") and the entity on whose behalf the individual accepting this Agreement accepts this Agreement ("**Customer**"). The individual accepting this Agreement hereby represents and warrants that it is duly authorized by the entity on whose behalf it accepts this Agreement to so accept this Agreement. Supabase and Customer may be referred to herein collectively as the "**Parties**" or individually as a "**Party**." The Parties agree as follows: + +## 1. Definitions. + +1. "**Aggregated Data**" means data and information related to or derived from Customer Data or Customer's use of the Services that is used by Supabase in an aggregate and anonymized manner, including to compile statistical and performance information related to the Services. +2. "**Authorized User**" means Customer's employees, consultants, contractors, and agents (i) who are authorized by Customer to access and use the Services under the rights granted to Customer pursuant to this Agreement; and (ii) for whom access to the Services has been purchased hereunder. +3. "**Customer Data**" means information, data, and other content, in any form or medium, that is submitted, posted, or otherwise transmitted by or on behalf of Customer or an Authorized User through the Services; provided that, for purposes of clarity, Customer Data does not include Aggregated Data. +4. "**Documentation**" means Supabase's end user documentation relating to the Services available at [supabase.io](https://supabase.com). +5. "**Harmful Code**" means any software, hardware, or other technology, device, or means, including any virus, worm, malware, or other malicious computer code, the purpose or effect of which is to permit unauthorized access to, or to destroy, disrupt, disable, distort, or otherwise harm or impede in any manner any (i) computer, software, firmware, hardware, system, or network; or (ii) any application or function of any of the foregoing or the security, integrity, confidentiality, or use of any data processed thereby. +6. "**Order**" means: (i) the purchase order, order form, or other ordering document entered into by the Parties that incorporates this Agreement by reference; or (ii) if Customer registered for the Services through Supabase's online ordering process, the results of such online ordering process. +7. "**Personal Information**" means any information that, individually or in combination, does or can identify a specific individual or by or from which a specific individual may be identified, contacted, or located, including without limitation all data considered "personal data", "personally identifiable information", or something similar under applicable laws, rules, or regulations relating to data privacy. +8. "**Supabase IP**" means the Services, the Documentation, and any and all intellectual property provided to Customer or any Authorized User in connection with the foregoing. For the avoidance of doubt, Supabase IP includes Aggregated Data and any information, data, or other content derived from Supabase's provision of the Services but does not include Customer Data. +9. "**Services**" means Supabase's proprietary hosted software platform, as made available by Supabase to Authorized Users from time to time. +10. "**Subscription Period**" means the time period identified on the Order during which Customer's Authorized Users may access and use the Services. +11. "**Third-Party Products**" means any third-party products provided with, integrated with, or incorporated into the Services. +12. "**Usage Limitations**" means the usage limitations set forth in this Agreement and the Order, including without limitation any limitations on the number of Authorized Users (if any), and the applicable product, pricing, and support tiers agreed-upon by the Parties. + +## 2. Access and Use. + +### 1. Provision of Access. + +Subject to and conditioned on Customer's compliance with the terms and conditions of this Agreement, including without limitation the Usage Limitations, Supabase will make available to Customer during the Subscription Period, on a non-exclusive, non-transferable (except in compliance with Section 13.8), and non-sublicensable basis, access to and use of the Services, solely for use by Authorized Users. Such use is limited to Customer's internal business purposes and the features and functionalities specified in the Order. Supabase shall provide to Customer the necessary access credentials to allow Customer to access the Services. + +### 2. Documentation License. + +Subject to and conditioned on Customer's compliance with the terms and conditions of this Agreement, Supabase hereby grants to Customer a non-exclusive, non-transferable (except in compliance with Section 13.8), and non-sublicensable license to use the Documentation during the Subscription Period solely for Customer's internal business purposes in connection with its use of the Services. + +### 3. Use Restrictions. + +Customer shall not use the Services for any purposes beyond the scope of the access granted in this Agreement. Customer shall not at any time, directly or indirectly, and shall not permit any Authorized Users to: (i) copy, modify, or create derivative works of any Supabase IP, whether in whole or in part; (ii) rent, lease, lend, sell, license, sublicense, assign, distribute, publish, transfer, or otherwise make available the Services or Documentation to any third party; (iii) reverse engineer, disassemble, decompile, decode, adapt, or otherwise attempt to derive or gain access to any software component of the Services, in whole or in part; (iv) remove any proprietary notices from any Supabase IP; (v) use any Supabase IP in any manner or for any purpose that infringes, misappropriates, or otherwise violates any intellectual property right or other right of any person, or that violates any applicable law; (vi) access or use any Supabase IP for purposes of competitive analysis of Supabase or the Services, the development, provision, or use of a competing software service or product, or any other purpose that is to Supabase's detriment or commercial disadvantage; (vii) bypass or breach any security device or protection used by the Services or access or use the Services other than by an Authorized User through the use of valid access credentials; or (vii) input, upload, transmit, or otherwise provide to or through the Services any information or materials that are unlawful or injurious, or that contain, transmit, or activate any Harmful Code. + +### 4. Reservation of Rights. + +Supabase reserves all rights not expressly granted to Customer in this Agreement. Except for the limited rights and licenses expressly granted under this Agreement, nothing in this Agreement grants, by implication, waiver, estoppel, or otherwise, to Customer or any third party any intellectual property rights or other right, title, or interest in or to the Supabase IP. + +### 5. Suspension. + +Notwithstanding anything to the contrary in this Agreement, Supabase may temporarily suspend Customer's and any Authorized User's access to any portion or all of the Services if: (i) Supabase reasonably determines that (A) there is a threat or attack on any of the Supabase IP; (B) Customer's or any Authorized User's use of the Supabase IP disrupts or poses a security risk to the Supabase IP or to any other customer or vendor of Supabase; (C) Customer, or any Authorized User, is using the Supabase IP for fraudulent or illegal activities; (D) subject to applicable law, Customer has ceased to continue its business in the ordinary course, made an assignment for the benefit of creditors or similar disposition of its assets, or become the subject of any bankruptcy, reorganization, liquidation, dissolution, or similar proceeding; or (E) Supabase's provision of the Services to Customer or any Authorized User is prohibited by applicable law; (ii) any vendor of Supabase has suspended or terminated Supabase's access to or use of any Third-Party Products required to enable Customer to access the Services; or (iii) in accordance with Section 5.1 (any such suspension described in subclause (i), (ii), or (iii), a "**Service Suspension**"). Supabase shall use commercially reasonable efforts to provide written notice of any Service Suspension to Customer and to provide updates regarding resumption of access to the Services following any Service Suspension. Supabase shall use commercially reasonable efforts to resume providing access to the Services as soon as reasonably possible after the event giving rise to the Service Suspension is cured. Supabase will have no liability for any damage, liabilities, losses (including any loss of data or profits), or any other consequences that Customer or any Authorized User may incur as a result of a Service Suspension. + +### 6. Aggregated Data. + +Notwithstanding anything to the contrary in this Agreement, Supabase may monitor Customer's use of the Services and collect and compile Aggregated Data. As between Supabase and Customer, all right, title, and interest in Aggregated Data, and all intellectual property rights therein, belong to and are retained solely by Supabase. Customer acknowledges that Supabase may compile Aggregated Data based on Customer Data input into the Services. Customer agrees that Supabase may (i) make Aggregated Data available to third parties including its other customers in compliance with applicable law, and (ii) use Aggregated Data to the extent and in the manner permitted under applicable law. + +## 3. Customer Responsibilities. + +### 1. General. + +Customer is responsible and liable for all uses of the Services and Documentation resulting from access provided by Customer, directly or indirectly, whether such access or use is permitted by or in violation of this Agreement. Without limiting the generality of the foregoing, Customer is responsible for all acts and omissions of Authorized Users, and any act or omission by an Authorized User that would constitute a breach of this Agreement if taken by Customer will be deemed a breach of this Agreement by Customer. Customer shall use reasonable efforts to make all Authorized Users aware of this Agreement's provisions as applicable to such Authorized User's use of the Services and shall cause Authorized Users to comply with such provisions. + +### 2. Third-Party Products. + +Supabase may from time to time make Third-Party Products available to Customer or Supabase may allow for certain Third-Party Products to be integrated with the Services to allow for the transmission of Customer Data from such Third-Party Products into the Services. For purposes of this Agreement, such Third-Party Products are subject to their own terms and conditions. If Customer does not agree to abide by the applicable terms for any such Third-Party Products, then Customer should not install or use such Third-Party Products. By authorizing Supabase to transmit Customer Data from Third-Party Products into the Services, Customer represents and warrants to Supabase that it has all right, power, and authority to provide such authorization. + +### 3. Customer Control and Responsibility. + +Customer has and will retain sole responsibility for: (i) all Customer Data, including its content and use; (ii) all information, instructions, and materials provided by or on behalf of Customer or any Authorized User in connection with the Services; (iii) Customer's information technology infrastructure, including computers, software, databases, electronic systems (including database management systems), and networks, whether operated directly by Customer or through the use of third-party services ("**Customer Systems**"); (iv) the security and use of Customer's and its Authorized Users' access credentials; and (v) all access to and use of the Services directly or indirectly by or through the Customer Systems or its or its Authorized Users' access credentials, with or without Customer's knowledge or consent, including all results obtained from, and all conclusions, decisions, and actions based on, such access or use. + +## 4. Support. + +During the Subscription Period, Supabase will use commercially reasonable efforts to provide Customer with basic customer support via Supabase's standard support channels during Supabase's normal business hours. + +## 5. Fees and Taxes. + +### 1. Fees. + +Where paid for services are agreed between Supabase and Customer per the Order, Customer shall pay Supabase the fees ("**Fees**") identified in the Order without offset or deduction at the cadence identified in the Order (e.g., monthly or annually). Fees paid by Customer are non-refundable. If Customer fails to make any payment when due, and Customer has not notified Supabase in writing within ten (10) days of the payment becoming due and payable that the payment is subject to a good faith dispute, without limiting Supabase's other rights and remedies: (i) Supabase may charge interest on the undisputed past due amount at the rate of 1.5% per month, calculated daily and compounded monthly or, if lower, the highest rate permitted under applicable law; (ii) Customer shall reimburse Supabase for all reasonable costs incurred by Supabase in collecting any late payments or interest, including attorneys' fees, court costs, and collection agency fees; and (iii) if such failure continues for ten (10) days or more, Supabase may suspend Customer's and its Authorized Users' access to any portion or all of the Services until such amounts are paid in full. + +### 2. Taxes. + +All Fees and other amounts payable by Customer under this Agreement are exclusive of taxes and similar assessments. Customer is responsible for all sales, use, and excise taxes, and any other similar taxes, duties, and charges of any kind imposed by any federal, state, or local governmental or regulatory authority on any amounts payable by Customer hereunder, other than any taxes imposed on Supabase's income. To the extent that Supabase is required by law to pay any such taxes, duties, or other charges to any governmental or regulatory authority, Supabase may invoice Customer for such taxes, duties, or other charges and Customer will pay such invoiced amounts in accordance with this Agreement. + +## 6. Confidential Information. + +### 1. Definition. + +From time to time during the Subscription Period, either Party may disclose or make available to the other Party information about its business affairs, products, confidential intellectual property, trade secrets, third-party confidential information, and other sensitive or proprietary information, whether orally or in written, electronic, or other form or media that: (i) is marked, designated or otherwise identified as "confidential" or something similar at the time of disclosure or within a reasonable period of time thereafter; or (ii) would be considered confidential by a reasonable person given the nature of the information or the circumstances of its disclosure (collectively, "**Confidential Information**"). Except for Personal Information, Confidential Information does not include information that, at the time of disclosure is: (a) in the public domain; (b) known to the receiving Party at the time of disclosure; (c) rightfully obtained by the receiving Party on a non-confidential basis from a third party; or (d) independently developed by the receiving Party without use of, reference to, or reliance upon the disclosing Party's Confidential Information. + +### 2. Duty. + +The receiving Party shall not disclose the disclosing Party's Confidential Information to any person or entity, except to the receiving Party's employees, contractors, and agents who have a need to know the Confidential Information for the receiving Party to exercise its rights or perform its obligations hereunder ("**Representatives**"). The receiving Party will be responsible for all the acts and omissions of its Representatives as they relate to Confidential Information hereunder. Notwithstanding the foregoing, each Party may disclose Confidential Information to the limited extent required (i) in order to comply with the order of a court or other governmental body, or as otherwise necessary to comply with applicable law, provided that the Party making the disclosure pursuant to the order shall first have given written notice to the other Party and made a reasonable effort to obtain a protective order; or (ii) to establish a Party's rights under this Agreement, including to make required court filings. Further, notwithstanding the foregoing, each Party may disclose the terms and existence of this Agreement to its actual or potential investors, debtholders, acquirers, or merger partners under customary confidentiality terms. + +### 3. Return of Materials; Effects of Termination/Expiration. + +On the expiration or termination of the Agreement, the receiving Party shall promptly return to the disclosing Party all copies, whether in written, electronic, or other form or media, of the disclosing Party's Confidential Information, or destroy all such copies and certify in writing to the disclosing Party that such Confidential Information has been destroyed. Each Party's obligations of non-use and non-disclosure with regard to Confidential Information are effective as of the Effective Date and will expire three (3) years from the date of termination or expiration of this Agreement; provided, however, with respect to any Confidential Information that constitutes a trade secret (as determined under applicable law), such obligations of non-disclosure will survive the termination or expiration of this Agreement for as long as such Confidential Information remains subject to trade secret protection under applicable law. + +## 7. Personal Information. + +Customer will ensure that its Customer Data, and its use of such Customer Data, complies with this Agreement and any applicable law. Customer is responsible for properly configuring and using the Services and taking its own steps to maintain appropriate security, protection, and backup of Customer Data. Customer may not store or process protected health information (as defined in HIPAA) using the Services unless Customer signs a Business Associate Agreement with Supabase. Customer may not store any payment cardholder information using the Services without Supabase's prior written approval. + +## 8. Intellectual Property Ownership; Feedback. + +### 1. Supabase IP. + +Customer acknowledges that, as between Customer and Supabase, Supabase owns all right, title, and interest, including all intellectual property rights, in and to the Supabase IP and, with respect to Third-Party Products, the applicable third-party providers own all right, title, and interest, including all intellectual property rights, in and to the Third-Party Products. + +### 2. Customer Data. + +Supabase acknowledges that, as between Supabase and Customer, Customer owns all right, title, and interest, including all intellectual property rights, in and to the Customer Data. Customer hereby grants to Supabase a non-exclusive, royalty-free, worldwide license to reproduce, distribute, and otherwise use and display the Customer Data and perform all acts with respect to the Customer Data as may be necessary for Supabase to provide the Services to Customer, and a non-exclusive, perpetual, irrevocable, royalty-free, worldwide license to reproduce, distribute, modify, and otherwise use and display Customer Data incorporated within the Aggregated Data. Customer may export the Customer Data at any time through the features and functionalities made available via the Services. + +### 3. Feedback. + +If Customer or any of its employees or contractors sends or transmits any communications or materials to Supabase by mail, email, telephone, or otherwise, suggesting or recommending changes to the Supabase IP, including without limitation, new features or functionality relating thereto, or any comments, questions, suggestions, or the like ("**Feedback**"), Supabase is free to use such Feedback irrespective of any other obligation or limitation between the Parties governing such Feedback so long as Supabase does not identify Customer as the source of the Feedback without Customer's prior approval. + +## 9. Warranty Disclaimer. + +The Supabase IP is provided "as is" and Supabase +hereby disclaims all warranties, whether express, implied, statutory, or +otherwise. Supabase specifically disclaims all implied warranties of +merchantability, fitness for a particular purpose, title, and non-infringement, +and all warranties arising from course of dealing, usage, or trade practice. Supabase +makes no warranty of any kind that the Supabase IP, or any products or results +of the use thereof, will meet Customer’s or any other person’s requirements, +operate without interruption, achieve any intended result, be compatible or +work with any software, system or other services, or be secure, accurate, +complete, free of harmful code, or error free. + +## 10. Indemnification. + +### 1. Supabase Indemnification. + +1. Supabase shall indemnify, defend, and hold harmless Customer from and against any and all losses, damages, liabilities, costs (including reasonable attorneys' fees) ("**Losses**") incurred by Customer resulting from any third-party claim, suit, action, or proceeding ("**Third-Party Claim**") that the Services, or any use of the Services in accordance with this Agreement, infringes or misappropriates such third party's US copyrights or trade secrets; provided that Customer promptly notifies Supabase in writing of the claim, cooperates with Supabase, and allows Supabase sole authority to control the defense and settlement of such claim. +2. If such a claim is made or appears possible, Customer agrees to permit Supabase, at Supabase's sole discretion: to (i) modify or replace the Services, or component or part thereof, to make it non-infringing; or (ii) obtain the right for Customer to continue use. If Supabase determines that neither alternative is reasonably commercially available, Supabase may terminate this Agreement, in its entirety or with respect to the affected component or part, effective immediately on written notice to Customer. +3. This Section 10.1 will not apply to the extent that the alleged infringement arises from: (i) use of the Services in combination with data, software, hardware, equipment, or technology not provided by Supabase or authorized by Supabase in writing; (ii) modifications to the Services not made by Supabase; (iii) Customer Data; or (iv) Third-Party Products. + +### 2. Customer Indemnification. + +Customer shall indemnify, hold harmless, and, at Supabase's option, defend Supabase from and against any Losses resulting from any Third-Party Claim that the Customer Data, or any use of the Customer Data in accordance with this Agreement, infringes or misappropriates such third party's US intellectual property or other rights and any Third-Party Claims based on Customer's or any Authorized User's (i) negligence or willful misconduct; (ii) use of the Services in a manner not authorized by this Agreement; or (iii) use of the Services in combination with data, software, hardware, equipment or technology not provided by Supabase or authorized by Supabase in writing; in each case provided that Customer may not settle any Third-Party Claim against Supabase unless Supabase consents to such settlement, and further provided that Supabase will have the right, at its option, to defend itself against any such Third-Party Claim or to participate in the defense thereof by counsel of its own choice. + +### 3. Sole Remedy. + +This section 10.3 sets forth Customer's sole remedies and Supabase's sole liability and obligation for any actual, threatened, or alleged claims that the services infringe, misappropriate, or otherwise violate any intellectual property rights of any third party. + +## 11. Limitations of Liability. + +Except for: (i) a party’s breach of its confidentiality obligations; +(ii) a party’s indemnity obligations; or (iii) a party’s gross negligence, +fraud, or willful misconduct ("**Excluded Liabilities**"), (a) in no +event will either party be liable under or in connection with this agreement +under any legal or equitable theory, including breach of contract, tort +(including negligence), strict liability, and otherwise, for any: (1) +consequential, incidental, indirect, exemplary, special, enhanced, or punitive +damages; (2) increased costs, diminution in value or lost business, production, +revenues, or profits; (3) loss of goodwill or reputation; (4) use, inability to +use, loss, interruption, delay or recovery of any data, or breach of data or +system security; or (5) cost of replacement goods or services, in each case +regardless of whether such party was advised of the possibility of such losses +or damages or such losses or damages were otherwise foreseeable; and (b) in no +event will either party’s aggregate liability arising out of or related to this +agreement under any legal or equitable theory, including breach of contract, +tort (including negligence), strict liability, and otherwise exceed the total +amounts paid and/or payable to Supabase under this agreement in the twelve (12) +months immediately preceding the claim; provided that, notwithstanding the +foregoing, Supabase's aggregate liability arising out of or relating to any +excluded liabilities will not exceed three times (3x) the total amounts paid +and/or payable to Supabase by Customer under this agreement in the twelve (12) +months immediately preceding the claim. + +## 12. Subscription Period and Termination. + +### 1. Subscription Period. + +The initial term of this Agreement begins on the Effective Date and, unless terminated earlier pursuant to Section 12.2, will continue in effect for the period identified in the Order (the "**Initial Subscription Period**"). This Agreement will automatically renew for additional successive terms equal to the length of the Initial Subscription Period unless earlier terminated pursuant to this Agreement's express provisions or either Party gives the other Party written notice of non-renewal at least thirty (30) days prior to the expiration of the then-current term (each a "**Renewal Subscription Period**" and together with the Initial Subscription Period, the "**Subscription Period**").] + +#### 2. Termination. + +In addition to any other express termination right set forth in this Agreement: + +1. Supabase may terminate this Agreement, effective on written notice to Customer, if Customer: (i) fails to pay any amount when due hereunder, and such failure continues more than ten (10) calendar days after Supabase's delivery of written notice thereof; or (ii) breaches any of its obligations under Section 2.3 or Section 6; +2. either Party may terminate this Agreement, effective on written notice to the other Party, if the other Party materially breaches this Agreement, and such breach: (i) is incapable of cure; or (ii) being capable of cure, remains uncured thirty (30) calendar days after the non-breaching Party provides the breaching Party with written notice of such breach; or +3. either Party may terminate this Agreement, effective immediately upon written notice to the other Party, if the other Party: (i) becomes insolvent or is generally unable to pay, or fails to pay, its debts as they become due; (ii) files or has filed against it, a petition for voluntary or involuntary bankruptcy or otherwise becomes subject, voluntarily or involuntarily, to any proceeding under any domestic or foreign bankruptcy or insolvency law; (iii) makes or seeks to make a general assignment for the benefit of its creditors; or (iv) applies for or has appointed a receiver, trustee, custodian, or similar agent appointed by order of any court of competent jurisdiction to take charge of or sell any material portion of its property or business. + +### 3. Effect of Expiration or Termination. + +Upon expiration or earlier termination of this Agreement, Customer shall immediately discontinue use of the Supabase IP and, without limiting Customer's obligations under Section 6, Customer shall delete, destroy, or return all copies of the Supabase IP and certify in writing to the Supabase that the Supabase IP has been deleted or destroyed. No expiration or termination will affect Customer's obligation to pay all Fees that may have become due before such expiration or termination or entitle Customer to any refund. + +### 4. Survival. + +This Section 12.4 and Sections 1, 5, 6, 8, 9, 10, 11, and 13 survive any termination or expiration of this Agreement. No other provisions of this Agreement survive the expiration or earlier termination of this Agreement. + +## 13. Miscellaneous. + +### 1. Entire Agreement. + +This Agreement, together with any other documents incorporated herein by reference, constitutes the sole and entire agreement of the Parties with respect to the subject matter of this Agreement and supersedes all prior and contemporaneous understandings, agreements, and representations and warranties, both written and oral, with respect to such subject matter. In the event of any inconsistency between the statements made in the body of this Agreement, the related Exhibits, and any other documents incorporated herein by reference, the following order of precedence governs: (i) first, this Agreement; and (ii) second, any other documents incorporated herein by reference. + +### 2. Notices. + +All notices, requests, consents, claims, demands, waivers, and other communications hereunder (each, a "**Notice**") must be in writing and addressed to the Parties at the addresses set forth on the first page of this Agreement or as identified on the Order Form (or to such other address that may be designated by the Party giving Notice from time to time in accordance with this Section). All Notices must be delivered by personal delivery, nationally recognized signed for on delivery courier (with all fees pre-paid), or email (with confirmation of transmission). All email Notices to Supabase must be sent to [legal@supabase.io](mailto:legal@supabase.io). Except as otherwise provided in this Agreement, a Notice is effective only: (i) upon receipt by the receiving Party; and (ii) if the Party giving the Notice has complied with the requirements of this Section. + +### 3. Force Majeure. + +In no event shall either Party be liable to the other Party, or be deemed to have breached this Agreement, for any failure or delay in performing its obligations under this Agreement (except for any obligations to make payments), if and to the extent such failure or delay is caused by any circumstances beyond such Party's reasonable control, including but not limited to acts of God, flood, fire, earthquake, explosion, war, terrorism, invasion, riot or other civil unrest, strikes, labor stoppages or slowdowns or other industrial disturbances, or passage of law or any action taken by a governmental or public authority, including imposing an embargo. + +### 4. Amendment and Modification. + +Supabase may change this Agreement (except for any Orders) from time to time at its discretion. The date on which the Agreement was last modified will be updated at the top of this Agreement. Supabase will provide Customer with reasonable notice prior to any amendments or modifications taking effect, either by emailing the email address associated with Customer's account on the Services or by another method reasonably designed to provide notice to Customer. If Customer accesses or uses the Services after the effective date of the revised Agreement, such access and use will constitute Customer's acceptance of the revised Agreement beginning at the next Renewal Subscription Period or, if Customer enters into a new Order with Supabase, as of the date of execution of such Order. + +### 5. Waiver. + +No failure or delay by either Party in exercising any right or remedy available to it in connection with this Agreement will constitute a waiver of such right or remedy. No waiver under this Agreement will be effective unless made in writing and signed by an authorized representative of the Party granting the waiver. + +### 6. Severability. + +If any provision of this Agreement is invalid, illegal, or unenforceable in any jurisdiction, such invalidity, illegality, or unenforceability will not affect any other term or provision of this Agreement or invalidate or render unenforceable such term or provision in any other jurisdiction. Upon such determination that any term or other provision is invalid, illegal, or unenforceable, the Parties shall negotiate in good faith to modify this Agreement so as to effect their original intent as closely as possible in a mutually acceptable manner in order that the transactions contemplated hereby be consummated as originally contemplated to the greatest extent possible. + +### 7. Governing Law; Submission to Jurisdiction. + +This Agreement is governed by and construed in accordance with the internal laws of the State of California without giving effect to any choice or conflict of law provision or rule that would require or permit the application of the laws of any jurisdiction other than those of the State of California. Any legal suit, action, or proceeding arising out of or related to this Agreement or the licenses granted hereunder must be instituted in the federal courts of the United States or the courts of the State of California in each case located in San Francisco County, California and each Party irrevocably submits to the exclusive jurisdiction of such courts in any such suit, action, or proceeding. + +### 8. Assignment. + +Customer may not assign any of its rights or delegate any of its obligations hereunder, in each case whether voluntarily, involuntarily, by operation of law or otherwise, without the prior written consent of Supabase. Any purported assignment or delegation in violation of this Section will be null and void. No assignment or delegation will relieve the assigning or delegating Party of any of its obligations hereunder. This Agreement is binding upon and inures to the benefit of the Parties and their respective permitted successors and assigns. + +### 9. Export Regulation. + +The Services utilize software and technology that may be subject to US export control laws, including the US Export Administration Act and its associated regulations. Customer shall not, directly or indirectly, export, re-export, or release the Services or the underlying software or technology to, or make the Services or the underlying software or technology accessible from, any jurisdiction or country to which export, re-export, or release is prohibited by law, rule, or regulation. Customer shall comply with all applicable federal laws, regulations, and rules, and complete all required undertakings (including obtaining any necessary export license or other governmental approval), prior to exporting, re-exporting, releasing, or otherwise making the Services or the underlying software or technology available outside the US. + +### 10. US Government Rights. + +Each of the Documentation and the software components that constitute the Services is a "commercial item" as that term is defined at 48 C.F.R. § 2.101, consisting of "commercial computer software" and "commercial computer software documentation" as such terms are used in 48 C.F.R. § 12.212. Accordingly, if Customer is an agency of the US Government or any contractor therefor, Customer only receives those rights with respect to the Services and Documentation as are granted to all other end users, in accordance with (a) 48 C.F.R. § 227.7201 through 48 C.F.R. § 227.7204, with respect to the Department of Defense and their contractors, or (b) 48 C.F.R. § 12.212, with respect to all other US Government users and their contractors. + +### 11. Equitable Relief. + +Each Party acknowledges and agrees that a breach or threatened breach by such Party of any of its obligations under Section 6 or, in the case of Customer, Section 2.3, would cause the other Party irreparable harm for which monetary damages would not be an adequate remedy and agrees that, in the event of such breach or threatened breach, the other Party will be entitled to equitable relief, including a restraining order, an injunction, specific performance and any other relief that may be available from any court, without any requirement to post a bond or other security, or to prove actual damages or that monetary damages are not an adequate remedy. Such remedies are not exclusive and are in addition to all other remedies that may be available at law, in equity or otherwise. + +### 12. Publicity. + +Supabase may identify Customer as a user of the Services and may use Customer's name, logo, and other trademarks in Supabase's customer list, press releases, blog posts, advertisements, and website (and all use thereof and goodwill arising therefrom shall inure to the sole and exclusive benefit of Customer). Otherwise, neither Party may use the name, logo, or other trademarks of the other Party for any purpose without the other Party's prior written approval. diff --git a/apps/reference/docs/faq.md b/apps/reference/docs/faq.md new file mode 100755 index 00000000000..044a73f9ec0 --- /dev/null +++ b/apps/reference/docs/faq.md @@ -0,0 +1,38 @@ +--- +id: faq +title: FAQs +description: 'Most frequently asked questions regarding Supabase' +--- + +### Where do I find support? + +Choose the support channel relevant for your situation here: [supabase.com/support](https://supabase.com/support) + +### How much does it cost? + +Self-hosting Supabase is free. If you wish to use our cloud-platform, we provide [simple, predictable pricing](https://supabase.com/pricing). + +### How do I host Supabase? + +You can use the docker-compose script [here](https://github.com/supabase/supabase/tree/master/docker), and find detailed instructions [here](/docs/guides/hosting/overview). + +Supabase is an amalgamation of open source tools. Some of these tools are made by Supabase (like our [Realtime Server](https://github.com/supabase/realtime)), some we support directly (like [PostgREST](http://postgrest.org/en/v7.0.0/)), and some are third-party tools (like [KonSupabase is an amalgamation open sourceg](https://github.com/Kong/kong)). + +All of the tools we use in Supabase are MIT, Apache 2.0, or PostgreSQL licensed. This is one of the requirements to be considered for the Supabase stack. + +### How can you be a Firebase alternative if you're built with a relational database? + +We started Supabase because we love the functionality of Firebase, but we personally experienced the scaling issues that many others experienced. We chose Postgres because it's well-trusted, with phenomenal scalability. + +Our goal is to make Postgres as easy to use as Firebase, so that you no longer have to choose between usability and scalability. +We're sure that once you start using Postgres, you'll love it more than any other database. + +### Do you support `[some other database]`? + +We only support PostgreSQL. It's unlikely we'll ever move away from Postgres; however, you can [vote on a new database](https://github.com/supabase/supabase/discussions/6) if you want us to start development. + +### Do you have a library for `[some other language]`? + +We officially support [JavaScript](/docs/reference/javascript/installing) and [Dart](/docs/reference/dart/installing). + +You can find community-supported libraries in our [GitHub Community](https://github.com/supabase-community), and you can also help us to identify the most popular languages by [voting for a new client library](https://github.com/supabase/supabase/discussions/5). diff --git a/apps/reference/docs/going-into-prod.mdx b/apps/reference/docs/going-into-prod.mdx new file mode 100644 index 00000000000..1abefc05cdb --- /dev/null +++ b/apps/reference/docs/going-into-prod.mdx @@ -0,0 +1,63 @@ +--- +id: going-into-prod +title: 'Production Readiness' +description: 'Things to do before making your app publicly available' +--- + +After developing your project and deciding it's time to Go Live With Real Users, you should run through this checklist to ensure that your project is: + +- secure +- won't falter under the expected load +- remains available whilst in production + +## Security + +- Ensure RLS is enabled + - Tables that do not have RLS enabled with reasonable policies allow any client to access and modify their data. This is unlikely to be what you want in the majority of cases. + - [Learn more about RLS](/docs/guides/auth/row-level-security). +- Enable replication on tables containing sensitive data by enabling Row Level Security (RLS) and setting row security policies: + - Go to the Authentication > Policies page in the Supabase Dashboard to enable RLS and create security policies. + - Go to the Database > Replication page in the Supabase Dashboard to manage replication tables. +- Enable 2FA on GitHub. Since your GitHub account gives you administrative rights to your Supabase project, you should protect it with a strong password and 2FA using a U2F key or a TOTP app. +- Ensure email confirmations are enabled in the `Auth > Settings` page. +- Use a custom SMTP server for auth emails so that your users can see that the mails are coming from a trusted domain (preferably the same domain that your app is hosted on). Grab SMTP credentials from any major email provider such as SendGrid, AWS SES, etc. +- Think hard about how _you_ would abuse your service as an attacker, and mitigate. +- Review these [common cybersecurity threats](https://auth0.com/docs/security/prevent-threats). + +## Performance + +- Ensure that you have suitable indices to cater to your common query patterns + - [Learn more about indexes in Postgres](https://www.enterprisedb.com/postgres-tutorials/overview-postgresql-indexes). + - `pg_stat_statements` can help you [identify hot or slow queries](https://www.virtual-dba.com/blog/postgresql-performance-identifying-hot-and-slow-queries/). +- Perform load testing (preferably on a staging env) + - Tools like [k6](https://k6.io/) can simulate traffic from many different users. +- Upgrade your database if you require more resources. If you need anything beyond what is listed, contact enterprise@supabase.io. +- If you are expecting a surge in traffic (for a big launch), let the team know by sending your Project Ref to us (support@supabase.io) with more details about your launch. We'll keep an eye on your project. + +## Availability + +- Use your own SMTP credentials so that you have full control over the deliverability of your transactional auth emails (see Auth > Settings) + - you can grab SMTP credentials from any major email provider such as SendGrid, AWS SES, etc. + - The default rate limit for auth emails provided by Supabase is 30 new users per hour, if doing a major public announcement you will likely require more than this. +- If your application is on the free tier and is **not** expected to be queried at least once every 7 days, then it may be paused by Supabase to save on server resources. + - You can restore paused projects from the Supabase dashboard. + - Upgrade to Pro to guarantee that your project will not be paused for inactivity. +- Database backups are not available for download on the free tier. + - You can set up your own backup systems using tools like [pg_dump](https://www.postgresqltutorial.com/postgresql-backup-database/) or [wal-g](https://github.com/wal-g/wal-g). + - Nightly backups for Pro tier projects are available on the Supabase dashboard for up to 7 days. +- Upgrading to the Supabase Pro Tier will give you access to email support on support@supabase.io + +## Platform status + +If Supabase experiences outages, we keep you as informed as possible, as early as possible. We provide the following feedback channels: + +- Status page: [status.supabase.com](https://status.supabase.com/) +- RSS Feed: [status.supabase.com/history.rss](https://status.supabase.com/history.rss) +- Atom Feed: [status.supabase.com/history.atom](https://status.supabase.com/history.atom) +- Slack Alerts: You can receive updates via the RSS feed, using Slack's [built-in RSS functionality](https://slack.com/help/articles/218688467-Add-RSS-feeds-to-Slack)
`/feed subscribe https://status.supabase.com/history.atom` + +Make sure to review our [SLA](/docs/company/sla) for details on our commitment to Platform Stability. + +## Next steps + +This checklist is always growing so be sure to check back frequently, and also feel free to suggest additions and amendments by making a PR on [GitHub](https://github.com/supabase/supabase). diff --git a/apps/reference/docs/gotrue/client/.gitkeep b/apps/reference/docs/gotrue/client/.gitkeep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/apps/reference/docs/gotrue/server/about.md b/apps/reference/docs/gotrue/server/about.md new file mode 100644 index 00000000000..e84698de591 --- /dev/null +++ b/apps/reference/docs/gotrue/server/about.md @@ -0,0 +1,708 @@ +--- +id: about +title: GoTrue Auth Server +description: An SWT based API for managing users and issuing SWT tokens +--- + +GoTrue is a small open-source API written in golang, that can act as a self-standing +API service for handling user registration and authentication for JAM projects. + +It's based on OAuth2 and JWT and will handle user signup, authentication and custom +user data. + +## Configuration + +You may configure GoTrue using either a configuration file named `.env`, +environment variables, or a combination of both. Environment variables are prefixed with `GOTRUE_`, and will always have precedence over values provided via file. + +### Top-Level + +``` +GOTRUE_SITE_URL=https://example.netlify.com/ +``` + +`SITE_URL` - `string` **required** + +The base URL your site is located at. Currently used in combination with other settings to construct URLs used in emails. + +`OPERATOR_TOKEN` - `string` _Multi-instance mode only_ + +The shared secret with an operator (usually Netlify) for this microservice. Used to verify requests have been proxied through the operator and +the payload values can be trusted. + +`DISABLE_SIGNUP` - `bool` + +When signup is disabled the only way to create new users is through invites. Defaults to `false`, all signups enabled. + +`GOTRUE_RATE_LIMIT_HEADER` - `string` + +Header on which to rate limit the `/token` endpoint. + +### API + +``` +GOTRUE_API_HOST=localhost +PORT=9999 +``` + +`API_HOST` - `string` + +Hostname to listen on. + +`PORT` (no prefix) / `API_PORT` - `number` + +Port number to listen on. Defaults to `8081`. + +`API_ENDPOINT` - `string` _Multi-instance mode only_ + +Controls what endpoint Netlify can access this API on. + +`REQUEST_ID_HEADER` - `string` + +If you wish to inherit a request ID from the incoming request, specify the name in this value. + +### Database + +``` +GOTRUE_DB_DRIVER=mysql +DATABASE_URL=root@localhost/gotrue +``` + +`DB_DRIVER` - `string` **required** + +Chooses what dialect of database you want. Must be `mysql`. + +`DATABASE_URL` (no prefix) / `DB_DATABASE_URL` - `string` **required** + +Connection string for the database. + +`DB_NAMESPACE` - `string` + +Adds a prefix to all table names. + +**Migrations Note** + +Migrations are not applied automatically, so you will need to run them after +you've built gotrue. + +- If built locally: `./gotrue migrate` +- Using Docker: `docker run --rm gotrue gotrue migrate` + +### Logging + +``` +LOG_LEVEL=debug # available without GOTRUE prefix (exception) +GOTRUE_LOG_FILE=/var/log/go/gotrue.log +``` + +`LOG_LEVEL` - `string` + +Controls what log levels are output. Choose from `panic`, `fatal`, `error`, `warn`, `info`, or `debug`. Defaults to `info`. + +`LOG_FILE` - `string` + +If you wish logs to be written to a file, set `log_file` to a valid file path. + +### JSON Web Tokens (JWT) + +``` +GOTRUE_JWT_SECRET=supersecretvalue +GOTRUE_JWT_EXP=3600 +GOTRUE_JWT_AUD=netlify +``` + +`JWT_SECRET` - `string` **required** + +The secret used to sign JWT tokens with. + +`JWT_EXP` - `number` + +How long tokens are valid for, in seconds. Defaults to 3600 (1 hour). + +`JWT_AUD` - `string` + +The default JWT audience. Use audiences to group users. + +`JWT_ADMIN_GROUP_NAME` - `string` + +The name of the admin group (if enabled). Defaults to `admin`. + +`JWT_DEFAULT_GROUP_NAME` - `string` + +The default group to assign all new users to. + +### External Authentication Providers + +We support `bitbucket`, `github`, `gitlab`, and `google` for external authentication. +Use the names as the keys underneath `external` to configure each separately. + +``` +GOTRUE_EXTERNAL_GITHUB_CLIENT_ID=myappclientid +GOTRUE_EXTERNAL_GITHUB_SECRET=clientsecretvaluessssh +``` + +No external providers are required, but you must provide the required values if you choose to enable any. + +`EXTERNAL_X_ENABLED` - `bool` + +Whether this external provider is enabled or not + +`EXTERNAL_X_CLIENT_ID` - `string` **required** + +The OAuth2 Client ID registered with the external provider. + +`EXTERNAL_X_SECRET` - `string` **required** + +The OAuth2 Client Secret provided by the external provider when you registered. + +`EXTERNAL_X_REDIRECT_URI` - `string` **required for gitlab** + +The URI a OAuth2 provider will redirect to with the `code` and `state` values. + +`EXTERNAL_X_URL` - `string` + +The base URL used for constructing the URLs to request authorization and access tokens. Used by `gitlab` only. Defaults to `https://gitlab.com`. + +### E-Mail + +Sending email is not required, but highly recommended for password recovery. +If enabled, you must provide the required values below. + +``` +GOTRUE_SMTP_HOST=smtp.mandrillapp.com +GOTRUE_SMTP_PORT=587 +GOTRUE_SMTP_USER=smtp-delivery@example.com +GOTRUE_SMTP_PASS=correcthorsebatterystaple +GOTRUE_SMTP_ADMIN_EMAIL=support@example.com +GOTRUE_MAILER_SUBJECTS_CONFIRMATION="Please confirm" +``` + +`SMTP_ADMIN_EMAIL` - `string` **required** + +The `From` email address for all emails sent. + +`SMTP_HOST` - `string` **required** + +The mail server hostname to send emails through. + +`SMTP_PORT` - `number` **required** + +The port number to connect to the mail server on. + +`SMTP_USER` - `string` + +If the mail server requires authentication, the username to use. + +`SMTP_PASS` - `string` + +If the mail server requires authentication, the password to use. + +`SMTP_MAX_FREQUENCY` - `number` + +Controls the minimum amount of time that must pass before sending another signup confirmation or password reset email. The value is the number of seconds. Defaults to 900 (15 minutes). + +`MAILER_AUTOCONFIRM` - `bool` + +If you do not require email confirmation, you may set this to `true`. Defaults to `false`. + +`MAILER_SECURE_EMAIL_CHANGE_ENABLED` - `bool` + +If `true`, send an email to both the user's current and new email with a confirmation link, otherwise send an email with confirmation link only to new email. Defaults to `true`. + +`MAILER_URLPATHS_INVITE` - `string` + +URL path to use in the user invite email. Defaults to `/`. + +`MAILER_URLPATHS_CONFIRMATION` - `string` + +URL path to use in the signup confirmation email. Defaults to `/`. + +`MAILER_URLPATHS_RECOVERY` - `string` + +URL path to use in the password reset email. Defaults to `/`. + +`MAILER_URLPATHS_EMAIL_CHANGE` - `string` + +URL path to use in the email change confirmation email. Defaults to `/`. + +`MAILER_SUBJECTS_INVITE` - `string` + +Email subject to use for user invite. Defaults to `You have been invited`. + +`MAILER_SUBJECTS_CONFIRMATION` - `string` + +Email subject to use for signup confirmation. Defaults to `Confirm Your Signup`. + +`MAILER_SUBJECTS_RECOVERY` - `string` + +Email subject to use for password reset. Defaults to `Reset Your Password`. + +`MAILER_SUBJECTS_MAGIC_LINK` - `string` + +Email subject to use for magic link email. Defaults to `Your Magic Link`. + +`MAILER_SUBJECTS_EMAIL_CHANGE` - `string` + +Email subject to use for email change confirmation. Defaults to `Confirm Email Change`. + +`MAILER_TEMPLATES_INVITE` - `string` + +URL path to an email template to use when inviting a user. +`SiteURL`, `Email`, and `ConfirmationURL` variables are available. + +Default Content (if template is unavailable): + +```html +

You have been invited

+ +

+ You have been invited to create a user on {{ .SiteURL }}. Follow this link to + accept the invite: +

+

Accept the invite

+``` + +`MAILER_TEMPLATES_CONFIRMATION` - `string` + +URL path to an email template to use when confirming a signup. +`SiteURL`, `Email`, and `ConfirmationURL` variables are available. + +Default Content (if template is unavailable): + +```html +

Confirm your signup

+ +

Follow this link to confirm your user:

+

Confirm your mail

+``` + +`MAILER_TEMPLATES_RECOVERY` - `string` + +URL path to an email template to use when resetting a password. +`SiteURL`, `Email`, and `ConfirmationURL` variables are available. + +Default Content (if template is unavailable): + +```html +

Reset Password

+ +

Follow this link to reset the password for your user:

+

Reset Password

+``` + +`MAILER_TEMPLATES_MAGIC_LINK` - `string` + +URL path to an email template to use when sending magic link. +`SiteURL`, `Email`, and `ConfirmationURL` variables are available. + +Default Content (if template is unavailable): + +```html +

Magic Link

+ +

Follow this link to login:

+

Log In

+``` + +`MAILER_TEMPLATES_EMAIL_CHANGE` - `string` + +URL path to an email template to use when confirming the change of an email address. +`SiteURL`, `Email`, `NewEmail`, and `ConfirmationURL` variables are available. + +Default Content (if template is unavailable): + +```html +

Confirm Change of Email

+ +

+ Follow this link to confirm the update of your email from {{ .Email }} to {{ + .NewEmail }}: +

+

Change Email

+``` + +## Endpoints + +GoTrue exposes the following endpoints: + +### **GET /settings** + +Returns the publicly available settings for this gotrue instance. + +```json +{ + "external": { + "bitbucket": true, + "github": true, + "gitlab": true, + "google": true + }, + "disable_signup": false, + "autoconfirm": false +} +``` + +### **POST /signup** + +Register a new user with an email and password. + +```json +{ + "email": "email@example.com", + "password": "secret" +} +``` + +Returns: + +```json +{ + "id": "11111111-2222-3333-4444-5555555555555", + "email": "email@example.com", + "confirmation_sent_at": "2016-05-15T20:49:40.882805774-07:00", + "created_at": "2016-05-15T19:53:12.368652374-07:00", + "updated_at": "2016-05-15T19:53:12.368652374-07:00" +} +``` + +### **POST /invite** + +Invites a new user with an email. +This endpoint requires the `service_role` or `supabase_admin` JWT set as an Auth Bearer header: + +e.g. + +```json +headers: { + "Authorization" : "Bearer eyJhbGciOiJI...M3A90LCkxxtX9oNP9KZO" +} +``` + +```json +{ + "email": "email@example.com" +} +``` + +Returns: + +```json +{ + "id": "11111111-2222-3333-4444-5555555555555", + "email": "email@example.com", + "confirmation_sent_at": "2016-05-15T20:49:40.882805774-07:00", + "created_at": "2016-05-15T19:53:12.368652374-07:00", + "updated_at": "2016-05-15T19:53:12.368652374-07:00", + "invited_at": "2016-05-15T19:53:12.368652374-07:00" +} +``` + +### **POST /verify** + +Verify a registration or a password recovery. Type can be `signup` or `recovery` or `invite` +and the `token` is a token returned from either `/signup` or `/recover`. + +```json +{ + "type": "signup", + "token": "confirmation-code-delivered-in-email" +} +``` + +`password` is required for signup verification if no existing password exists. + +Returns: + +```json +{ + "access_token": "jwt-token-representing-the-user", + "token_type": "bearer", + "expires_in": 3600, + "refresh_token": "a-refresh-token", + "type": "signup | recovery | invite" +} +``` + +### **GET /verify** + +Verify a registration or a password recovery. Type can be `signup` or `recovery` or `magiclink` or `invite` +and the `token` is a token returned from either `/signup` or `/recover` or `/magiclink`. + +query params: + +```json +{ + "type": "signup", + "token": "confirmation-code-delivered-in-email" +} +``` + +User will be logged in and redirected to: + +```json +SITE_URL/#access_token=jwt-token-representing-the-user&token_type=bearer&expires_in=3600&refresh_token=a-refresh-token&type=invite +``` + +Your app should detect the query params in the fragment and use them to set the session (supabase-js does this automatically) + +You can use the `type` param to redirect the user to a password set form in the case of `invite` or `recovery`, +or show an account confirmed/welcome message in the case of `signup`, or direct them to some additional onboarding flow + +### **POST /magiclink** + +Magic Link. Will deliver a link (e.g. `/verify?type=magiclink&token=fgtyuf68ddqdaDd`) to the user based on +email address which they can use to redeem an access_token. + +By default Magic Links can only be sent once every 60 seconds + +```json +{ + "email": "email@example.com" +} +``` + +Returns: + +```json +{} +``` + +when clicked the magic link will redirect the user to `#access_token=x&refresh_token=y&expires_in=z&token_type=bearer&type=magiclink` (see `/verify` above) + +### **POST /recover** + +Password recovery. Will deliver a password recovery mail to the user based on +email address. + +By default recovery links can only be sent once every 60 seconds + +```json +{ + "email": "email@example.com" +} +``` + +Returns: + +```json +{} +``` + +### **POST /token** + +This is an OAuth2 endpoint that currently implements +the password and refresh_token grant types + +query params: + +``` +?grant_type=password +``` + +body: + +```json +{ + "email": "name@domain.com", + "password": "somepassword" +} +``` + +or + +query params: + +``` +grant_type=refresh_token +``` + +body: + +```json +{ + "refresh_token": "a-refresh-token" +} +``` + +Once you have an access token, you can access the methods requiring authentication +by settings the `Authorization: Bearer YOUR_ACCESS_TOKEN_HERE` header. + +Returns: + +```json +{ + "access_token": "jwt-token-representing-the-user", + "token_type": "bearer", + "expires_in": 3600, + "refresh_token": "a-refresh-token" +} +``` + +### **GET /user** + +Get the JSON object for the logged in user (requires authentication) + +Returns: + +```json +{ + "id": "11111111-2222-3333-4444-5555555555555", + "email": "email@example.com", + "confirmation_sent_at": "2016-05-15T20:49:40.882805774-07:00", + "created_at": "2016-05-15T19:53:12.368652374-07:00", + "updated_at": "2016-05-15T19:53:12.368652374-07:00" +} +``` + +### **PUT /user** + +Update a user (Requires authentication). Apart from changing email/password, this +method can be used to set custom user data. + +```json +{ + "email": "new-email@example.com", + "password": "new-password", + "data": { + "key": "value", + "number": 10, + "admin": false + } +} +``` + +Returns: + +```json +{ + "id": "11111111-2222-3333-4444-5555555555555", + "email": "email@example.com", + "confirmation_sent_at": "2016-05-15T20:49:40.882805774-07:00", + "created_at": "2016-05-15T19:53:12.368652374-07:00", + "updated_at": "2016-05-15T19:53:12.368652374-07:00" +} +``` + +### **POST /admin/users** + +Creates a new user. Requires your `service_role` API key and thus should only be +used in secure server-side environments. + +```json +{ + "email": "new-email@example.com", + "password": "new-password", + "data": { + "key": "value", + "number": 10, + "admin": false + } +} +``` + +Returns: + +```json +{ + "id": "11111111-2222-3333-4444-5555555555555", + "aud": "authenticated", + "role": "authenticated", + "email": "email@example.com", + "app_metadata": { + "provider": "email" + }, + "user_metadata": null, + "created_at": "2016-05-15T19:53:12.368652374-07:00", + "updated_at": "2016-05-15T19:53:12.368652374-07:00" +} +``` + +### **GET /admin/users/{user_id}** + +Gets a user. Requires your `service_role` API key and thus should only be used +in secure server-side environments. + +Returns: + +```json +{ + "id": "11111111-2222-3333-4444-5555555555555", + "aud": "authenticated", + "role": "authenticated", + "email": "email@example.com", + "app_metadata": { + "provider": "email" + }, + "user_metadata": {}, + "created_at": "2016-05-15T19:53:12.368652374-07:00", + "updated_at": "2016-05-15T19:53:12.368652374-07:00" +} +``` + +### **PUT /admin/users/{user_id}** + +Updates a user. Requires your `service_role` API key and thus should only be +used in secure server-side environments. + +```json +{ + "email": "email@example.com", + "password": "updated-password", + "data": { + "key": "updated-value", + "number": 10, + "admin": false + } +} +``` + +Returns: + +```json +{ + "id": "11111111-2222-3333-4444-5555555555555", + "aud": "authenticated", + "role": "authenticated", + "email": "email@example.com", + "app_metadata": { + "provider": "email" + }, + "user_metadata": {}, + "created_at": "2016-05-15T19:53:12.368652374-07:00", + "updated_at": "2016-05-15T19:53:12.368652374-07:00" +} +``` + +### **DELETE /admin/users/{user_id}** + +Deletes a user. Requires your `service_role` API key and thus should only be +used in secure server-side environments. + +### **POST /logout** + +Logout a user (Requires authentication). + +This will revoke all refresh tokens for the user. Remember that the JWT tokens +will still be valid for stateless auth until they expires. + +### **GET /authorize** + +Get access_token from external oauth provider + +query params: + +``` +provider=google | bitbucket | github | gitlab +``` + +Redirects to provider and then to `/callback` + +### **GET /callback** + +External provider should redirect to here + +Redirects to `#access_token=&refresh_token=&expires_in=3600&provider=` + +## Pre-built + +- [Docker](https://hub.docker.com/repository/docker/supabase/gotrue) diff --git a/apps/reference/docs/guides/api.mdx b/apps/reference/docs/guides/api.mdx new file mode 100644 index 00000000000..3d9c80e88f1 --- /dev/null +++ b/apps/reference/docs/guides/api.mdx @@ -0,0 +1,402 @@ +--- +id: api +title: APIs +description: Auto-generating and Realtime APIs. +sidebar_label: Overview +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +## Overview + +Supabase generates three types of API directly from your database schema. + +- REST - interact with your database through a restful interface. +- Realtime - listen to database changes. +- GraphQL - [in beta](https://supabase.com/blog/2021/12/03/pg-graphql). + +The APIs are: + +- **Instant and auto-generated.**
As you update your database the changes are immediately accessible through your API. +- **Self documenting.**
Supabase generates documentation in the Dashboard which updates as you make database changes. +- **Secure.**
The API is configured to work with PostgreSQL's Row Level Security, provisioned behind an API gateway with key-auth enabled. +- **Fast.**
Our benchmarks for basic reads are more than 300% faster than Firebase. The API is a very thin layer on top of Postgres, which does most of the heavy lifting. +- **Scalable.**
The API can serve thousands of simultaneous requests, and works well for Serverless workloads. + + +### REST API {#rest-api-overview} + +Supabase provides a RESTful API using [PostgREST](https://postgrest.org/). This is a very thin API layer on top of Postgres. +It provides everything you need from a CRUD API: + +- Basic CRUD operations +- Deeply nested joins, allowing you to fetch data from multiple tables in a single fetch +- Works with Postgres Views +- Works with Postgres Functions +- Works with the Postgres security model - including Row Level Security, Roles, and Grants. + + + +### GraphQL API {#graphql-api-overview} + +:::note + +GraphQL is in Beta, and may have breaking changes. It is only available on self-hosted setups and Supabase projects created after 28th March 2022. + +::: + +GraphQL in Supabase works through [pg_graphql](https://supabase.com/blog/2021/12/03/pg-graphql), an open source PostgreSQL extension for GraphQL. + +### Realtime API {#realtime-api-overview} + +Supabase provides a Realtime API using [Realtime](https://github.com/supabase/realtime). You can use this to listen to database changes over websockets. +Realtime leverages PostgreSQL's built-in logical replication. You can manage your Realtime API simply by managing Postgres publications. + +## Getting started + +All APIs are auto-created from Database tables. After you have added tables or functions to your database, you can use the APIs provided. + +### Creating API Routes + +API routes are automatically created when you create Postgres Tables, Views, or Functions. + +Let's create our first +API route by creating a table called `todos` to store tasks. +This creates a corresponding route `todos` which can accept `GET`, `POST`, `PATCH`, & `DELETE` requests. + + + + + +1. Go to the [Table editor](https://app.supabase.com/project/_/editor) page in the Dashboard. +1. Click **New Table** and create a table with the name `todos`. +1. Click **Save**. +1. Click **New Column** and create a column with the name `task` and type `text`. +1. Click **Save**. + + + + + + +```sql +-- Create a table called "todos" with a column to store tasks. + +create table todos ( + id bigint generated by default as identity primary key, + task text check (char_length(task) > 3) +); +``` + + + + +### API URL and Keys + +Every Supabase project has a unique API URL. Your API is secured behind an API gateway which requires an API Key for every request. + +1. Go to the [Settings](https://app.supabase.com/project/_/settings/general) page in the Dashboard. +2. Click **API** in the sidebar. +3. Find your API `URL`, `anon`, and `service_role` keys on this page. + + + +The REST API and the GraphQL API are both accessible through this URL: + +- REST: `https://.supabase.co/rest/v1` +- GraphQL: `https://.supabase.co/graphql/v1` + +Both of these routes require the `anon` key to be passed through an `apikey` header. + +#### API Keys + +You are provided with two keys: + +- an `anon` key, which is safe to be used in a browser context. +- a `service_role` key, which should only be used on a server. This key can bypass Row Level Security. NEVER use this key in a browser. + + +### Accessing the docs in the Dashboard + +#### REST API {#rest-api-dashboard-docs} + +Supabase generates documentation in the [Dashboard](https://app.supabase.com) which updates as you make database changes. +Let's view the documentation for a `countries` table which we created in our database. + +1. Go to the [API](https://app.supabase.com/project/_/api) page in the Dashboard. +2. Find the `countries` table under **Tables and Views** in the sidebar. +3. Switch between the JavaScript and the cURL docs using the tabs. + + + +#### GraphQL + +The GraphQL Endpoint that we provide (`https://.supabase.co/graphql/v1`) is compatible with any GraphiQL implementation that can pass an `apikey` header. +Some suggested applications: + +- [paw.cloud](https://paw.cloud) +- [insomnia.rest](https://insomnia.rest) +- [postman.com/graphql](https://www.postman.com/graphql/) +- Self-hosted GraphiQL: GraphiQL can be served through a simple HTML file. See [this discussion](https://github.com/supabase/supabase/discussions/6144) for more details. + +## Using the API + + +### REST API + +You can interact with your API directly via HTTP requests, or you can use the client libraries which we provide. + +Let's see how to make a request to the `todos` table which we created in the first step, +using the API URL (`SUPABASE_URL`) and Key (`SUPABASE_ANON_KEY`) we provided: + + + + + + +```javascript +// Initialize the JS client +import { createClient } from '@supabase/supabase-js' +const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY) + +// Make a request +const { data: todos, error } = await supabase + .from('todos') + .select('*') +``` + + + + +```bash +# Append /rest/v1/ to your URL, and then use the table name as the route +curl '/rest/v1/todos' \ +-H "apikey: " \ +-H "Authorization: Bearer " +``` + + + + +JS Reference: [select()](/docs/reference/javascript/select), +[insert()](/docs/reference/javascript/insert), +[update()](/docs/reference/javascript/update), +[upsert()](/docs/reference/javascript/upsert), +[delete()](/docs/reference/javascript/delete), +[rpc()](/docs/reference/javascript/rpc) (call Postgres functions). + + +### GraphQL API + +:::note + +To rebuild your GraphQL schema from the SQL schema, call `select graphql.rebuild_schema();`. +Be sure to rebuild the GraphQL schema after altering the SQL schema. + +::: + +You can use any GraphQL client with the Supabase GraphQL API. For our GraphQL example we will use [urql](https://formidable.com/open-source/urql/docs/). + + + + + +```javascript +import { createClient, useQuery } from 'urql' + +// Prepare API key and Authorization header +const headers = { + apikey: , + authorization: `Bearer: ${ +} + +// Create GraphQL client +// See: https://formidable.com/open-source/urql/docs/basics/react-preact/#setting-up-the-client +const client = createClient({ + url: '/graphql/v1', + fetchOptions: function createFetchOptions() { + return { headers } + }, +}) + +// Prepare our GraphQL query +const TodosQuery = ` + query { + todosCollection { + edges { + node { + id + title + } + } + } + } +` + +// Query for the data (React) +const [result, reexecuteQuery] = useQuery({ + query: TodosQuery, +}) + +// Read the result +const { data, fetching, error } = result +``` + + + + +```bash +# Append /graphql/v1/ to your URL, and then use the table name as the route +curl --request POST '/graphql/v1' \ +-H 'apikey: ' \ +-H 'Authorization: Bearer ' \ +-d '{ "query":"{ todos(first: 3) { edges { node { id } } } }" }' +``` + + + + + +### Realtime API + +By default Realtime is disabled on your database. Let's turn on Realtime for the `todos` table. + + + + + +1. Go to the [Database](https://app.supabase.com/project/_/database/tables) page in the Dashboard. +2. Click on **Replication** in the sidebar. +3. Control which database events are sent by toggling **Insert**, **Update**, and **Delete**. +4. Control which tables broadcast changes by selecting **Source** and toggling each table. + + + + + + +```sql +alter publication supabase_realtime add table todos; +``` + + + + +From the client, we can listen to any new data that is inserted into the `todos` table: + +```javascript +// Initialize the JS client +import { createClient } from '@supabase/supabase-js' +const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY) + +// Create a function to handle inserts +const handleInserts = (payload) => { + console.log('Change received!', payload) +} + +// Listen to inserts +const { data: todos, error } = await supabase + .from('todos') + .on('INSERT', handleInserts) + .subscribe() +``` + +Use [subscribe()](/docs/reference/javascript/subscribe) to listen to database changes. +The Realtime API works through PostgreSQL's replication functionality. Postgres sends database changes to a [publication](/docs/guides/database/replication#publications) +called `supabase_realtime`, and by managing this publication you can control which data is broadcast. + +## API Security + + +### Securing your Routes + + +Your API is designed to work with Postgres Row Level Security (RLS). If you use Supabase [Auth](/docs/guides/auth), you can restrict data based on the logged-in user. +To control access to your data, you can use [Policies](/docs/guides/auth#policies). +When you create a table in Postgres, Row Level Security is disabled by default. To enable RLS: + + + + + +1. Go to the [Authentication](https://app.supabase.com/project/_/auth/users) page in the Dashboard. +2. Click on **Policies** in the sidebar. +3. Select **Enable RLS** to enable Row Level Security. + + + + +```sql +alter table todos enable row level security; +``` + + + + +### The `service_role` key + +Never expose the `service_role` key in a browser or anywhere where a user can see it. This Key can is designed to bypass Row Level Security - so it should only be used on a private server. + +We have [partnered with GitHub](https://supabase.com/blog/2022/03/28/community-day#supabase-is-now-a-github-secret-scanning-partner) to scan for Supabase `service_role` keys pushed to public repositories. +If they detect any keys with service_role privileges being pushed to GitHub, they will forward the API key to us, so that we can automatically revoke the detected secrets and notify you, protecting your data against malicious actors. + +### Safeguards towards accidental deletes and updates + +For all projects, by default, the Postgres extension [safeupdate](https://github.com/eradman/pg-safeupdate) is enabled for all queries coming from the API. +This ensures that any `delete()` or `update()` would fail if there are no accompanying filters provided. +To confirm that safeupdate is enabled for queries going through the API of your project, the following query could be run: +```sql +select usename,useconfig from pg_shadow where usename = 'authenticator' ; +``` + +The expected value for `useconfig` should be: +``` +["session_preload_libraries=supautils, safeupdate"] +``` diff --git a/apps/reference/docs/guides/api/generating-types.mdx b/apps/reference/docs/guides/api/generating-types.mdx new file mode 100644 index 00000000000..db7882f66d0 --- /dev/null +++ b/apps/reference/docs/guides/api/generating-types.mdx @@ -0,0 +1,118 @@ +--- +id: generating-types +title: "Generating Types" +description: How to generate types for your API and Supabase libraries. +--- + +Supabase APIs are generated from your database, which means that we can use database introspection to generate type-safe API definitions. + +### Generating types from OpenAPI specification + +Supabase generates an OpenAPI specification file for your database which can be used to generate your data types for usage with TypeScript. + +The OpenAPI specification for your Supabase project can be accessed as follows: + +```txt +https://your-project.supabase.co/rest/v1/?apikey=your-anon-key +``` + +Using the open source [openapi-typescript](https://github.com/drwpow/openapi-typescript#%EF%B8%8F-reading-specs-from-remote-resource) tool you can generate your types and store them locally: + +```bash +npx openapi-typescript https://your-project.supabase.co/rest/v1/?apikey=your-anon-key --output types/supabase.ts +``` + +Important notes: + +- Since the generator uses JSON API, there is no way to determine if a column is an Array. It will generate array types as `string`, even though Supabase handles this automatically and returns arrays. + You can fix this manually in the files by changing the type, e.g. `names: string` -> `names: string[]` +- The types won't automatically stay in sync with your database, so make sure to regenerate your types after your make changes to your database. + +After you have generated your types, you can use them in your TypeScript projects: + +```ts +import { NextApiRequest, NextApiResponse } from "next" +import { createClient } from "@supabase/supabase-js" +import { definitions } from "../../types/supabase" + +const supabase = createClient( + process.env.NEXT_PUBLIC_SUPABASE_URL, + process.env.SUPABASE_SECRET_KEY +) + +export default async (req: NextApiRequest, res: NextApiResponse) => { + const allOnlineUsers = await supabase + .from("users") + .select("*") + .eq("status", "ONLINE") + res.status(200).json(allOnlineUsers) +}; +``` + +For more advance type-support, check out [`postgrest-js-tools`](https://github.com/mzalevski/postgrest-js-tools). + +## Update types automatically with GitHub Actions + +One way to keep your type definitions in sync with your database is to set up a GitHub action that runs on a schedule. + +The following script can be run in your terminal to produce the file `types/database/index.ts`. +``` +npx openapi-typescript https://your-project.supabase.co/rest/v1/?apikey=your-anon-key --output types/database/index.ts +``` + +You can add this script to your `package.json` and run it using `npm run update-types`: + +``` +"update-types": "npx openapi-typescript \"${SUPABASE_URL}/rest/v1/?apikey=${SUPABASE_ANON_KEY}\" --version=2 --output types/database/index.ts" +``` + +You can use GitHub actions to generate this file automatically. This script will commit the change to your repo every night. +Create a file `.github/workflows/update-types.yml` and add the following snippet into this file to define the action along with the environment variables. + +```yml +name: Update database types + +on: + schedule: + # sets the action to run daily. You can modify this to run the action more or less frequently + - cron: '0 0 * * *' + +jobs: + update: + runs-on: ubuntu-latest + env: + SUPABASE_URL: ${{secrets.SUPABASE_URL}} + SUPABASE_ANON_KEY: ${{secrets.SUPABASE_ANON_KEY}} + steps: + - uses: actions/checkout@v2 + with: + persist-credentials: false + fetch-depth: 0 + - uses: actions/setup-node@v2.1.5 + with: + node-version: 14 + - run: npm run update-types + - name: check for file changes + id: git_status + run: | + echo "::set-output name=status::$(git status -s)" + - name: Commit files + if: ${{contains(steps.git_status.outputs.status, ' ')}} + run: | + git add types/database/index.ts + git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com" + git config --local user.name "github-actions[bot]" + git commit -m "Update database types" -a + - name: Push changes + if: ${{contains(steps.git_status.outputs.status, ' ')}} + uses: ad-m/github-push-action@master + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + branch: ${{ github.ref }} +``` + +Alternatively, you can use a community-supported GitHub action: [generate-supabase-db-types-github-action](https://github.com/lyqht/generate-supabase-db-types-github-action). + +## Resources + +- [Generating Supabase types with GitHub Actions](https://blog.esteetey.dev/how-to-create-and-test-a-github-action-that-generates-types-from-supabase-database) \ No newline at end of file diff --git a/apps/reference/docs/guides/auth.mdx b/apps/reference/docs/guides/auth.mdx new file mode 100644 index 00000000000..6efba7332ff --- /dev/null +++ b/apps/reference/docs/guides/auth.mdx @@ -0,0 +1,167 @@ +--- +id: auth +title: Auth +description: Use Supabase to Authenticate and Authorize your users. +sidebar_label: Overview +--- + +import Link from '@docusaurus/Link' +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' +import providers from '@site/src/data/authProviders' + + + +## Overview + +There are two parts to every Auth system: + +- **Authentication:** should this person be allowed in? If yes, who are they? +- **Authorization:** once they are in, what are they allowed to do? + +Supabase Auth is designed to work either as a standalone product, or deeply integrated with the other Supabase products. +Postgres is at the heart of everything we do, and the Auth system follows this principle. We leverage Postgres' built-in Auth functionality wherever possible. + +## Authentication + +You can authenticate your users in several ways: + +- Email & password. +- Magic links (one-click logins). +- Social providers. +- Phone logins. + +### Providers + +We provide a suite of Providers and login methods. + +
+
+ {providers.map((x) => ( +
+ +
+
+ {x.logo && {x.name}} +

{x.name}

+

+ {x.official ? + Official + : + + Unofficial + + } +

+
+
+
+ Platform: + {x.platform.toString()} +
+
+ Self-Hosted: + {x.selfHosted.toString()} +
+
+
+ +
+ ))} +
+
+ + +### Simple interface + +You can enable third-providers with the click of a button by navigating to Authentication > Settings > External OAuth Providers and inputting your `Client ID` and `Secret` for each. + +![OAuth Logins.](/img/supabase-oauth-logins.png) + + +## Authorization + + +When you need granular authorization rules, nothing beats PostgreSQL's Row Level Security (RLS). + +Policies are PostgreSQL's rule engine. They are incredibly powerful and flexible, allowing you to write complex SQL rules which fit your unique business needs. + +Get started with our [Row Level Security Guides](/docs/guides/auth/row-level-security). + + +### Row Level Security + +Authentication only gets you so far. When you need granular authorization rules, nothing beats PostgreSQL's [Row Level Security (RLS)](https://www.postgresql.org/docs/current/ddl-rowsecurity.html). Supabase makes it simple to turn RLS on and off. + + + +### Policies + +[Policies](https://www.postgresql.org/docs/current/sql-createpolicy.html) are PostgreSQL's rule engine. They are incredibly powerful and flexible, allowing you to write complex SQL rules which fit your unique business needs. + + + +With policies, your database becomes the rules engine. Instead of repetitively filtering your queries, like this ... + +```js +const loggedInUserId = 'd0714948' +let { data, error } = await supabase + .from('users') + .select('user_id, name') + .eq('user_id', loggedInUserId) + +// console.log(data) +// => { id: 'd0714948', name: 'Jane' } +``` + +... you can simply define a rule on your database table, `auth.uid() = user_id`, and your request will return the rows which pass the rule, even when you remove the filter from your middleware: + +```js +let { data, error } = await supabase.from('users').select('user_id, name') + +// console.log(data) +// Still => { id: 'd0714948', name: 'Jane' } +``` + + +### How It Works + +1. A user signs up. Supabase creates a new user in the `auth.users` table. +2. Supabase returns a new JWT, which contains the user's `UUID`. +3. Every request to your database also sends the JWT. +4. Postgres inspects the JWT to determine the user making the request. +5. The user's UID can be used in policies to restrict access to rows. + +Supabase provides a special function in Postgres, `auth.uid()`, which extracts the user's UID from the JWT. This is especially useful when creating policies. + + + +## User Management + +Supabase makes it simple to manage your users. + + + +When users sign up, Supabase assigns them a unique ID. You can reference this ID anywhere in your database. For example, you might create a `profiles` table referencing `id` in the `auth.users` table using a `user_id` field. + +Supabase provides the routes to [sign up](/docs/reference/javascript/auth-signup), [log in](/docs/reference/javascript/auth-signin), +[log out](/docs/reference/javascript/auth-signout), and manage users in your apps and websites. + + +## Next Steps + +- Sign in: [app.supabase.com](https://app.supabase.com) diff --git a/apps/reference/docs/guides/auth/auth-apple.mdx b/apps/reference/docs/guides/auth/auth-apple.mdx new file mode 100644 index 00000000000..fc3f776eca1 --- /dev/null +++ b/apps/reference/docs/guides/auth/auth-apple.mdx @@ -0,0 +1,214 @@ +--- +id: auth-apple +title: 'Login with Apple' +description: Add Apple OAuth to your Supabase project +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +To enable Apple Auth for your project, you need to set up an Apple OAuth application and add the application credentials to your Supabase Dashboard. + +## Overview + +Apple OAuth consists of six broad steps: + +- Obtaining an `App Id` with “Sign In with Apple” capabilities. +- Obtaining a `Services Id` - this will serve as the `client_id`. +- Obtaining a `secret key` that will be used to get our `client_secret`. +- Generating the `client_secret` using the `secret key`. +- Add your `client id` and `client secret` keys to your [Supabase Project](https://app.supabase.com). +- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js). + +## Steps + +### Access your Apple Developer account + +- Go to [developer.apple.com](https://developer.apple.com). +- Click on `Account` at the top right to log in. + +![Apple Developer Portal.](/img/guides/auth-apple/apple-developer-portal.png) + +### Obtain an App ID + +- Go to `Certificates, Identifiers & Profiles`. +- Click on `Identifiers` at the left. +- Click on the `+` sign in the upper left next to `Identifiers`. +- Select `App IDs` and click `Continue`. +- Select type `App` and click `Continue`. +- Fill out your app information: + - App description. + - Bundle ID (Apple recommends reverse-domain name style, so if your domain is acme.com and your app is called roadrunner, use: "com.acme.roadrunner"). + - Scroll down and check `Sign In With Apple`. + - Click `Continue` at the top right. + - Click `Register` at the top right. + +### Obtain a Services ID + +This will serve as the `client_id` when you make API calls to authenticate the user. + +- Go to `Certificates, Identifiers & Profiles`. +- Click on `Identifiers` at the left. +- Click on the `+` sign in the upper left next to `Identifiers`. +- Select `Services IDs` and click `Continue`. +- Fill out your information: + - App description. + - Bundle ID (you can't use the same Bundle ID from the previous step, but you can just add something to the beginning, such as "app." to make it app.com.acme.roadrunner"). + - SAVE THIS ID -- this ID will become your `client_id` later. + - Click `Continue` at the top right. + - Click `Register` at the top right. + +### Find your callback URL + +The next step requires a callback URL, which looks like this: + +`https://.supabase.co/auth/v1/callback` + +- Go to your [Supabase Project Dashboard](https://app.supabase.com). +- Click on the `Settings` icon at the bottom of the left sidebar. +- Click on `API` in the list. +- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard. +- Now just add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`. + + + +### Configure your Services ID + +- Under `Identifiers`, click on your newly-created Services ID. +- Check the box next to `Sign In With Apple` to enable it. +- Click `Configure` to the right. +- Make sure your newly created Bundle ID is selected under `Primary App ID` +- Add your domain to the `Domains and Subdomains` box (do not add `https://`, just add the domain). +- In the `Return URLs` box, type the callback URL of your app which you found in the previous step and click `Next` at the bottom right. +- Click `Done` at the bottom. +- Click `Continue` at the top right. +- Click `Save` at the top right. + +### Download your secret key + +Now you'll need to download a `secret key` file from Apple that will be used to generate your `client_secret`. + +- Go to `Certificates, Identifiers & Profiles`. +- Click on `Keys` at the left. +- Click on the `+` sign in the upper left next to `Keys`. +- Enter a `Key Name`. +- Check `Sign In with Apple`. +- Click `Configure` to the right. +- Select your newly-created Services ID from the dropdown selector. +- Click `Save` at the top right. +- Click `Continue` at the top right. +- Click `Register` at the top right. +- Click `Download` at the top right. +- Save the downloaded file -- this contains your "secret key" that will be used to generate your `client_secret`. +- Click `Done` at the top right. + +### Generate a `client_secret` + +The `secret key` you downloaded is used to create the `client_secret` string you'll need to authenticate your users. + +According to the [Apple Docs](https://developer.apple.com/documentation/signinwithapplerestapi/generate_and_validate_tokens) it needs to be a JWT +token encrypted using the Elliptic Curve Digital Signature Algorithm (ECDSA) with the P-256 curve and the SHA-256 hash algorithm. + +At this time, the easiest way to generate this JWT token is with [Ruby](https://www.ruby-lang.org/en/). +If you don't have Ruby installed, you can [Download Ruby Here](https://www.ruby-lang.org/en/downloads). + +- Install Ruby (or check to make sure it's installed on your system). +- Install [ruby-jwt](https://github.com/jwt/ruby-jwt). +- From the command line, run: `sudo gem install jwt`. + +Create the script below using a text editor: `secret_gen.rb` + +```ruby +require "jwt" + +key_file = "Path to the private key" +team_id = "Your Team ID" +client_id = "The Service ID of the service you created" +key_id = "The Key ID of the private key" + +validity_period = 180 # In days. Max 180 (6 months) according to Apple docs. + +private_key = OpenSSL::PKey::EC.new IO.read key_file + +token = JWT.encode( + { + iss: team_id, + iat: Time.now.to_i, + exp: Time.now.to_i + 86400 * validity_period, + aud: "https://appleid.apple.com", + sub: client_id + }, + private_key, + "ES256", + header_fields= + { + kid: key_id + } +) +puts token +``` + +1. Edit the `secret_gen.rb` file: + +- `key_file` = "Path to the private key you downloaded from Apple". It should look like this: `AuthKey_XXXXXXXXXX.p8`. +- `team_id` = "Your Team ID". This is found at the top right of the Apple Developer site (next to your name). +- `client_id` = "The Service ID of the service you created". This is the `Services ID` you created in the above step `Obtain a Services ID`. If you've lost this ID, you can find it in the Apple Developer Site: + - Go to `Certificates, Identifiers & Profiles`. + - Click `Identifiers` at the left. + - At the top right drop-down, select `Services IDs`. + - Find your Identifier in the list (i.e. app.com.acme.roadrunner). +- `key_id` = "The Key ID of the private key". This can be found in the name of your downloaded secret file (For a file named `AuthKey_XXXXXXXXXX.p8` your key_id is `XXXXXXXXXX`). If you've lost this ID, you can find it in the Apple Developer Site: + - Go to `Certificates, Identifiers & Profiles`. + - Click `Keys` at the left. + - Click on your newly-created key in the list. + - Look under `Key ID` to find your key_id. + +2. From the command line, run: `ruby secret_gen.rb > client_secret.txt`. +3. Your `client_secret` is now stored in this `client_secret.txt` file. + +### Add your OAuth credentials to Supabase + +- Go to your [Supabase Dashboard](https://app.supabase.com). +- In the left sidebar, click the `Authentication` icon (near the top). +- Click `Settings` from the list to go to the `Authentication Settings` page. +- Enter the final (hosted) URL of your app under `Site URL` (this is important). +- Under `External OAuth Providers` turn `Apple Enabled` to ON. +- Enter your `client_id` and `client_secret` saved in the previous steps. +- Click `Save`. + +### Add login code to your client app + +The JavaScript client code is documented in the [Supabase OAuth Reference](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers). + +```js +const { user, session, error } = await supabase.auth.signIn({ + provider: 'apple', +}) +``` + +Add a function which you can call from a button, link, or UI element. + +```js +async function signInWithApple() { + const { user, session, error } = await supabase.auth.signIn({ + provider: 'apple', + }) +} +``` + +To log out: + +```js +async function signout() { + const { error } = await supabase.auth.signOut() +} +``` + +## Resources + +- [Apple Developer Account](https://developer.apple.com). +- [Ruby](https://www.ruby-lang.org/en/) Docs. +- [ruby-jwt](https://github.com/jwt/ruby-jwt) library. +- Thanks to [Janak Amarasena](https://medium.com/@janakda) who did all the heavy lifting in [How to configure Sign In with Apple](https://medium.com/identity-beyond-borders/how-to-configure-sign-in-with-apple-77c61e336003). diff --git a/apps/reference/docs/guides/auth/auth-azure.mdx b/apps/reference/docs/guides/auth/auth-azure.mdx new file mode 100644 index 00000000000..9b8b0e0ccf1 --- /dev/null +++ b/apps/reference/docs/guides/auth/auth-azure.mdx @@ -0,0 +1,101 @@ +--- +id: auth-azure +title: 'Login with Azure' +description: Add Azure OAuth to your Supabase project +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +To enable Azure Auth for your project, you need to set up an Azure OAuth application and add the application credentials to your Supabase Dashboard. + +## Overview + +Azure OAuth consists of four broad steps: + +- Create an application under Azure Active Directory. +- Obtain a `Application (client) ID` with “Sign In with Azure” capabilities. This will be used as the `client id`. +- Create a `Secret ID` with “Sign In with Azure” capabilities. The value of the secret will be used as the `client secret`. +- Whitelist the callback url of your application. + +## Steps + +### Access your Azure Developer account + +- Go to [portal.azure.com](https://portal.azure.com/#home). +- Login and select "Azure Active Directory" under the list of Azure Services. + +### Register an application + +- Under Azure Active Directory, select "App registrations" in the side panel. +- Select "New registration". +- Choose a name and select your preferred option for the supported account types. +- Specify the "Redirect URI". +- The redirect / callback URI should look like this: `https://.supabase.co/auth/v1/callback` +- Click "Register" at the bottom of the form. + +![Register an application.](/img/guides/auth-azure/azure-register-app.png) + +### Obtain a Client ID + +This will serve as the `client_id` when you make API calls to authenticate the user. + +- Once your app has been registered, the client id can be found under the [list of app registrations](https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredApps) under the column titled "Application (client) ID". + +![Obtain the client id](/img/guides/auth-azure/azure-client-id.png) + +### Obtain a Secret ID + +This will serve as the `client_secret` when you make API calls to authenticate the user. + +- Click on the name of the app registered above. +- Under "Essentials", click on "Client credentials". +- Navigate to the "Client secrets" tab and select "New client secret". +- Enter a description and choose your preferred expiry for the secret. +- Once the secret is generated, save the `value` (not the secret ID). + +![Obtain the client secret](/img/guides/auth-azure/azure-client-secret.png) + +## Obtain the Tenant URL + +This will allow your users to use your custom Azure login page when logging in. + +- Select the Directory (Tenant) ID value. +- The Azure Tenant URL should look like this: `https://login.microsoftonline.com/` + +![Obtain the tenant url](/img/guides/auth-azure/azure-tenant-url.png) + +### Add login code to your client app + +The JavaScript client code is documented in the [Supabase OAuth Reference](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers). + +```js +const { user, session, error } = await supabase.auth.signIn({ + provider: 'azure', +}) +``` + +Add a function which you can call from a button, link, or UI element. + +```js +async function signInWithAzure() { + const { user, session, error } = await supabase.auth.signIn({ + provider: 'azure', + }, { + scopes: 'email', + }) +} +``` + +To log out: + +```js +async function signout() { + const { error } = await supabase.auth.signOut() +} +``` + +## Resources + +- [Azure Developer Account](https://portal.azure.com). +- [GitHub Discussion](https://github.com/supabase/gotrue/pull/54#issuecomment-757043573). diff --git a/apps/reference/docs/guides/auth/auth-bitbucket.mdx b/apps/reference/docs/guides/auth/auth-bitbucket.mdx new file mode 100644 index 00000000000..774cd32c91d --- /dev/null +++ b/apps/reference/docs/guides/auth/auth-bitbucket.mdx @@ -0,0 +1,102 @@ +--- +id: auth-bitbucket +title: 'Login with Bitbucket' +description: Add Bitbucket OAuth to your Supabase project +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +To enable Bitbucket Auth for your project, you need to set up a BitBucket OAuth application and add the application credentials to your Supabase Dashboard. + +## Overview + +Setting up Bitbucket logins for your application consists of 3 parts: + +- Create and configure a Bitbucket OAuth Consumer on [Bitbucket](https://bitbucket.org) +- Add your Bitbucket OAuth Consumer keys to your [Supabase Project](https://app.supabase.com) +- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js) + +## Steps + +### Access your Bitbucket account + +- Go to [bitbucket.org](https://bitbucket.org/). +- Click on `Login` at the top right to log in. + +![Bitbucket Developer Portal.](/img/guides/auth-bitbucket/bitbucket-portal.png) + +### Find your callback URL + +The next step requires a callback URL, which looks like this: + +`https://.supabase.co/auth/v1/callback` + +- Go to your [Supabase Project Dashboard](https://app.supabase.com). +- Click on the `Settings` icon at the bottom of the left sidebar. +- Click on `API` in the list. +- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard. +- Now just add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`. + + + +### Create a Bitbucket OAuth app + +- Click on your profile icon at the bottom left +- Click on `All Workspaces` +- Select a workspace and click on it to select it +- Click on `Settings` on the left +- Click on `OAuth consumers` on the left under `Apps and Features` (near the bottom) +- Click `Add Consumer` at the top +- Enter the name of your app under `Name` +- In `Callback URL`, type the callback URL of your app +- Check the permissions you need (Email, Read should be enough) +- Click `Save` at the bottom +- Click on your app name (the name of your new OAuth Consumer) +- Copy your `Key` (`client_key`) and `Secret` (`client_secret`) codes + +### Add your Bitbucket credentials into your Supabase Project + +- Go to your [Supabase Project Dashboard](https://app.supabase.com) +- In the left sidebar, click the `Authentication` icon (near the top) +- Click `Settings` from the list to go to the `Authentication Settings` page +- Enter the final (hosted) URL of your app under `Site URL` (this is important) +- Under `External OAuth Providers` turn `Bitbucket Enabled` to ON +- Enter your `client_id` and `client_secret` saved in the previous step +- Click `Save` + +### Add login code to your client app + +The JavaScript client code is documented here: [Supabase OAuth Client Code](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers) + +```js +const { user, session, error } = await supabase.auth.signIn({ + provider: 'bitbucket', +}) +``` + +Add this function which you can call from a button, link, or UI element. + +```js +async function signInWithBitbucket() { + const { user, session, error } = await supabase.auth.signIn({ + provider: 'bitbucket', + }) +} +``` + +To log out: + +```js +async function signout() { + const { error } = await supabase.auth.signOut() +} +``` + +## Resources + +- [Supabase Account - Free Tier OK](https://supabase.com) +- [Supabase JS Client](https://github.com/supabase/supabase-js) +- [Bitbucket Account](https://bitbucket.org) diff --git a/apps/reference/docs/guides/auth/auth-discord.mdx b/apps/reference/docs/guides/auth/auth-discord.mdx new file mode 100644 index 00000000000..05ea31a6eea --- /dev/null +++ b/apps/reference/docs/guides/auth/auth-discord.mdx @@ -0,0 +1,108 @@ +--- +id: auth-discord +title: 'Login with Discord' +description: Add Discord OAuth to your Supabase project +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +To enable Discord Auth for your project, you need to set up a Discord Application and add the Application OAuth credentials to your Supabase Dashboard. + +## Overview + +Setting up Discord logins for your application consists of 3 parts: + +- Create and configure a Discord Application [Discord Developer Portal](https://discord.com/developers) +- Add your Discord OAuth Consumer keys to your [Supabase Project](https://app.supabase.com) +- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js) + +## Steps + +### Access your Discord account + +- Go to [discord.com](https://discord.com/). +- Click on `Login` at the top right to log in. + +![Discord Portal.](/img/guides/auth-discord/discord-portal.png) + +- Once logged in, go to [discord.com/developers](https://discord.com/developers). + +![Discord Portal.](/img/guides/auth-discord/discord-developer-portal.png) + +### Find your callback URL + +In the next step you require a callback URL, which looks like this: + +`https://.supabase.co/auth/v1/callback` + +- Go to your [Supabase Project Dashboard](https://app.supabase.com). +- Click on the `Settings` icon at the bottom of the left sidebar. +- Click on `API` in the list. +- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard. +- Now just add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`. + + + +### Create a Discord Application + +- Click on `New Application` at the top right. +- Enter the name of your application and click `Create`. +- Click on `OAuth2` under `Settings` in the left side panel. +- Click `Add Redirect` under `Redirects`. +- Type or paste your `callback URL` into the `Redirects` box. +- Click `Save Changes` at the bottom. +- Copy your `Client ID` and `Client Secret` under `Client information`. + +### Add your Discord credentials into your Supabase Project + +- Go to your [Supabase Project Dashboard](https://app.supabase.com) +- In the left sidebar, click the `Authentication` icon (near the top) +- Click `Settings` from the list to go to the `Authentication Settings` page +- Enter the final (hosted) URL of your app under `Site URL` (this is important) +- Under `External OAuth Providers` turn `Discord Enabled` to ON +- Enter your `client_id` and `client_secret` saved in the previous step +- Click `Save` + +### Add login code to your client app + +The JavaScript client code is documented here: [Supabase OAuth Client Code](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers) + +```js +const { user, session, error } = await supabase.auth.signIn({ + provider: 'discord', +}) +``` + +:::note + +If you call `signIn()` when already logged in, Discord will prompt the user again for authorization. + +::: + +Add this function which you can call from a button, link, or UI element. + +```js +async function signInWithDiscord() { + const { user, session, error } = await supabase.auth.signIn({ + provider: 'discord', + }) +} +``` + +To log out: + +```js +async function signout() { + const { error } = await supabase.auth.signOut() +} +``` + +## Resources + +- [Supabase Account - Free Tier OK](https://supabase.com) +- [Supabase JS Client](https://github.com/supabase/supabase-js) +- [Discord Account](https://discord.com) +- [Discord Developer Portal](https://discord.com/developers) diff --git a/apps/reference/docs/guides/auth/auth-email.mdx b/apps/reference/docs/guides/auth/auth-email.mdx new file mode 100644 index 00000000000..8edcca138e2 --- /dev/null +++ b/apps/reference/docs/guides/auth/auth-email.mdx @@ -0,0 +1,143 @@ +--- +id: auth-email +title: 'Login With Email' +description: Use Supabase to Authenticate and Authorize your users using email. +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +## Overview + +Setting up Email logins for your Supabase application. + +- Add Email authenticator to your [Supabase Project](https://app.supabase.com) +- Add the login code to your application - [JavaScript](https://github.com/supabase/supabase-js) | [Dart](https://github.com/supabase/supabase-dart) + +## Configure email settings + +- Go to your [Supabase Project Dashboard](https://app.supabase.com) +- In the left sidebar, click the `Authentication` icon (near the top) +- Click `Settings` from the list to go to the `Authentication Settings` page +- Enter the final (hosted) URL of your app under `Site URL` +- Under `Email Auth` turn `Enable Email Signup` to ON +- Click `Save` + +:::note Self hosting + +For self-hosting, you can update your project configuration using the files and environment variables provided. +See the [self-hosting docs](/docs/guides/hosting/overview#configuration) for details. + +::: + +### Add login code to your client app + +Add logins using our client libraries: + +- [JavaScript](/docs/reference/javascript/auth-signin#sign-in-with-email) +- [Dart](/docs/reference/dart/auth-signin#sign-in-with-email) + + + + + +```js +const { user, error } = await supabase.auth.signIn({ + email: 'example@email.com', + password: 'example-password', +}) +``` + + + + + +```dart +final res = await supabase.auth.signIn( + email: 'example@email.com', + password: 'example-password' +); + +final user = res.data?.user; +final error = res.error; +``` + + + + + +Add this function which you can call from a button, link, or UI element. + + + + + +```js +async function signInWithEmail() { + const { user, error } = await supabase.auth.signIn({ + email: 'example@email.com', + password: 'example-password', + }) +} +``` + + + + + +```dart +Future signInWithEmail() async { + await supabase.auth.signIn( + email: 'example@email.com', + password: 'example-password' + ); +} +``` + + + + + +To log out: + + + + + +```js +async function signOut() { + const { error } = await supabase.auth.signOut() +} +``` + + + + + +```dart +Future signOut() async { + await supabase.auth.signOut(); +} +``` + + + + + +## Resources + +- [Supabase Account - Free Tier OK](https://supabase.com) +- [Supabase JS Client](https://github.com/supabase/supabase-js) +- [Supabase Dart Client](https://github.com/supabase/supabase-dart) diff --git a/apps/reference/docs/guides/auth/auth-facebook.mdx b/apps/reference/docs/guides/auth/auth-facebook.mdx new file mode 100644 index 00000000000..d3fcccb5c06 --- /dev/null +++ b/apps/reference/docs/guides/auth/auth-facebook.mdx @@ -0,0 +1,119 @@ +--- +id: auth-facebook +title: 'Login with Facebook' +description: Add Facebook OAuth to your Supabase project +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +To enable Facebook Auth for your project, you need to set up a Facebook OAuth application and add the application credentials to your Supabase Dashboard. + +## Overview + +Setting up Facebook logins for your application consists of 3 parts: + +- Create and configure a Facebook Application on the [Facebook Developers Site](https://developers.facebook.com) +- Add your Facebook keys to your [Supabase Project](https://app.supabase.com) +- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js) + +## Steps + +### Access your Facebook Developer account + +- Go to [developers.facebook.com](https://developers.facebook.com). +- Click on `Log In` at the top right to log in. + +![Facebook Developer Portal.](/img/guides/auth-facebook/facebook-portal.png) + +### Create a Facebook App + +- Click on `My Apps` at the top right. +- Click `Create App` near the top right. +- Select your app type and click `Continue`. +- Fill in your app information, then click `Create App`. +- This should bring you to the screen: `Add Products to Your App`. (Alternatively you can click on `Add Product` in the left sidebar to get to this screen.) + +### Find your callback URI + +The next step requires a callback URI, which looks like this: + +`https://.supabase.co/auth/v1/callback` + +- Go to your [Supabase Project Dashboard](https://app.supabase.com). +- Click on the `Settings` icon at the bottom of the left sidebar. +- Click on `API` in the list. +- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard. +- Now just add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`. + + + +### Set up FaceBook Login for your Facebook App + +From the `Add Products to your App` screen: + +- Click `Setup` under `Facebook Login` +- Skip the Quickstart screen, instead, in the left sidebar, click `Settings` under `Facebook Login` +- Enter your callback URI under `Valid OAuth Redirect URIs` on the `Facebook Login Settings` page +- Enter this in the `Valid OAuth Redirect URIs` box +- Click `Save Changes` at the bottom right + +Be aware that you have to set the right access levels on your Facebook App to enable 3rd party applications to read the email address. +From the `App Review -> Permissions and Features` screen: + +- Click the button `Request Advanced Access` on the right side of `public_profile` and `email` + +You can read more about access levels [here](https://developers.facebook.com/docs/graph-api/overview/access-levels/) + +### Copy your Facebook App ID and Secret + +- Click `Settings / Basic` in the left sidebar +- Copy your App ID from the top of the `Basic Settings` page +- Under `App Secret` click `Show` then copy your secret +- Make sure all required fields are completed on this screen. + +### Enter your Facebook App ID and Secret into your Supabase Project + +- Go to your [Supabase Project Dashboard](https://app.supabase.com) +- In the left sidebar, click the `Authentication` icon (near the top) +- Click `Settings` from the list to go to the `Authentication Settings` page +- Enter the final (hosted) URL of your app under `Site URL` (this is important) +- Under `External OAuth Providers` turn `Facebook Enabled` to ON +- Enter your `Facebook client ID` and `Facebook secret` saved in the previous step +- Click `Save` + +### Add login code to your client app + +The JavaScript client code is documented here: [Supabase OAuth Client Code](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers) + +```js +const { user, session, error } = await supabase.auth.signIn({ + provider: 'facebook', +}) +``` + +Add this function which you can call from a button, link, or UI element. + +```js +async function signInWithFacebook() { + const { user, session, error } = await supabase.auth.signIn({ + provider: 'facebook', + }) +} +``` + +To log out: + +```js +async function signout() { + const { error } = await supabase.auth.signOut() +} +``` + +## Resources + +- [Supabase Account - Free Tier OK](https://supabase.com) +- [Supabase JS Client](https://github.com/supabase/supabase-js) +- [Facebook Developers Dashboard](https://developers.facebook.com/) diff --git a/apps/reference/docs/guides/auth/auth-github.mdx b/apps/reference/docs/guides/auth/auth-github.mdx new file mode 100644 index 00000000000..c2d43ba9108 --- /dev/null +++ b/apps/reference/docs/guides/auth/auth-github.mdx @@ -0,0 +1,112 @@ +--- +id: auth-github +title: 'Login with GitHub' +description: Add GitHub OAuth to your Supabase project +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +To enable GitHub Auth for your project, you need to set up a GitHub OAuth application and add the application credentials to your Supabase Dashboard. + +## Overview + +Setting up GitHub logins for your application consists of 3 parts: + +- Create and configure a GitHub OAuth App on [GitHub](https://github.com) +- Add your GitHub OAuth keys to your [Supabase Project](https://app.supabase.com) +- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js) + +## Steps + +### Access your GitHub account + +- Go to [github.com](https://github.com). +- Click on `Sign In` at the top right to log in. + +![GitHub Developer Portal.](/img/guides/auth-github/github-portal.png) + +### Create a GitHub Oauth App + +Go to the [GitHub Developer Settings](https://github.com/settings/developers) page: + +- Click on your profile photo at the top right +- Click Settings near the bottom of the menu +- In the left sidebar, click `Developer settings` (near the bottom) +- In the left sidebar, click `OAuth Apps` + +### Find your callback URL + +The next step requires a callback URL, which looks like this: + +`https://.supabase.co/auth/v1/callback` + +- Go to your [Supabase Project Dashboard](https://app.supabase.com). +- Click on the `Settings` icon at the bottom of the left sidebar. +- Click on `API` in the list. +- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard. +- Now just add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`. + + + +### Register a new OAuth application + +- Click `Register a new application`. If you've created an app before, click `New OAuth App` here. +- In `Application name`, type the name of your app. +- In `Homepage URL`, type the full URL to your app's website. +- In `Authorization callback URL`, type the callback URL of your app. +- Enter the URL in the `Valid OAuth Redirect URIs` box. +- Click `Save Changes` at the bottom right. +- Click `Register Application`. + +Copy your new OAuth credentials + +- Copy and save your `Client ID`. +- Click `Generate a new client secret`. +- Copy and save your `Client secret`. + +### Enter your GitHub credentials into your Supabase Project + +- Go to your [Supabase Project Dashboard](https://app.supabase.com) +- In the left sidebar, click the `Authentication` icon (near the top) +- Click `Settings` from the list to go to the `Authentication Settings` page +- Enter the final (hosted) URL of your app under `Site URL` (this is important) +- Under `External OAuth Providers` turn `GitHub Enabled` to ON +- Enter your `GitHub Client ID` and `GitHub Client Secret` saved in the previous step +- Click `Save` + +### Add login code to your client app + +The JavaScript client code is documented here: [Supabase OAuth Client Code](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers) + +```js +const { user, session, error } = await supabase.auth.signIn({ + provider: 'github', +}) +``` + +Add this function which you can call from a button, link, or UI element. + +```js +async function signInWithGithub() { + const { user, session, error } = await supabase.auth.signIn({ + provider: 'github', + }) +} +``` + +To log out: + +```js +async function signout() { + const { error } = await supabase.auth.signOut() +} +``` + +## Resources + +- [Supabase Account - Free Tier OK](https://supabase.com) +- [Supabase JS Client](https://github.com/supabase/supabase-js) +- [GitHub Developer Settings](https://github.com/settings/developers) diff --git a/apps/reference/docs/guides/auth/auth-gitlab.mdx b/apps/reference/docs/guides/auth/auth-gitlab.mdx new file mode 100644 index 00000000000..5bcd2971232 --- /dev/null +++ b/apps/reference/docs/guides/auth/auth-gitlab.mdx @@ -0,0 +1,99 @@ +--- +id: auth-gitlab +title: 'Login with GitLab' +description: Add GitLab OAuth to your Supabase project +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +To enable GitLab Auth for your project, you need to set up a GitLab OAuth application and add the application credentials to your Supabase Dashboard. + +## Overview + +Setting up GitLab logins for your application consists of 3 parts: + +- Create and configure a GitLab Application on [GitLab](https://gitlab.com) +- Add your GitLab Application keys to your [Supabase Project](https://app.supabase.com) +- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js) + +## Steps + +### Access your GitLab account + +- Go to [gitlab.com](https://gitlab.com). +- Click on `Login` at the top right to log in. + +![GitLab Developer Portal.](/img/guides/auth-gitlab/gitlab-portal.png) + +### Find your callback URL + +The next step requires a callback URL, which looks like this: + +`https://.supabase.co/auth/v1/callback` + +- Go to your [Supabase Project Dashboard](https://app.supabase.com). +- Click on the `Settings` icon at the bottom of the left sidebar. +- Click on `API` in the list. +- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard. +- Now just add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`. + + + +### Create your GitLab Application + +- Click on your `profile logo` (avatar) in the top-right corner. +- Select `Edit profile`. +- In the left sidebar, select Applications. +- Enter the name of the application. +- In the `Redirect URI` box, type the callback URL of your app. +- Check the box next to `Confidential` (make sure it is checked). +- Check the scope named `read_user` (this is the only required scope). +- Click `Save Application` at the bottom. +- Copy and save your `Application ID` (`client_id`) and `Secret` (`client_secret`) which you'll need later. + +### Add your GitLab credentials into your Supabase Project + +- Go to your [Supabase Project Dashboard](https://app.supabase.com). +- In the left sidebar, click the `Authentication` icon (near the top). +- Click `Settings` from the list to go to the `Authentication Settings` page. +- Enter the final (hosted) URL of your app under `Site URL` (this is important). +- Under `External OAuth Providers` turn `GitLab Enabled` to ON. +- Enter your `client_id` and `client_secret` saved in the previous step. +- Click `Save`. + +### Add login code to your client app + +The JavaScript client code is documented here: [Supabase OAuth Client Code](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers) + +```js +const { user, session, error } = await supabase.auth.signIn({ + provider: 'gitlab', +}) +``` + +Add this function which you can call from a button, link, or UI element. + +```js +async function signInWithGitLab() { + const { user, session, error } = await supabase.auth.signIn({ + provider: 'gitlab', + }) +} +``` + +To log out: + +```js +async function signout() { + const { error } = await supabase.auth.signOut() +} +``` + +## Resources + +- [Supabase Account - Free Tier OK](https://supabase.com) +- [Supabase JS Client](https://github.com/supabase/supabase-js) +- [GitLab Account](https://gitlab.com) diff --git a/apps/reference/docs/guides/auth/auth-google.mdx b/apps/reference/docs/guides/auth/auth-google.mdx new file mode 100644 index 00000000000..aeb92d43f12 --- /dev/null +++ b/apps/reference/docs/guides/auth/auth-google.mdx @@ -0,0 +1,127 @@ +--- +id: auth-google +title: 'Login with Google' +description: Add Google OAuth to your Supabase project +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +To enable Google Auth for your project, you need to set up a Google OAuth application and add the application credentials to your Supabase Dashboard. + +## Overview + +Setting up Google logins for your application consists of 3 parts: + +- Create and configure a Google Project on the [Google Cloud Platform Console](https://console.cloud.google.com/home/dashboard) +- Add your Google OAuth keys to your [Supabase Project](https://app.supabase.com) +- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js) + +## Steps + +### Access your Google Cloud Platform account + +- Go to [cloud.google.com](https://cloud.google.com). +- Click on `Sign in` at the top right to log in. + +![Google Developer Portal.](/img/guides/auth-google/google-portal.png) + +### Create a Google Cloud Platform Project + +- Click on `Select a Project` at the top left. + - (Or, if a project is currently selected, click on the current project name at the top left.) +- Click `New Project` at the top right. +- Fill in your app information, then click `Create`. + - (This can take a few minutes.) +- This should bring you to the dashboard for your new project. + +### Create the OAuth Keys for your project + +From your project's dashboard screen: + +- In the search bar at the top labeled `Search products and resources` type `OAuth`. +- Click on `OAuth consent screen` from the list of results. +- On the `OAuth consent screen` page select `External`. +- Click `Create`. + +### Edit your app information + +- On the `Edit app registration` page fill out your app information. +- Click `Save and continue` at the bottom. + +### Find your callback URL + +The next step requires a callback URL, which looks like this: + +`https://.supabase.co/auth/v1/callback` + +- Go to your [Supabase Project Dashboard](https://app.supabase.com). +- Click on the `Settings` icon at the bottom of the left sidebar. +- Click on `API` in the list. +- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard. +- Now just add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`. + + + +### Create your credentials + +- Click `Credentials` at the left to go to the `Credentials` page +- Click `Create Credentials` near the top then select `OAuth client ID` +- On the `Create OAuth client ID` page, select your application type. If you're not sure, choose `Web application`. +- Fill in your app name. +- At the bottom, under `Authorized redirect URIs` click `Add URI`. +- Enter your callback URI under `Authorized redirect URIs` at the bottom. +- Enter your callback URI in the `Valid OAuth Redirect URIs` box. +- Click `Save Changes` at the bottom right. +- Click `Create`. + +Copy your new OAuth credentials + +- A box will appear called `OAuth client created`. +- Copy and save the values under `Your Client ID` and `Your Client Secret`. + +### Enter your Google credentials into your Supabase Project + +- Go to your [Supabase Project Dashboard](https://app.supabase.com) +- In the left sidebar, click the `Authentication` icon (near the top) +- Click `Settings` from the list to go to the `Authentication Settings` page +- Enter the final (hosted) URL of your app under `Site URL` (this is important) +- Under `External OAuth Providers` turn `Google Enabled` to ON +- Enter your `Google Client ID` and `Google Client Secret` saved in the previous step +- Click `Save` + +### Add login code to your client app + +The JavaScript client code is documented here: [Supabase OAuth Client Code](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers) + +```js +const { user, session, error } = await supabase.auth.signIn({ + provider: 'google', +}) +``` + +Add this function which you can call from a button, link, or UI element. + +```js +async function signInWithGoogle() { + const { user, session, error } = await supabase.auth.signIn({ + provider: 'google', + }) +} +``` + +To log out: + +```js +async function signout() { + const { error } = await supabase.auth.signOut() +} +``` + +## Resources + +- [Supabase Account - Free Tier OK](https://supabase.com) +- [Supabase JS Client](https://github.com/supabase/supabase-js) +- [Google Cloud Platform Console](https://console.cloud.google.com/home/dashboard) diff --git a/apps/reference/docs/guides/auth/auth-keycloak.mdx b/apps/reference/docs/guides/auth/auth-keycloak.mdx new file mode 100644 index 00000000000..03834670c77 --- /dev/null +++ b/apps/reference/docs/guides/auth/auth-keycloak.mdx @@ -0,0 +1,95 @@ +--- +id: auth-keycloak +title: 'Login with Keycloak' +description: Add Keycloak OAuth to your Supabase project +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +To enable Keycloak Auth for your project, you need to set up an Keycloak OAuth application and add the application credentials to your Supabase Dashboard. + +## Overview + +To get started with Keycloak, you can run it in a docker container with: `docker run -e KEYCLOAK_USER=admin -e KEYCLOAK_PASSWORD=admin -p 8080:8080 jboss/keycloak:latest` + +This guide will be assuming that you are running keycloak in a docker container as described in the command above. + +Keycloak OAuth consists of five broad steps: + +- Create a new client in your specified keycloak realm. +- Obtain the `issuer` from the "OpenID Endpoint Configuration". This will be used as the `Keycloak URL`. +- Ensure that the new client has the "Client Protocol" set to "openid-connect" and the "Access Type" is set to "confidential". +- The `Client ID` of the client created will be used as the `client id`. +- Obtain the `Secret` from the credentials tab which will be used as the `client secret`. +- Whitelist the callback url of your application. + +## Steps + +### Access your Keycloak Admin console + +- Login by visiting [`http://localhost:8080`](http://localhost:8080) and clicking on "Administration Console". + +### Create a Keycloak Realm + +- Once you've logged in to the Keycloak console, you can add a realm from the side panel. The default realm should be named "Master". +- After you've added a new realm, you can retrieve the `issuer` from the "OpenID Endpoint Configuration" endpoint. The `issuer` will be used as the `Keycloak URL`. +- You can find this endpoint from the realm settings under the "General Tab" or visit [`http://localhost:8080/realms/my_realm_name/.well-known/openid-configuration`](http://localhost:8080/realms/my_realm_name/.well-known/openid-configuration) + +![Add a Keycloak Realm.](/img/guides/auth-keycloak/keycloak-create-realm.png) + +### Create a Keycloak Client + +The "Client ID" of the created client will serve as the `client_id` when you make API calls to authenticate the user. + +![Add a Keycloak client](/img/guides/auth-keycloak/keycloak-add-client.png) + +### Client Settings + +After you've created the client successfully, ensure that you set the following settings: +1. The "Client Protocol" should be set to "openid-connect". +2. The "Access Type" should be set to "confidential". +3. The "Valid Redirect URIs" should be set to: `https://.supabase.co/auth/v1/callback`. + +![Obtain the client id, set the client protocol and access type](/img/guides/auth-keycloak/keycloak-client-id.png) +![Set redirect uri](/img/guides/auth-keycloak/keycloak-redirect-uri.png) + +### Obtain the Client Secret + +This will serve as the `client_secret` when you make API calls to authenticate the user. +Under the "Credentials" tab, the `Secret` value will be used as the `client secret`. + +![Obtain the client secret](/img/guides/auth-keycloak/keycloak-client-secret.png) + +### Add login code to your client app + +The JavaScript client code is documented in the [Supabase OAuth Reference](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers). + +```js +const { user, session, error } = await supabase.auth.signIn({ + provider: 'keycloak', +}) +``` + +Add a function which you can call from a button, link, or UI element. + +```js +async function signInWithKeycloak() { + const { user, session, error } = await supabase.auth.signIn({ + provider: 'keycloak', + } +} +``` + +To log out: + +```js +async function signout() { + const { error } = await supabase.auth.signOut() +} +``` + +## Resources + +- You can find the keycloak openid endpoint configuration under the realm settings. +![Keycloak OpenID Endpoint Configuration](/img/guides/auth-keycloak/keycloak-openid-endpoint-config.png) diff --git a/apps/reference/docs/guides/auth/auth-linkedin.mdx b/apps/reference/docs/guides/auth/auth-linkedin.mdx new file mode 100644 index 00000000000..b7031776217 --- /dev/null +++ b/apps/reference/docs/guides/auth/auth-linkedin.mdx @@ -0,0 +1,98 @@ +--- +id: auth-linkedin +title: 'Login with LinkedIn' +description: Add LinkedIn OAuth to your Supabase project +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +To enable LinkedIn Auth for your project, you need to set up a LinkedIn OAuth application and add the application credentials to your Supabase Dashboard. + +## Overview + +Setting up LinkedIn logins for your application consists of 3 parts: + +- Create and configure a LinkedIn Project and App on the [LinkedIn Developer Dashboard](https://www.linkedin.com/developers/apps). +- Add your LinkedIn `API Key` and `API Secret Key` to your [Supabase Project](https://app.supabase.com). +- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js). + +## Steps + +### Access your LinkedIn Developer account + +- Go to [LinkedIn Developer Dashboard](https://www.linkedin.com/developers/apps). +- Log in (if necessary.) + +![LinkedIn Developer Portal](/img/guides/auth-linkedin/linkedin_developers_page.png) + +### Find your callback URL + +The next step requires a callback URL, which looks like this: + +`https://.supabase.co/auth/v1/callback` + +- Go to your [Supabase Project Dashboard](https://app.supabase.com). +- Click on the `Settings` icon at the bottom of the left sidebar. +- Click on `API` in the list. +- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard. +- Now just add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`. + + + +### Create a LinkedIn OAuth app + +- Go to [LinkedIn Developer Dashboard](https://www.linkedin.com/developers/apps). +- Click on `Create App` at the top right +- Enter your `LinkedIn Page` and `App Logo` +- Save your app +- Click `Auth` from the top menu +- Add your `Redirect URL` to the `Authorized Redirect URLs for your app` section +- Copy and save your newly-generated `Client ID` +- Copy and save your newly-generated `Client Secret` + +### Enter your LinkedIn credentials into your Supabase Project + +- Go to your [Supabase Project Dashboard](https://app.supabase.com). +- In the left sidebar, click the `Authentication` icon (near the top). +- Click `Settings` from the list to go to the `Authentication Settings` page. +- Enter the final (hosted) URL of your app under `Site URL` (this is important). +- Under `External OAuth Providers` turn `LinkedIn Enabled` to ON. +- Enter your `API Key` (`client_id`) and `API Secret Key` (`client_secret`) saved in the previous step. +- Click `Save`. + +### Add login code to your client app + +The JavaScript client code is documented here: [Supabase OAuth Client Code](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers). + +```js +const { user, session, error } = await supabase.auth.signIn({ + provider: 'LinkedIn', +}) +``` + +Add this function which you can call from a button, link, or UI element. + +```js +async function signInWithLinkedIn() { + const { user, session, error } = await supabase.auth.signIn({ + provider: 'LinkedIn', + }) +} +``` + +To log out: + +```js +async function signout() { + const { error } = await supabase.auth.signOut() +} +``` + +## Resources + +- [Supabase Account - Free Tier OK](https://supabase.com) +- [Supabase JS Client](https://github.com/supabase/supabase-js) +- [LinkedIn Developer Dashboard](https://api.LinkedIn.com/apps) diff --git a/apps/reference/docs/guides/auth/auth-magic-link.mdx b/apps/reference/docs/guides/auth/auth-magic-link.mdx new file mode 100644 index 00000000000..5d320a55abe --- /dev/null +++ b/apps/reference/docs/guides/auth/auth-magic-link.mdx @@ -0,0 +1,129 @@ +--- +id: auth-magic-link +title: 'Login With Magic Link' +description: Use Supabase to Authenticate and Authorize your users using Magic Link. +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +By default, if no password is provided, the user will be sent a "magic link" to their email address, which they can click to open your application with a valid session. By default, a given user can only request a Magic Link once every 60 seconds. + +## Overview + +Setting up Magic Link logins for your Supabase application. + +- Add Magic Link authenticator to your [Supabase Project](https://app.supabase.com) +- Add the login code to your application - [JavaScript](https://github.com/supabase/supabase-js) | [Dart](https://github.com/supabase/supabase-dart) + +## Add Magic Link into your Supabase Project + +- Go to your [Supabase Project Dashboard](https://app.supabase.com) +- In the left sidebar, click the `Authentication` icon (near the top) +- Click `Settings` from the list to go to the `Authentication Settings` page +- Enter the final (hosted) URL of your app under `Site URL` (this is important) +- Under `Email Auth` turn `Enable Email Signup` to ON +- Click `Save` + +### Add login code to your client app + +Add logins using our client libraries: + +- [JavaScript](/docs/reference/javascript/auth-signin#sign-in-with-magic-link) +- [Dart](/docs/reference/dart/auth-signin#sign-in-with-magic-link) + + + + + +```js +const { user, error } = await supabase.auth.signIn({ + email: 'example@email.com', +}) +``` + + + + + +```dart +final res = await supabase.auth.signIn(email: 'example@email.com'); + +final error = res.error; +``` + + + + + +Add this function which you can call from a button, link, or UI element. + + + + + +```js +async function signInWithEmail() { + const { user, error } = await supabase.auth.signIn({ + email: 'example@email.com', + }) +} +``` + + + + + +```dart +Future signInWithEmail() async { + await supabase.auth.signIn(email: 'example@email.com'); +} +``` + + + + + +To log out: + + + + + +```js +async function signOut() { + const { error } = await supabase.auth.signOut() +} +``` + + + + + +```dart +Future signOut() async { + await supabase.auth.signOut(); +} +``` + + + + + +## Resources + +- [Supabase Account - Free Tier OK](https://supabase.com) +- [Supabase JS Client](https://github.com/supabase/supabase-js) +- [Supabase Dart Client](https://github.com/supabase/supabase-dart) diff --git a/apps/reference/docs/guides/auth/auth-messagebird.mdx b/apps/reference/docs/guides/auth/auth-messagebird.mdx new file mode 100644 index 00000000000..dd806ecb6b7 --- /dev/null +++ b/apps/reference/docs/guides/auth/auth-messagebird.mdx @@ -0,0 +1,282 @@ +--- +id: auth-messagebird +title: Phone Auth with MessageBird +description: How to set up and use Mobile OTP with MessageBird and Supabase. +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +## Overview + +In this guide we'll show you how to authenticate your users with SMS based OTP (One-Time Password) tokens. + +There are two reasons to use Supabase SMS OTP tokens: + +- You want users to log in with mobile + password, and the mobile should be verified via SMS +- You want users to log in with mobile ONLY (i.e. passwordless login) + +We'll cover: + +- [Finding your MessageBird credentials](#finding-your-messagebird-credentials) +- [Using OTP with password based logins](#using-otp-with-password-based-logins) +- [Using OTP as a passwordless sign-in mechanism](#using-otp-as-a-passwordless-sign-in-mechanism) + +What you'll need: + +- A MessageBird account (sign up here: https://dashboard.messagebird.com/en/sign-up) +- A Supabase project (create one here: https://app.supabase.com) +- A mobile phone capable of receiving SMS + +## Steps + +### Finding your MessageBird credentials + +Start by logging into your MessageBird account and verify the mobile number you'll be using to test with: https://dashboard.messagebird.com/en/getting-started/sms + +This is the number that will be receiving the SMS OTPs. + +![Verify your own phone number](/img/guides/auth-messagebird/1.png) + +![Get your API Keys](/img/guides/auth-messagebird/2.png) + +Navigate to the [dashboard settings](https://dashboard.messagebird.com/en/settings/sms) to set the default originator. The messagebird originator is the name or number from which the message is sent. +For more information, you can refer to the messagebird article on choosing an originator [here](https://support.messagebird.com/hc/en-us/articles/115002628665-Choosing-an-originator) + +![Set the default originator](/img/guides/auth-messagebird/3.png) + +You will need the following values to get started: + +- Live API Key / Test API Key +- MessageBird originator + +Now go to the Auth > Settings page in the Supabase dashboard (https://app.supabase.com/project/YOUR-PROJECT-REF/auth/settings). + +You should see an option to enable Phone Signup. + +![Enable Phone Sign-Up](/img/guides/auth-twilio/7.png) + +Toggle it on, and copy the 2 values over from the messagebird dashboard. Click save. + +Note: If you use the Test API Key, the OTP will not be delivered to the mobile number specified but messagebird will log the response in the dashboard. +If the Live API Key is used instead, the OTP will be delivered and there will be a deduction in your free credits. + + +Plugin MessageBird credentials + +Now the backend should be setup, we can proceed to add our client-side code! + +#### SMS custom template + +The SMS message sent to a phone containing an OTP code can be customized. This is useful if you need to mention a brand name or display a website address. + +Go to Auth > Templates page in the Supabase dashboard (https://app.supabase.com/project/YOUR-PROJECT-REF/auth/templates). + +Use the variable `.Code` in the template to display the code. + +### Using OTP with password based logins + +In this use scenario we'll be using the user's mobile phone number as an alternative to an email address when signing up along with a password. You may want to think hard about the permanency of this however. It is not uncommon for mobile phone numbers to be recycled by phone networks when users cancel their phone contracts or move countries, therefore granting access to the user's account to whoever takes over the phone number in the future. Soon we'll add multi-factor auth, which will mitigate this risk, but for now you may want to give some thought to allowing your users to recover their account by some other means in an emergency. + +Using supabase-js on the client you'll want to use the same `signUp` method that you'd use for email based sign ups, but with the `phone` param instead of the `email param`: + + + + +```js +let { user, error } = await supabase.auth.signUp({ + phone: '+13334445555', + password: 'some-password', +}) +``` + + + + +```bash +curl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/signup' \ +-H "apikey: SUPABASE_KEY" \ +-H "Content-Type: application/json" \ +-d '{ + "phone": "+13334445555", + "password": "some-password" +}' +``` + + + + +The user will now receive an SMS with a 6-digit pin that you will need to receive from them within 60-seconds before they can login to their account. + +You should present a form to the user so they can input the 6 digit pin, then send it along with the phone number to `verifyOTP`: + + + + +```js +let { session, error } = await supabase.auth.verifyOTP({ + phone: '+13334445555', + token: '123456', +}) +``` + + + + +```bash +curl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/verify' \ +-H "apikey: SUPABASE_KEY" \ +-H "Content-Type: application/json" \ +-d '{ + "type": "sms", + "phone": "+13334445555", + "token": "123456" +}' +``` + + + + +If successful the user will now be logged in and you should receive a valid session like: + +```json +{ + "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhdXRoZW50aWNhdGVkIiwiZXhwIjoxNjI3MjkxNTc3LCJzdWIiOiJmYTA2NTQ1Zi1kYmI1LTQxY2EtYjk1NC1kOGUyOTg4YzcxOTEiLCJlbWFpbCI6IiIsInBob25lIjoiNjU4NzUyMjAyOSIsImFwcF9tZXRhZGF0YSI6eyJwcm92aWRlciI6InBob25lIn0sInVzZXJfbWV0YWRhdGEiOnt9LCJyb2xlIjoiYXV0aGVudGljYXRlZCJ9.1BqRi0NbS_yr1f6hnr4q3s1ylMR3c1vkiJ4e_N55dhM", + "token_type": "bearer", + "expires_in": 3600, + "refresh_token": "LSp8LglPPvf0DxGMSj-vaQ" +} +``` + +The access token can be sent in the Authorization header as a Bearer token for any CRUD operations on supabase-js. See our guide on [Row Level Security](/docs/guides/auth#row-level-security) for more info on restricting access on a user basis. + +Also now that the mobile has been verified, the user can use the number and password to sign in without needing to verify their number each time: + + + + +```js +let { user, error } = await supabase.auth.signIn({ + phone: '+13334445555', + password: 'some-password', +}) +``` + + + + +```bash +curl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/token?grant_type=password' \ +-H "apikey: SUPABASE_KEY" \ +-H "Content-Type: application/json" \ +-d '{ + "phone": "+13334445555", + "password": "some-password" +}' +``` + + + + +### Using OTP as a passwordless sign-in mechanism + +In this scenario you are granting your user's the ability to login to their account without needing to set a password on their account, all they have to do to log in is verify their mobile each time using the OTP. + +In javascript we can use the `signIn` method with a single parameter: `phone` + + + + +```js +let { user, error } = await supabase.auth.signIn({ + phone: '+13334445555', +}) +``` + + + + +```bash +curl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/otp' \ +-H "apikey: SUPABASE_KEY" \ +-H "Content-Type: application/json" \ +-d '{ + "phone": "+13334445555" +}' +``` + + + + +The second step is the same as the previous section, you need to collect the 6-digit pin from the user and pass it along with their phone number to the verify method: + + + + +```js +let { session, error } = await supabase.auth.verifyOTP({ + phone: '+13334445555', + token: '123456', +}) +``` + + + + +```bash +curl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/verify' \ +-H "apikey: SUPABASE_KEY" \ +-H "Content-Type: application/json" \ +-d '{ + "type": "sms", + "phone": "+13334445555", + "token": "123456" +}' +``` + + + + +and the response should also be the same as above: + +```json +{ + "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhdXRoZW50aWNhdGVkIiwiZXhwIjoxNjI3MjkxNTc3LCJzdWIiOiJmYTA2NTQ1Zi1kYmI1LTQxY2EtYjk1NC1kOGUyOTg4YzcxOTEiLCJlbWFpbCI6IiIsInBob25lIjoiNjU4NzUyMjAyOSIsImFwcF9tZXRhZGF0YSI6eyJwcm92aWRlciI6InBob25lIn0sInVzZXJfbWV0YWRhdGEiOnt9LCJyb2xlIjoiYXV0aGVudGljYXRlZCJ9.1BqRi0NbS_yr1f6hnr4q3s1ylMR3c1vkiJ4e_N55dhM", + "token_type": "bearer", + "expires_in": 3600, + "refresh_token": "LSp8LglPPvf0DxGMSj-vaQ" +} +``` + +The user does not have a password therefore will need to sign in via this method each time they want to access your service. + +## Resources + +- [MessageBird Signup](https://dashboard.messagebird.com/en/sign-up) +- [Supabase Dashboard](https://app.supabase.com) +- [Supabase Row Level Security](/docs/guides/auth#row-level-security) diff --git a/apps/reference/docs/guides/auth/auth-notion.mdx b/apps/reference/docs/guides/auth/auth-notion.mdx new file mode 100644 index 00000000000..44a6464c03d --- /dev/null +++ b/apps/reference/docs/guides/auth/auth-notion.mdx @@ -0,0 +1,101 @@ +--- +id: auth-notion +title: 'Login with Notion' +description: Add Notion OAuth to your Supabase project +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +To enable Notion Auth for your project, you need to set up a Notion Application and add the Application OAuth credentials to your Supabase Dashboard. + +## Overview + +Setting up Notion logins for your application consists of 3 parts: + +- Create and configure a Notion Application [Notion Developer Portal](https://www.notion.so/my-integrations) +- Retrieve your OAuth client ID and OAuth client secret and add them to your [Supabase Project](https://app.supabase.com) +- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js) + +## Steps + +### Create your notion integration + +- Go to [developers.notion.com](https://developers.notion.com/). +- Click "View my integrations" and login. + +![notion.so](/img/guides/auth-notion/notion.png) + +- Once logged in, go to [notion.so/my-integrations](https://notion.so/my-integrations) and create a new integration. +- When creating your integration, ensure that you select "Public integration" under "Integration type" and "Read user information including email addresses" under "Capabilities". +- You will need to add a redirect uri, see [Add the redirect uri](#add-the-redirect-uri) +- Once you've filled in the necessary fields, click "Submit" to finish creating the integration. + +![notion.so](/img/guides/auth-notion/notion-developer.png) + +### Add the redirect uri +- After selecting "Public integration", you should see an option to add "Redirect URIs". + +![notion.so](/img/guides/auth-notion/notion-redirect-uri.png) + +You can retrieve the redirect uri with the following steps: + +- Go to your [Supabase Project Dashboard](https://app.supabase.com). +- Click on the `Settings` icon at the bottom of the left sidebar. +- Click on `API` in the list. +- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard. +- Add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`. + +Your redirect uri should look like the following: `https://.supabase.co/auth/v1/callback` + + + +### Add your Notion credentials into your Supabase Project + +- Once you've created your notion integration, you should be able to retrieve the "OAuth client ID" and "OAuth client secret" from the "OAuth Domain and URIs" tab. + +![notion.so](/img/guides/auth-notion/notion-creds.png) + +- Go to your [Supabase Project Dashboard](https://app.supabase.com) +- In the left sidebar, click the `Authentication` icon (near the top) +- Click `Settings` from the list to go to the `Authentication Settings` page +- Under `External OAuth Providers` turn `Notion Enabled` to ON +- Enter the "OAuth client ID" and "OAuth client secret" obtained in the `client id` and `client secret` fields. +- Click `Save` + +### Add login code to your client app + +The JavaScript client code is documented here: [Supabase OAuth Client Code](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers) + +```js +const { user, session, error } = await supabase.auth.signIn({ + provider: 'notion', +}) +``` + +Add this function which you can call from a button, link, or UI element. + +```js +async function signInWithNotion() { + const { user, session, error } = await supabase.auth.signIn({ + provider: 'notion', + }) +} +``` + +To log out: + +```js +async function signout() { + const { error } = await supabase.auth.signOut() +} +``` + +## Resources + +- [Supabase Account - Free Tier OK](https://supabase.com) +- [Supabase JS Client](https://github.com/supabase/supabase-js) +- [Notion Account](https://notion.so) +- [Notion Developer Portal](https://www.notion.so/my-integrations) diff --git a/apps/reference/docs/guides/auth/auth-slack.mdx b/apps/reference/docs/guides/auth/auth-slack.mdx new file mode 100644 index 00000000000..fd60e76a8b1 --- /dev/null +++ b/apps/reference/docs/guides/auth/auth-slack.mdx @@ -0,0 +1,111 @@ +--- +id: auth-slack +title: 'Login with Slack' +description: Add Slack OAuth to your Supabase project +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +To enable Slack Auth for your project, you need to set up a Slack OAuth application and add the application credentials to your Supabase Dashboard. + +## Overview + +Setting up Slack logins for your application consists of 3 parts: + +- Create and configure a Slack Project and App on the [Slack Developer Dashboard](https://api.slack.com/apps). +- Add your Slack `API Key` and `API Secret Key` to your [Supabase Project](https://app.supabase.com). +- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js). + +## Steps + +### Access your Slack Developer account + +- Go to [api.slack.com](https://api.slack.com/apps). +- Click on `Your Apps` at the top right to log in. + +![Slack Developer Portal.](/img/guides/auth-slack/slack-portal.png) + +### Find your callback URL + +The next step requires a callback URL, which looks like this: + +`https://.supabase.co/auth/v1/callback` + +- Go to your [Supabase Project Dashboard](https://app.supabase.com). +- Click on the `Settings` icon at the bottom of the left sidebar. +- Click on `API` in the list. +- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard. +- Now just add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`. + + + +### Create a Slack OAuth app + +- Go to [api.slack.com](https://api.slack.com/apps). +- Click on `Create an App` + +Under `Create an app...`: + +- Click `From scratch` +- Type the name of your app +- Select your `Slack Workspace` +- Click `Create App` + +Under `App Credentials`: + +- Copy and save your newly-generated `Client ID` +- Copy and save your newly-generated `Client Secret` +- Click `Permissions` + +Under `Redirect URLs`: + +- Click `Add New Redirect URL` +- Paste your `Callback URL` then click `Add` +- Click `Save URLs` + +### Enter your Slack credentials into your Supabase Project + +- Go to your [Supabase Project Dashboard](https://app.supabase.com). +- In the left sidebar, click the `Authentication` icon (near the top). +- Click `Settings` from the list to go to the `Authentication Settings` page. +- Enter the final (hosted) URL of your app under `Site URL` (this is important). +- Under `External OAuth Providers` turn `Slack Enabled` to ON. +- Enter your `Client ID` (`client_id`) and `Client Secret` (`client_secret`) saved in the previous step. +- Click `Save`. + +### Add login code to your client app + +The JavaScript client code is documented here: [Supabase OAuth Client Code](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers). + +```js +const { user, session, error } = await supabase.auth.signIn({ + provider: 'slack', +}) +``` + +Add this function which you can call from a button, link, or UI element. + +```js +async function signInWithSlack() { + const { user, session, error } = await supabase.auth.signIn({ + provider: 'slack', + }) +} +``` + +To log out: + +```js +async function signout() { + const { error } = await supabase.auth.signOut() +} +``` + +## Resources + +- [Supabase Account - Free Tier OK](https://supabase.com) +- [Supabase JS Client](https://github.com/supabase/supabase-js) +- [Slack Developer Dashboard](https://api.slack.com/apps) diff --git a/apps/reference/docs/guides/auth/auth-spotify.mdx b/apps/reference/docs/guides/auth/auth-spotify.mdx new file mode 100644 index 00000000000..760eaf85d04 --- /dev/null +++ b/apps/reference/docs/guides/auth/auth-spotify.mdx @@ -0,0 +1,106 @@ +--- +id: auth-spotify +title: 'Login with Spotify' +description: Add Spotify OAuth to your Supabase project +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +To enable Spotify Auth for your project, you need to set up a Spotify OAuth application and add the application credentials to your Supabase Dashboard. + +## Overview + +Setting up Spotify logins for your application consists of 3 parts: + +- Create and configure a Spotify Project and App on the [Spotify Developer Dashboard](https://developer.spotify.com/dashboard/). +- Add your Spotify `API Key` and `API Secret Key` to your [Supabase Project](https://app.supabase.com). +- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js). + +## Steps + +### Access your Spotify Developer account + +- Log into [Spotify](https://spotify.com) +- Access the [Spotify Developer Dashboard](https://developer.spotify.com/dashboard) + +![Spotify Developer Portal.](/img/guides/auth-spotify/spotify-portal.png) + +### Find your callback URL + +The next step requires a callback URL, which looks like this: + +`https://.supabase.co/auth/v1/callback` + +- Go to your [Supabase Project Dashboard](https://app.supabase.com). +- Click on the `Settings` icon at the bottom of the left sidebar. +- Click on `API` in the list. +- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard. +- Now just add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`. + + + +### Create a Spotify OAuth app + +- Log into [Spotify](https://spotify.com). +- Go to the [Spotify Developer Dashboard](https://developer.spotify.com/dashboard) +- Click `Create an App` +- Type your `App name` +- Type your `App description` +- Check the box to agree with the `Developer TOS and Branding Guidelines` +- Click `Create` +- Save your `Client ID` +- Save your `Client Secret` +- Click `Edit Settings` + +Under `Redirect URIs`: + +- Paste your Supabase Callback URL in the box +- Click `Add` +- Click `Save` at the bottom + +### Enter your Spotify credentials into your Supabase Project + +- Go to your [Supabase Project Dashboard](https://app.supabase.com). +- In the left sidebar, click the `Authentication` icon (near the top). +- Click `Settings` from the list to go to the `Authentication Settings` page. +- Enter the final (hosted) URL of your app under `Site URL` (this is important). +- Under `External OAuth Providers` turn `Spotify Enabled` to ON. +- Enter your `Client ID` (`client_id`) and `Client Secret` (`client_secret`) saved in the previous step. +- Click `Save`. + +### Add login code to your client app + +The JavaScript client code is documented here: [Supabase OAuth Client Code](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers). + +```js +const { user, session, error } = await supabase.auth.signIn({ + provider: 'spotify', +}) +``` + +Add this function which you can call from a button, link, or UI element. + +```js +async function signInWithSpotify() { + const { user, session, error } = await supabase.auth.signIn({ + provider: 'spotify', + }) +} +``` + +To log out: + +```js +async function signout() { + const { error } = await supabase.auth.signOut() +} +``` + +## Resources + +- [Supabase Account - Free Tier OK](https://supabase.com) +- [Supabase JS Client](https://github.com/supabase/supabase-js) +- [Spotify Developer Dashboard](https://developer.spotify.com/dashboard/) diff --git a/apps/reference/docs/guides/auth/auth-twilio.mdx b/apps/reference/docs/guides/auth/auth-twilio.mdx new file mode 100644 index 00000000000..ba9ac6fec27 --- /dev/null +++ b/apps/reference/docs/guides/auth/auth-twilio.mdx @@ -0,0 +1,301 @@ +--- +id: auth-twilio +title: Phone Auth with Twilio +description: How to set up and use Mobile OTP with Twilio and Supabase. +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +## Overview + +In this guide we'll show you how to authenticate your users with SMS based One-Time Password (OTP) tokens. + +There are two reasons to use Supabase SMS OTP tokens: + +- You want users to log in with mobile number + password, and the mobile number should be verified via SMS +- You want users to log in with mobile number ONLY (i.e. passwordless login) + +We'll cover: + +- [Finding your Twilio credentials](#finding-your-twilio-credentials) +- [Using OTP with password based logins](#using-otp-with-password-based-logins) +- [Using OTP as a passwordless sign-in mechanism](#using-otp-as-a-passwordless-sign-in-mechanism) + +What you'll need: + +- A Twilio account (sign up here: https://www.twilio.com/try-twilio) +- A Supabase project (create one here: https://app.supabase.com) +- A mobile phone capable of receiving SMS + +## Video + + + +## Steps + +### Finding your Twilio credentials + +Start by logging into your Twilio account and starting a new project: https://www.twilio.com/console/projects/create + +Give your project a name and verify the mobile number you'll be using to test with. This is the number that will be receiving the SMS OTPs. + +![Name your twilio project](/img/guides/auth-twilio/1.png) +![verify your own phone number](/img/guides/auth-twilio/2.png) + +Select 'SMS', 'Identity & Verification', and 'With code' as options on the welcome form. + +![Form Fields](/img/guides/auth-twilio/3.png) + +When you're back on the [Twilio console screen](https://www.twilio.com/console), you need to scroll down and click 'Get a trial phone number' - this is the number that you'll be sending SMSs from. + +![Get a trial phone number](/img/guides/auth-twilio/4.png) + +![Successful phone number](/img/guides/auth-twilio/5.png) + +You should now be able to see all three values you'll need to get started: + +- Account SID +- Auth Token +- Sender Phone Number + +![All the credentials you'll need](/img/guides/auth-twilio/6.png) + +Now go to the Auth > Settings page in the Supabase dashboard (https://app.supabase.com/project/YOUR-PROJECT-REF/auth/settings). + +You should see an option to enable Phone Signup: + +![Enable Phone Sign-Up](/img/guides/auth-twilio/7.png) + +Toggle it on, and copy the 3 values over from the twilio dashboard. Click save. + +Note: for "Twilio Message Service SID" you can use the Sender Phone Number generated above. + +![Plug in Twilio credentials](/img/guides/auth-twilio/8.png) + +Now the backend should be setup, we can proceed to add our client-side code! + +#### SMS custom template + +The SMS message sent to a phone containing an OTP code can be customized. This is useful if you need to mention a brand name or display a website address. + +Go to Auth > Templates page in the Supabase dashboard (https://app.supabase.com/project/YOUR-PROJECT-REF/auth/templates). + +Use the variable `.Code` in the template to display the OTP code. Here's an example in the SMS template. + +![example in the SMS template](/img/guides/auth-twilio/9.png) + +### Using OTP with password based logins + +In this scenario we'll be using the user's mobile phone number and a corresponding password as an alternative to signing up with an email address. Note: please thoroughly consider potential security implications when signing up with a combination of phone number and password. Phone numbers are sometimes recycled by phone networks when users cancel their phone contracts or move countries, thereby granting access to the user's account to the subsequent owner of the phone number. In the near future Supabase will support multifactor authentication, which will mitigate this risk, but for now you may want to consider allowing your users to recover their account by some other means in an emergency. + +Using supabase-js on the client you'll want to use the same `signUp` method that you'd use for email based sign ups, but with the `phone` param instead of the `email param`: + + + + +```js +let { user, error } = await supabase.auth.signUp({ + phone: '+13334445555', + password: 'some-password', +}) +``` + + + + +```bash +curl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/signup' \ +-H "apikey: SUPABASE_KEY" \ +-H "Content-Type: application/json" \ +-d '{ + "phone": "+13334445555", + "password": "some-password" +}' +``` + + + + +The user will now receive an SMS with a 6-digit pin that you will need to receive from them within 60-seconds before they can login to their account. + +You should present a form to the user so they can input the 6 digit pin, then send it along with the phone number to `verifyOTP`: + + + + +```js +let { session, error } = await supabase.auth.verifyOTP({ + phone: '+13334445555', + token: '123456', +}) +``` + + + + +```bash +curl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/verify' \ +-H "apikey: SUPABASE_KEY" \ +-H "Content-Type: application/json" \ +-d '{ + "type": "sms", + "phone": "+13334445555", + "token": "123456" +}' +``` + + + + +If successful the user will now be logged in and you should receive a valid session like: + +```json +{ + "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhdXRoZW50aWNhdGVkIiwiZXhwIjoxNjI3MjkxNTc3LCJzdWIiOiJmYTA2NTQ1Zi1kYmI1LTQxY2EtYjk1NC1kOGUyOTg4YzcxOTEiLCJlbWFpbCI6IiIsInBob25lIjoiNjU4NzUyMjAyOSIsImFwcF9tZXRhZGF0YSI6eyJwcm92aWRlciI6InBob25lIn0sInVzZXJfbWV0YWRhdGEiOnt9LCJyb2xlIjoiYXV0aGVudGljYXRlZCJ9.1BqRi0NbS_yr1f6hnr4q3s1ylMR3c1vkiJ4e_N55dhM", + "token_type": "bearer", + "expires_in": 3600, + "refresh_token": "LSp8LglPPvf0DxGMSj-vaQ" +} +``` + +The access token can be sent in the Authorization header as a Bearer token for any CRUD operations on supabase-js. See our guide on [Row Level Security](/docs/guides/auth#row-level-security) for more info on restricting access on a user basis. + +Also now that the mobile has been verified, the user can use the number and password to sign in without needing to verify their number each time: + + + + +```js +let { user, error } = await supabase.auth.signIn({ + phone: '+13334445555', + password: 'some-password', +}) +``` + + + + +```bash +curl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/token?grant_type=password' \ +-H "apikey: SUPABASE_KEY" \ +-H "Content-Type: application/json" \ +-d '{ + "phone": "+13334445555", + "password": "some-password" +}' +``` + + + + +### Using OTP as a passwordless sign-in mechanism + +In this scenario you are granting your user's the ability to login to their account without needing to set a password on their account, all they have to do to log in is verify their mobile each time using the OTP. + +In javascript we can use the `signIn` method with a single parameter: `phone` + + + + +```js +let { user, error } = await supabase.auth.signIn({ + phone: '+13334445555', +}) +``` + + + + +```bash +curl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/otp' \ +-H "apikey: SUPABASE_KEY" \ +-H "Content-Type: application/json" \ +-d '{ + "phone": "+13334445555" +}' +``` + + + + +The second step is the same as the previous section, you need to collect the 6-digit pin from the user and pass it along with their phone number to the verify method: + + + + +```js +let { session, error } = await supabase.auth.verifyOTP({ + phone: '+13334445555', + token: '123456', +}) +``` + + + + +```bash +curl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/verify' \ +-H "apikey: SUPABASE_KEY" \ +-H "Content-Type: application/json" \ +-d '{ + "type": "sms", + "phone": "+13334445555", + "token": "123456" +}' +``` + + + + +and the response should also be the same as above: + +```json +{ + "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhdXRoZW50aWNhdGVkIiwiZXhwIjoxNjI3MjkxNTc3LCJzdWIiOiJmYTA2NTQ1Zi1kYmI1LTQxY2EtYjk1NC1kOGUyOTg4YzcxOTEiLCJlbWFpbCI6IiIsInBob25lIjoiNjU4NzUyMjAyOSIsImFwcF9tZXRhZGF0YSI6eyJwcm92aWRlciI6InBob25lIn0sInVzZXJfbWV0YWRhdGEiOnt9LCJyb2xlIjoiYXV0aGVudGljYXRlZCJ9.1BqRi0NbS_yr1f6hnr4q3s1ylMR3c1vkiJ4e_N55dhM", + "token_type": "bearer", + "expires_in": 3600, + "refresh_token": "LSp8LglPPvf0DxGMSj-vaQ" +} +``` + +The user does not have a password therefore will need to sign in via this method each time they want to access your service. + +## Resources + +- [Twilio Signup](https://www.twilio.com/try-twilio) +- [Supabase Dashboard](https://app.supabase.com) +- [Supabase Row Level Security](/docs/guides/auth#row-level-security) diff --git a/apps/reference/docs/guides/auth/auth-twitch.mdx b/apps/reference/docs/guides/auth/auth-twitch.mdx new file mode 100644 index 00000000000..4c5b5519598 --- /dev/null +++ b/apps/reference/docs/guides/auth/auth-twitch.mdx @@ -0,0 +1,118 @@ +--- +id: auth-twitch +title: 'Login with Twitch' +description: Add Twitch OAuth to your Supabase project +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +To enable Twitch Auth for your project, you need to set up a Twitch Application and add the Application OAuth credentials to your Supabase Dashboard. + +## Overview + +Setting up Twitch logins for your application consists of 3 parts: + +- Create and configure a Twitch Application [Twitch Developer Console](https://dev.twitch.tv/console) +- Add your Twitch OAuth Consumer keys to your [Supabase Project](https://app.supabase.com) +- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js) + +## Steps + +### Access your Twitch Developer account + +- Go to [dev.twitch.tv](https://dev.twitch.tv). +- Click on `Log in with Twitch` at the top right to log in. +- If you have not already enabled 2-Factor Authentication for your Twitch Account, you will need to do that at [Twitch Security Settings](https://www.twitch.tv/settings/security) before you can continue. + +![Twitch Developer Page](/img/guides/auth-twitch/twitch-developer-page.png) + +- Once logged in, go to the [Twitch Developer Console](https://dev.twitch.tv/console). + +![Twitch Developer Console](/img/guides/auth-twitch/twitch-console.png) + +### Find your callback URL + +In the next step you require a callback URL, which looks like this: + +`https://.supabase.co/auth/v1/callback` + +- Go to your [Supabase Project Dashboard](https://app.supabase.com). +- Click on the `Settings` icon at the bottom of the left sidebar. +- Click on `API` in the list. +- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard. +- Now just add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`. + + + +### Create a Twitch Application + +![Twitch Developer Console](/img/guides/auth-twitch/twitch-console.png) + +- Click on `+ Register Your Application` at the top right. + +![Register Application](/img/guides/auth-twitch/twitch-register-your-application.png) + +- Enter the name of your application. +- Type or paste your `OAuth Redirect URL` (the callback URL from the previous step.) +- Select a category for your app. +- Check the Captcha box and click `Create`. + +### Retrieve your Twitch OAuth Client ID and Client Secret + +- Click `Manage` at the right of your application entry in the list. + +![Twitch Applications List](/img/guides/auth-twitch/twitch-applications-list.png) + +- Copy your Client ID. +- Click `New Secret` to create a new Client Secret. +- Copy your Client Secret. + +![Get Client ID and Secret](/img/guides/auth-twitch/twitch-get-keys.png) + +### Add your Twitch credentials into your Supabase Project + +- Go to your [Supabase Project Dashboard](https://app.supabase.com) +- In the left sidebar, click the `Authentication` icon (near the top) +- Click `Settings` from the list to go to the `Authentication Settings` page +- Enter the final (hosted) URL of your app under `Site URL` (this is important) +- Under `External OAuth Providers` turn `Twitch Enabled` to ON +- Enter your `client_id` and `client_secret` saved in the previous step +- Click `Save` + +### Add login code to your client app + +The JavaScript client code is documented here: [Supabase OAuth Client Code](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers) + +```js +const { user, session, error } = await supabase.auth.signIn({ + provider: 'twitch', +}) +``` + +Add this function which you can call from a button, link, or UI element. + +```js +async function signInWithTwitch() { + const { user, session, error } = await supabase.auth.signIn({ + provider: 'twitch', + }) +} +``` + +To log out: + +```js +async function signout() { + const { error } = await supabase.auth.signOut() +} +``` + +## Resources + +- [Supabase Account - Free Tier OK](https://supabase.com) +- [Supabase JS Client](https://github.com/supabase/supabase-js) +- [Twitch Account](https://twitch.tv) +- [Twitch Developer Console](https://dev.twitch.tv/console) diff --git a/apps/reference/docs/guides/auth/auth-twitter.mdx b/apps/reference/docs/guides/auth/auth-twitter.mdx new file mode 100644 index 00000000000..537137ea5ab --- /dev/null +++ b/apps/reference/docs/guides/auth/auth-twitter.mdx @@ -0,0 +1,107 @@ +--- +id: auth-twitter +title: 'Login with Twitter' +description: Add Twitter OAuth to your Supabase project +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +To enable Twitter Auth for your project, you need to set up a Twitter OAuth application and add the application credentials to your Supabase Dashboard. + +## Overview + +Setting up Twitter logins for your application consists of 3 parts: + +- Create and configure a Twitter Project and App on the [Twitter Developer Dashboard](https://developer.twitter.com/en/portal/dashboard). +- Add your Twitter `API Key` and `API Secret Key` to your [Supabase Project](https://app.supabase.com). +- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js). + +## Steps + +### Access your Twitter Developer account + +- Go to [developer.twitter.com](https://developer.twitter.com). +- Click on `Sign in` at the top right to log in. + +![Twitter Developer Portal.](/img/guides/auth-twitter/twitter-portal.png) + +### Find your callback URL + +The next step requires a callback URL, which looks like this: + +`https://.supabase.co/auth/v1/callback` + +- Go to your [Supabase Project Dashboard](https://app.supabase.com). +- Click on the `Settings` icon at the bottom of the left sidebar. +- Click on `API` in the list. +- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard. +- Now just add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`. + + + +### Create a Twitter OAuth app + +- Click `+ Create Project`. + - Enter your project name, click `Next`. + - Select your use case, click `Next`. + - Enter a description for your project, click `Next`. + - Enter a name for your app, click `Complete`. + - Copy and save your `API Key` (this is your `client_id`). + - Copy and save your `API Secret Key` (this is your `client_secret`). +- At the bottom, under `Next, setup your App` click the link `enable 3rd party authentication`. +- Under `App Settings`, click on the gear icon next to your app name to go to `App Settings`. +- At the bottom, next to `Authentication settings`, click `Edit`. +- Turn `Enable 3-legged OAuth` ON. +- Turn `Request email address from users` ON. +- Enter your `Callback URL`. +- Enter your `Website URL`. +- Enter your `Terms of service URL`. +- Enter your `Privacy policy URL`. +- Click `Save`. + +### Enter your Twitter credentials into your Supabase Project + +- Go to your [Supabase Project Dashboard](https://app.supabase.com). +- In the left sidebar, click the `Authentication` icon (near the top). +- Click `Settings` from the list to go to the `Authentication Settings` page. +- Enter the final (hosted) URL of your app under `Site URL` (this is important). +- Under `External OAuth Providers` turn `Twitter Enabled` to ON. +- Enter your `API Key` (`client_id`) and `API Secret Key` (`client_secret`) saved in the previous step. +- Click `Save`. + +### Add login code to your client app + +The JavaScript client code is documented here: [Supabase OAuth Client Code](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers). + +```js +const { user, session, error } = await supabase.auth.signIn({ + provider: 'twitter', +}) +``` + +Add this function which you can call from a button, link, or UI element. + +```js +async function signInWithTwitter() { + const { user, session, error } = await supabase.auth.signIn({ + provider: 'twitter', + }) +} +``` + +To log out: + +```js +async function signout() { + const { error } = await supabase.auth.signOut() +} +``` + +## Resources + +- [Supabase Account - Free Tier OK](https://supabase.com) +- [Supabase JS Client](https://github.com/supabase/supabase-js) +- [Twitter Developer Dashboard](https://developer.twitter.com/en/portal/dashboard) diff --git a/apps/reference/docs/guides/auth/auth-vonage.mdx b/apps/reference/docs/guides/auth/auth-vonage.mdx new file mode 100644 index 00000000000..109101c6cb5 --- /dev/null +++ b/apps/reference/docs/guides/auth/auth-vonage.mdx @@ -0,0 +1,274 @@ +--- +id: auth-vonage +title: Phone Auth with Vonage +description: How to set up and use Mobile OTP with Vonage and Supabase. +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +## Overview + +In this guide we'll show you how to authenticate your users with SMS based OTP (One-Time Password) tokens. + +There are two reasons to use Supabase SMS OTP tokens: + +- You want users to log in with mobile + password, and the mobile should be verified via SMS +- You want users to log in with mobile ONLY (i.e. passwordless login) + +We'll cover: + +- [Getting your Vonage API Key](#finding-your-vonage-api-key) +- [Using OTP with password based logins](#using-otp-with-password-based-logins) +- [Using OTP as a passwordless sign-in mechanism](#using-otp-as-a-passwordless-sign-in-mechanism) + +What you'll need: + +- A Vonage account (sign up here: https://dashboard.nexmo.com/sign-up) +- A Supabase project (create one here: https://app.supabase.com) +- A mobile phone capable of receiving SMS + +## Steps + +### Getting your Vonage credentials + +Start by logging into your Vonage Dashboard at https://dashboard.nexmo.com/ + +You will see you API Key and API Secret here, which is actually all you need to get started. + +In most countries, a phone number is actually optional and you can also use any Alphanumeric Sender ID of up to 11 characters length (8 for India) as a Sender ID (from). This means you do not need a number to test with in most cases. + +To find out more about supported countries for Alphanumeric Sender ID, check this overview: https://help.nexmo.com/hc/en-us/articles/115011781468-SMS-Features-Overview-Outbound-only- + +Hint: Some countries might need a Sender ID Registration to allow sending with an Alphanumeric Sender ID. You can find this information in the help article as well. If Alpha Sender IDs are not supported, you will need to buy a phone number. + +### Getting a phone number (optional) + +If you want a phone number to send SMS from, you can buy one from the Vonage Dashboard under Numbers > Buy Numbers (https://dashboard.nexmo.com/buy-numbers). + +Select the country you want a number for. You will need a mobile phone number with SMS or SMS+Voice capability. After you have bought the number, you will be able to send SMS from it. + +### Configure Supabase + +Now go to the Auth > Settings page in the Supabase dashboard (https://app.supabase.com/project/YOUR-PROJECT-REF/auth/settings). + +You should see an option to enable Phone Signup. + +Toggle it on, and copy the api key, api secret and optionally phone number values over from the Vonage dashboard. Click save. + +Now the backend should be setup, we can proceed to add our client-side code! + +#### SMS custom template + +The SMS message sent to a phone containing an OTP code can be customized. This is useful if you need to mention a brand name or display a website address. + +Go to Auth > Templates page in the Supabase dashboard (https://app.supabase.com/project/YOUR-PROJECT-REF/auth/templates). + +Use the variable `.Code` in the template to display the code. + +### Using OTP with password based logins + +In this use scenario we'll be using the user's mobile phone number as an alternative to an email address when signing up along with a password. You may want to think hard about the permanency of this however. It is not uncommon for mobile phone numbers to be recycled by phone networks when users cancel their phone contracts or move countries, therefore granting access to the user's account to whoever takes over the phone number in the future. + +Using supabase-js on the client you'll want to use the same `signUp` method that you'd use for email based sign ups, but with the `phone` param instead of the `email param`: + + + + +```js +let { user, error } = await supabase.auth.signUp({ + phone: '491512223334444', + password: 'some-password', +}) +``` + + + + +```bash +curl -X POST 'https://xxx.supabase.co/auth/v1/signup' \ +-H "apikey: SUPABASE_KEY" \ +-H "Content-Type: application/json" \ +-d '{ + "phone": "491512223334444", + "password": "some-password" +}' +``` + + + + +The user will now receive an SMS with a 6-digit pin that you will need to receive from them within 60-seconds before they can login to their account. + +You should present a form to the user so they can input the 6 digit pin, then send it along with the phone number to `verifyOTP`: + + + + +```js +let { session, error } = await supabase.auth.verifyOTP({ + phone: '491512223334444', + token: '123456', +}) +``` + + + + +```bash +curl -X POST 'https://xxx.supabase.co/auth/v1/verify' \ +-H "apikey: SUPABASE_KEY" \ +-H "Content-Type: application/json" \ +-d '{ + "type": "sms", + "phone": "491512223334444", + "token": "123456" +}' +``` + + + + +If successful the user will now be logged in and you should receive a valid session like: + +```json +{ + "access_token": "eyJxxx...", + "token_type": "bearer", + "expires_in": 3600, + "refresh_token": "yyy..." +} +``` + +The access token can be sent in the Authorization header as a Bearer token for any CRUD operations on supabase-js. See our guide on [Row Level Security](/docs/guides/auth#row-level-security) for more info on restricting access on a user basis. + +Also now that the mobile has been verified, the user can use the number and password to sign in without needing to verify their number each time: + + + + +```js +let { user, error } = await supabase.auth.signIn({ + phone: '491512223334444', + password: 'some-password', +}) +``` + + + + +```bash +curl -X POST 'https://xxx.supabase.co/auth/v1/token?grant_type=password' \ +-H "apikey: SUPABASE_KEY" \ +-H "Content-Type: application/json" \ +-d '{ + "phone": "491512223334444", + "password": "some-password" +}' +``` + + + + +### Using OTP as a passwordless sign-in mechanism + +In this scenario you are granting your user's the ability to login to their account without needing to set a password on their account, all they have to do to log in is verify their mobile each time using the OTP. + +In javascript we can use the `signIn` method with a single parameter: `phone` + + + + +```js +let { user, error } = await supabase.auth.signIn({ + phone: '491512223334444', +}) +``` + + + + +```bash +curl -X POST 'https://xxx.supabase.co/auth/v1/otp' \ +-H "apikey: SUPABASE_KEY" \ +-H "Content-Type: application/json" \ +-d '{ + "phone": "491512223334444" +}' +``` + + + + +The second step is the same as the previous section, you need to collect the 6-digit pin from the user and pass it along with their phone number to the verify method: + + + + +```js +let { session, error } = await supabase.auth.verifyOTP({ + phone: '491512223334444', + token: '123456', +}) +``` + + + + +```bash +curl -X POST 'https://xxx.supabase.co/auth/v1/verify' \ +-H "apikey: SUPABASE_KEY" \ +-H "Content-Type: application/json" \ +-d '{ + "type": "sms", + "phone": "491512223334444", + "token": "123456" +}' +``` + + + + +and the response should also be the same as above: + +```json +{ + "access_token": "eyJxxx...", + "token_type": "bearer", + "expires_in": 3600, + "refresh_token": "yyy..." +} +``` + +The user does not have a password therefore will need to sign in via this method each time they want to access your service. + +## Resources + +- [Vonage Signup](https://dashboard.nexmo.com/sign-up) +- [Supabase Dashboard](https://app.supabase.com) +- [Supabase Row Level Security](/docs/guides/auth#row-level-security) \ No newline at end of file diff --git a/apps/reference/docs/guides/auth/auth-workos.mdx b/apps/reference/docs/guides/auth/auth-workos.mdx new file mode 100644 index 00000000000..5a4b1abb306 --- /dev/null +++ b/apps/reference/docs/guides/auth/auth-workos.mdx @@ -0,0 +1,102 @@ +--- +id: auth-workos +title: 'Login with WorkOS' +description: Add WorkOS OAuth to your Supabase project +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +To enable WorkOS Auth for your project, you need to set up WorkOS OAuth application and add the application credentials to your Supabase Dashboard. + +## Overview + +In this guide, we will cover how to use Supabase OAuth with WorkOS to implement Single-Sign-On(SSO). + +The procedure consists of five broad steps: + +- Create a new organization from your WorkOS Dashboard. +- Obtain the `Client ID` from the Configuration tab and configure redirect URI. +- Obtain the `WorkOS Secret` from the credentials tab. +- Connect a WorkOS Supported Identity Provider +- Add your WorkOS credentials into your Supabase project + +## Steps + +### Create a WorkOS Organization + +Log in to the dashboard and hop over to the Organizations tab to create and organization +![Create an Organization](/img/guides/auth-workos/workos-create-organization.png) + +### Obtain the Client ID and configure Redirect URI + +Head over to the Configuration tab and configure the redirect URI.The redirect URI should look like `https://.supabase.co/auth/v1/callback` +Note that this is distinct from the redirect URI referred to in the Supabase dashboard + +![Fetch Client ID and configure Redirect URI](/img/guides/auth-workos/workos-clientid-redirect-uri.png) + +### Obtain the WorkOS Secret + +Head over to the API Keys page and obtain the secret key. + +![WorkOS Secret Key](/img/guides/auth-workos/workos-secret-key.png) + +### Connect a WorkOS Supported Identity Provider + +Set up the identity provider by visiting the setup link. + +![Visiting the setup link](/img/guides/auth-workos/workos-setup-identity-provider.png) + +You can pick between any one of the many identity providers that WorkOS supports. + +### Add your WorkOS credentials into your Supabase Project + +- Go to your [Supabase Project Dashboard](https://app.supabase.com) +- In the left sidebar, click the `Authentication` icon (near the top) +- Click `Settings` from the list to go to the `Authentication Settings` page +- Under `External OAuth Providers` turn `WorkOS Enabled` to ON +- Enter the `Client ID`, `Secret`, and `WorkOS URL` saved in the previous steps. The ``WorkOS URL` setting should be set to https://api.workos.com/ +- Click `Save` + + + +### Add login code to your client app + +The JavaScript client code is documented in the [Supabase OAuth Reference](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers). Note that you only need to include one of the three parameters: `connection`, `organization`, and `provider`. +You can refer to the [WorkOS Documentation](https://workos.com/docs/reference/sso/authorize/) to learn more about the different methods. + +```js +const { user, session, error } = await supabase.auth.signIn({ + provider: 'workos', +}, { + connection: "", + organization: "" +}) +``` + +Add a function which you can call from a button, link, or UI element. + +```js +async function signInWithWorkOS() { + const { user, session, error } = await supabase.auth.signIn({ + provider: 'workos', + }, { + connection: "", + organization: "" + }) +} +``` + +To log out: + +```js +async function signout() { + const { error } = await supabase.auth.signOut() +} +``` + +## Resources + +- [WorkOS Documentation](https://workos.com/docs/sso/guide) diff --git a/apps/reference/docs/guides/auth/auth-zoom.mdx b/apps/reference/docs/guides/auth/auth-zoom.mdx new file mode 100644 index 00000000000..3d2e3b7b478 --- /dev/null +++ b/apps/reference/docs/guides/auth/auth-zoom.mdx @@ -0,0 +1,107 @@ +--- +id: auth-zoom +title: 'Login with Zoom' +description: Add Zoom OAuth to your Supabase project +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +To enable Zoom Auth for your project, you need to set up a Zoom OAuth application and add the application credentials to your Supabase Dashboard. + +## Overview + +Setting up Zoom logins for your application consists of 3 parts: + +- Create and configure a Zoom OAuth App on [Zoom App Marketplace](https://marketplace.zoom.us/) +- Add your Zoom OAuth keys to your [Supabase Project](https://app.supabase.com) +- Add the login code to your [Supabase JS Client App](https://github.com/supabase/supabase-js) + +## Steps + +### Access your Zoom Developer account + +- Go to [marketplace.zoom.us](https://marketplace.zoom.us/). +- Click on `Sign In` at the top right to log in. + +![Zoom Developer Portal.](/img/guides/auth-zoom/zoom-portal.png) + +### Find your callback URL + +The next step requires a callback URL, which looks like this: + +`https://.supabase.co/auth/v1/callback` + +- Go to your [Supabase Project Dashboard](https://app.supabase.com). +- Click on the `Settings` icon at the bottom of the left sidebar. +- Click on `API` in the list. +- Under Config / URL you'll find your API URL, you can click `Copy` to copy it to the clipboard. +- Now just add `/auth/v1/callback` to the end of that to get your full `OAuth Redirect URI`. + + + +### Create a Zoom Oauth App + +- Go to [marketplace.zoom.us](https://marketplace.zoom.us/). +- Click on `Sign In` at the top right to log in. +- Click `Build App` (from the dropdown Develop) +- In the OAuth card, click `Create` +- Type the name of your app +- Choose app type +- Click `Create` + +Under `App credentials` + +- Copy and save your `Client ID`. +- Copy and save your `Client secret`. + +Under `Redirect URL for OAuth` + +- Paste your `Callback URL` +- Click `Continue` + +### Enter your Zoom credentials into your Supabase Project + +- Go to your [Supabase Project Dashboard](https://app.supabase.com) +- In the left sidebar, click the `Authentication` icon (near the top) +- Click `Settings` from the list to go to the `Authentication Settings` page +- Enter the final (hosted) URL of your app under `Site URL` (this is important) +- Under `External OAuth Providers` turn `Zoom Enabled` to ON +- Enter your `Zoom Client ID` and `Zoom Client Secret` saved in the previous step +- Click `Save` + +### Add login code to your client app + +The JavaScript client code is documented here: [Supabase OAuth Client Code](/docs/reference/javascript/auth-signin#sign-in-using-third-party-providers) + +```js +const { user, session, error } = await supabase.auth.signIn({ + provider: 'zoom', +}) +``` + +Add this function which you can call from a button, link, or UI element. + +```js +async function signInWithZoom() { + const { user, session, error } = await supabase.auth.signIn({ + provider: 'zoom', + }) +} +``` + +To log out: + +```js +async function signout() { + const { error } = await supabase.auth.signOut() +} +``` + +## Resources + +- [Supabase Account - Free Tier OK](https://supabase.com) +- [Supabase JS Client](https://github.com/supabase/supabase-js) +- [Zoom App Marketplace](https://marketplace.zoom.us/) diff --git a/apps/reference/docs/guides/auth/intro.mdx b/apps/reference/docs/guides/auth/intro.mdx new file mode 100644 index 00000000000..104a5359024 --- /dev/null +++ b/apps/reference/docs/guides/auth/intro.mdx @@ -0,0 +1,84 @@ +--- +id: intro +title: Supabase Auth +sidebar_label: Introduction +description: Use Supabase to Authenticate and Authorize your users. +# hide_table_of_contents: true +--- + +import Link from '@docusaurus/Link' +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' +import providers from '@site/src/data/authProviders' + + + +## Introduction + +Supabase Auth is designed to work with Postgres. There are two parts to every Auth system: + +- **Authentication:** should this person be allowed in? If yes, who are they? +- **Authorization:** once they are in, what are they allowed to do? + +## Authentication + +You can authenticate your users in several ways: + +- Email & password. +- Magic links (one-click logins). +- Social providers. +- Phone logins. + +
+
+ {providers.map((x) => ( +
+ +
+
+ {x.logo && {x.name}} +

{x.name}

+

+ {x.official ? + Official + : + + Unofficial + + } +

+
+
+
+ Platform: + {x.platform.toString()} +
+
+ Self-Hosted: + {x.selfHosted.toString()} +
+
+
+ +
+ ))} +
+
+ + +## Authorization + + +When you need granular authorization rules, nothing beats PostgreSQL's Row Level Security (RLS). + +Policies are PostgreSQL's rule engine. They are incredibly powerful and flexible, allowing you to write complex SQL rules which fit your unique business needs. + +Get started with our [Row Level Security Guides](/docs/guides/auth/row-level-security). \ No newline at end of file diff --git a/apps/reference/docs/guides/auth/managing-user-data.mdx b/apps/reference/docs/guides/auth/managing-user-data.mdx new file mode 100644 index 00000000000..d0affd2a189 --- /dev/null +++ b/apps/reference/docs/guides/auth/managing-user-data.mdx @@ -0,0 +1,109 @@ +--- +id: managing-user-data +title: Managing User Data +description: Securing your user data with Row Level Security. +--- + +For security purposes, the `auth` schema is not exposed on the auto-generated API. + +Even though Supabase provides an `auth.users` table, it can be helpful to create tables in the `public` schema for storing user data that you want to access via the API. + +## Creating user tables + +When you create tables to store user data, it's helpful to reference the `auth.users` table in the primary key. This ensures data integrity. + +For example, a `public.profiles` table might look like this: + +```sql +create table public.profiles ( + id uuid references auth.users not null, + first_name text, + last_name text, + + primary key (id) +); + +alter table public.profiles enable row level security; +``` + + +## Public access + +Since Row Level Security is enabled, this table is accessible via the API but no data will be returned unless we set up some Policies. +If we wanted the data to be _readable_ by everyone but only allow logged-in users to update their own data, the Policies would look like this: + +```sql +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 update own profile." + on profiles for update + using ( auth.uid() = id ); +``` + +## Private access + +If the data should only be _readable_ by the user who owns the data, we just need to change the `for select` query above. + +```sql +create policy "Profiles are viewable by users who created them." + on profiles for select + using ( auth.uid() = id ); +``` + +The nice thing about this pattern? We can now query this table via the API and we don't need to include data filters in our API queries - the Policies will handle that for us: + +```js +// This will return nothing while the user is logged out +const { data } = await supabase + .from('profiles') + .select('id, username, avatar_url, website') + +// After the user is logged in, this will only return +// the logged-in user's data - in this case a single row +const { error } = await supabase.auth.signIn({ email }) +const { data: profile } = await supabase + .from('profiles') + .select('id, username, avatar_url, website') +``` + +## Bypassing Row Level Security + +If you need to fetch a full list of user profiles, we supply a `service_key` which you can use with your API and Client Libraries to bypass Row Level Security. + +Make sure you _NEVER_ expose this publicly. But it can be used on the server-side to fetch all of the profiles. + + +## Advanced techniques + +### Using triggers + +If you want to add a row to your `public.profiles` table every time a user signs up, you can use triggers. +If the trigger fails however, it could block the user sign ups - so make sure that the code is well-tested. + +For example: + +```sql +-- inserts a row into public.users +create function public.handle_new_user() +returns trigger +language plpgsql +security definer set search_path = public +as $$ +begin + insert into public.profiles (id) + values (new.id); + return new; +end; +$$; + +-- trigger the function every time a user is created +create trigger on_auth_user_created + after insert on auth.users + for each row execute procedure public.handle_new_user(); +``` diff --git a/apps/reference/docs/guides/auth/row-level-security.mdx b/apps/reference/docs/guides/auth/row-level-security.mdx new file mode 100644 index 00000000000..88d91d049c8 --- /dev/null +++ b/apps/reference/docs/guides/auth/row-level-security.mdx @@ -0,0 +1,364 @@ +--- +id: row-level-security +title: Row Level Security +description: Secure your data using Postgres Row Level Security. +--- + +When you need granular authorization rules, nothing beats PostgreSQL's [Row Level Security (RLS)](https://www.postgresql.org/docs/current/ddl-rowsecurity.html). + +[Policies](https://www.postgresql.org/docs/current/sql-createpolicy.html) are PostgreSQL's rule engine. They are incredibly powerful and flexible, allowing you to write complex SQL rules which fit your unique business needs. + + + +## Policies + +Policies are easy to understand once you get the hang of them. Each policy is attached to a table, and the policy is executed +every time a table is accessed. +You can just think of them as adding a `WHERE` clause to every query. For example a policy like this ... + +```sql +create policy "Individuals can view their own todos." + on todos for select + using ( auth.uid() = user_id ); +``` + +.. would translate to this whenever a user tries to select from the todos table: + +```sql +select * +from todos +where auth.uid() = todos.user_id; -- Policy is implicitly added. +``` + +## Helper Functions + +Supabase provides you with a few easy functions that you can use with your policies. + +### `auth.uid()` + +Returns the ID of the user making the request. + +### `auth.jwt()` + +Returns the JWT of the user making the request. + +### `auth.role()` + +:::caution + +Deprecated + +::: + +The `auth.role()` function has been deprecated in favour of using the `TO` field, natively supported within Postgres. + +```sql +-- DEPRECATED +create policy "Public profiles are viewable by everyone." +on profiles for select using ( + auth.role() = 'authenticated' or auth.role() = 'anon' +); + +-- RECOMMENDED +create policy "Public profiles are viewable by everyone." +on profiles for select +to authenticated, anon +using ( + true +); +``` + +### `auth.email()` + +:::caution + +Deprecated. Use `auth.jwt() ->> 'email'` instead. + +::: + +Returns the email of the user making the request. + +## Examples + +Here are some examples to show you the power of PostgreSQL's RLS. + +### Allow read access + +```sql +-- 1. Create table +create table profiles ( + id uuid references auth.users, + avatar_url text +); + +-- 2. Enable RLS +alter table profiles + enable row level security; + +-- 3. Create Policy +create policy "Public profiles are viewable by everyone." + on profiles for select using ( + true + ); +``` + +1. Creates a table called `profiles` in the public schema (default schema). +2. Enables Row Level Security. +3. Creates a policy which allows all `select` queries to run. + +### Restrict updates + +```sql +-- 1. Create table +create table profiles ( + id uuid references auth.users, + avatar_url text +); + +-- 2. Enable RLS +alter table profiles + enable row level security; + +-- 3. Create Policy +create policy "Users can update their own profiles." + on profiles for update using ( + auth.uid() = id + ); +``` + +1. Creates a table called `profiles` in the public schema (default schema). +2. Enables RLS. +3. Creates a policy which allows logged in users to update their own data. + +### Only anon or authenticated access + +You can add a Postgres role + +```sql +create policy "Public profiles are viewable by everyone." +on profiles for select +to authenticated, anon +using ( + true +); +``` + +### Policies with joins + +Policies can even include table joins. This example shows how you can query "external" tables to build more advanced rules. + +```sql +create table teams ( + id serial primary key, + name text +); + +-- 2. Create many to many join +create table members ( + team_id bigint references teams, + user_id uuid references auth.users +); + +-- 3. Enable RLS +alter table teams + enable row level security; + +-- 4. Create Policy +create policy "Team members can update team details if they belong to the team." + on teams + for update using ( + auth.uid() in ( + select user_id from members + where team_id = id + ) + ); +``` + +**Note:** If RLS is also enabled for _members_, the user must also have read (_select_) access to _members_. Otherwise the joined query will not yield any results. + +### Policies with security definer functions + +Policies can also make use of `security definer functions`. This is useful in a many-to-many relationship where you want to restrict access to the linking table. Following the `teams` and `members` example from above, this example shows how you can use the security definer function in combination with a policy to control access to the `members` table. + +```sql +-- 1. Follow example for 'Policies with joins' above + +-- 2. Enable RLS +alter table members + enable row level security + +-- 3. Create security definer function +create or replace function get_teams_for_authenticated_user() +returns setof bigint +language sql +security definer +set search_path = public +stable +as $$ + select team_id + from members + where user_id = auth.uid() +$$; + +-- 4. Create Policy +create policy "Team members can update team members if they belong to the team." + on members + for all using ( + team_id in ( + select get_teams_for_authenticated_user() + ) + ); + +``` + +### Verifying email domains + +Postgres has a function `right(string, n)` that returns the rightmost n characters of a string. +You could use this to match staff member's email domains. + +```sql +-- 1. Create table +create table leaderboard ( + id uuid references auth.users, + high_score bigint +); + +-- 2. Enable RLS +alter table leaderboard + enable row level security; + +-- 3. Create Policy +create policy "Only Blizzard staff can update leaderboard" + on leaderboard + for update using ( + right(auth.email(), 13) = '@blizzard.com' + ); +``` + +### Time to live for rows + +Policies can also be used to implement TTL or time to live feature that you see in Instagram stories or Snapchat. +In the following example, rows of `stories` table are available only if they have been created within the last 24 hours. + +```sql +-- 1. Create table +create table if not exists stories ( + id uuid not null primary key DEFAULT uuid_generate_v4(), + created_at timestamp with time zone default timezone('utc' :: text, now()) not null, + content text not null +); + +-- 2. Enable RLS +alter table stories + enable row level security; + +-- 3. Create Policy +create policy "Stories are live for a day" + on stories + for select using ( + created_at > (current_timestamp - interval '1 day') + ); +``` + +### Advanced policies + +Use the full power of SQL to build extremely advanced rules. + +In this example, we will create a `posts` and `comments` tables and then create a policy that depends on another policy. +(In this case, the comments policy depends on the posts policy.) + +```sql +create table posts ( + id serial primary key, + creator_id uuid not null references auth.users(id), + title text not null, + body text not null, + publish_date date not null default now(), + audience uuid[] null -- many to many table omitted for brevity +); + +create table comments ( + id serial primary key, + post_id int not null references posts(id) on delete cascade, + user_id uuid not null references auth.users(id), + body text not null, + comment_date date not null default now() +); + +create policy "Creator can see their own posts" +on posts +for select +using ( + auth.uid() = posts.creator_id +); + +create policy "Logged in users can see the posts if they belong to the post 'audience'." +on posts +for select +using ( + auth.uid() = any (posts.audience) +); + +create policy "Users can see all comments for posts they have access to." +on comments +for select +using ( + exists ( + select 1 from posts + where posts.id = comments.post_id + ) +); +``` + +## Tips + +### Enable Realtime for database tables + +Realtime server broadcasts database changes to authorized users depending on your Row Level Security (RLS) policies. +We recommend that you enable row level security and set row security policies on tables that you add to the publication. +However, you may choose to disable RLS on a table and have changes broadcast to all connected clients. + +```sql +/** + * REALTIME SUBSCRIPTIONS + * Realtime enables listening to any table in your public schema. + */ + +begin; + -- remove the realtime publication + drop publication if exists supabase_realtime; + + -- re-create the publication but don't enable it for any tables + create publication supabase_realtime; +commit; + +-- add a table to the publication +alter publication supabase_realtime add table products; + +-- add other tables to the publication +alter publication supabase_realtime add table posts; +``` + +### You don't have to use policies + +You can also put your authorization rules in your middleware, similar to how you would create security rules with any other `backend <-> middleware <-> frontend` architecture. + +Policies are a tool. In the case of "serverless/Jamstack" setups, they are especially effective because you don't have to deploy any middleware at all. + +However, if you want to use another authorization method for your applications, that's also fine. Supabase is "just Postgres", so if your application +works with Postgres, then it also works with Supabase. + +Tip: Make sure to enable RLS for all your tables, so that your tables are inaccessible. Then use the "Service" which we provide, which is designed to bypass RLS. + +### Never use a service key on the client + +Supabase provides special "Service" keys, which can be used to bypass all RLS. +These should never be used in the browser or exposed to customers, but they are useful for administrative tasks. diff --git a/apps/reference/docs/guides/client-libraries.mdx b/apps/reference/docs/guides/client-libraries.mdx new file mode 100755 index 00000000000..54db0f94a72 --- /dev/null +++ b/apps/reference/docs/guides/client-libraries.mdx @@ -0,0 +1,525 @@ +--- +id: client-libraries +title: Client Libraries +description: 'Supabase provides client libraries in several languages.' +--- + + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + +The [Supabase Client](/docs/reference/javascript/installing) makes it simple for developers to build secure and scalable products. + +## Auth + + +Create new users using [`signUp()`](/docs/reference/javascript/auth-signup). By default, the user will need to verify their email address before logging in.
+If confirmations are disabled the response will contain an access token and also a confirmed_at value, otherwise it will just contain a confirmation_sent_at attribute. + + + + + +```js +const { error, data } = await supabase.auth.signUp({ + email: 'example@email.com', + password: 'example-password', +}) +``` + + + + + +```py +import os +from supabase import create_client, Client + +url: str = os.environ.get("SUPABASE_TEST_URL") +key: str = os.environ.get("SUPABASE_TEST_KEY") +supabase: Client = create_client(url, key) +user = supabase.auth.sign_up( + email='example@email.com', + password='example-password', +) +``` + + + + + + +```dart +import 'package:supabase/supabase.dart'; + +void main() async { + final client = SupabaseClient('supabaseUrl', 'supabaseKey'); + + // Sign up user with email and password + final response = await client + .auth + .signUp('example@email.com', 'example-password'); +} +``` + + + + + + + +Existing users can log in using [`signIn()`](/docs/reference/javascript/auth-signin). + + + + + +```js +const { error, data } = await supabase.auth.signIn({ + email: 'example@email.com', + password: 'example-password' +}) +``` + + + + + +```py +import os +from supabase import create_client, Client + +url: str = os.environ.get("SUPABASE_TEST_URL") +key: str = os.environ.get("SUPABASE_TEST_KEY") +supabase: Client = create_client(url, key) +user = supabase.auth.sign_in( + email='example@email.com', + password='example-password' +) +``` + + + + + + +```dart +import 'package:supabase/supabase.dart'; + +void main() async { + final client = SupabaseClient('supabaseUrl', 'supabaseKey'); + + // Sign in user with email and password + final response = await client + .auth + .signIn(email: 'example@email.com', password: 'example-password'); +} +``` + + + + + + +If there is an email, but no password passed to [`signIn()`](/docs/reference/javascript/auth-signin), the user will receive a magic link. + + + + + +```js +const { error, data } = await supabase.auth.signIn({ + email: 'example@email.com' +}) +``` + + + + + +```py +import os +from supabase import create_client, Client + +url: str = os.environ.get("SUPABASE_TEST_URL") +key: str = os.environ.get("SUPABASE_TEST_KEY") +supabase: Client = create_client(url, key) +user = supabase.auth.sign_in( + email='example@email.com' +) +``` + + + + + + +```dart +import 'package:supabase/supabase.dart'; + +void main() async { + final client = SupabaseClient('supabaseUrl', 'supabaseKey'); + + // Sign in user with email and magic link + final response = await client + .auth + .signIn(email: 'example@email.com'); +} +``` + + + + + + +Third party logins are also handled through [`signIn()`](/docs/reference/javascript/auth-signin). + + + + + + +```js +const { user, error } = await supabase.auth.signIn({ + // provider can be 'github', 'google', 'gitlab', or 'bitbucket' + provider: 'github' +}) +``` + + + + + +```py +# Not yet implemented +``` + + + + + + +```dart +import 'package:supabase/supabase.dart'; + +void main() async { + final client = SupabaseClient('supabaseUrl', 'supabaseKey'); + + final response = await client + .auth + .signIn(provider: Provider.github); +} +``` + + + + + +## Managing data + +Since Postgres is a Relational database, the client makes it simple to query tables and fetch related data in one round-trip, using [`select()`](/docs/reference/javascript/select). + + + + + + +```js +const { data, error } = await supabase + .from('countries') + .select(` + name, + cities ( + name + ) + `) +``` + + + + + +```py +import os +from supabase import create_client, Client + +url: str = os.environ.get("SUPABASE_TEST_URL") +key: str = os.environ.get("SUPABASE_TEST_KEY") +supabase: Client = create_client(url, key) + +data = supabase.table('countries').select('name').execute() +``` + + + + + + +```dart +import 'package:supabase/supabase.dart'; + +void main() async { + final client = SupabaseClient('supabaseUrl', 'supabaseKey'); + + // Query tables and fetch related data in one round-trip, using select() + final response = await client + .from('countries') + .select('name') + .execute(); +} +``` + + + + + + +You can do advanced [filtering](/docs/reference/javascript/using-filters) to extract only the data that you need. + + + + + + +```js +const { data, error } = await supabase + .from('cities') + .select('name, country_id') + .lt('country_id', 100) + .limit(10) +``` + + + + + +```py +data = supabase.table('cities').select('name, country_id').eq('name', 'Germany').execute() +# Assert we pulled real data. +assert len(data.get("data", [])) > 0 +``` + + + + + + +```dart +import 'package:supabase/supabase.dart'; + +void main() async { + final client = SupabaseClient('supabaseUrl', 'supabaseKey'); + + // When fetching data, use advanced filtering to only extract data, that you need. + final response = await client + .from('cities') + .select('name,country_id') + .lt('country_id', 100) + .limit(10) + .execute(); +} +``` + + + + + + +You can create data easily using [`insert()`](/docs/reference/javascript/insert). + + + + + + + +```js +const { data, error } = await supabase + .from('cities') + .insert([ + { name: 'The Shire', country_id: 554 }, + { name: 'Rohan', country_id: 555 }, + ]) +``` + + + + + +```py +data = supabase.table('cities').insert({'name': 'Gotham', 'country_id': 556 }).execute() +# assert if insert response is a success +assert data.get("status_code") in (200, 201) + +# bulk insert +data = supabase.table('cities').insert([ +{'name': 'Gotham', 'country_id': 556 }, +{'name': 'The Shire', 'country_id': 557 } +]).execute() + +``` + + + + + + +```dart +import 'package:supabase/supabase.dart'; + +void main() async { + final client = SupabaseClient('supabaseUrl', 'supabaseKey'); + + // Create data easily, using insert() + final response = await client + .from('cities') + .insert([ + { 'name': 'The Shire', 'country_id': 554 }, + { 'name': 'Rohan', 'country_id': 555 }, + ]) + .execute(); +} +``` + + + + + + +## Realtime Changes + +The Supabase client makes it simple to listen to realtime database changes, using [`subscribe()`](/docs/reference/javascript/subscribe). + + + + + + +```js +const mySubscription = supabase + .from('countries') + .on('*', payload => { + console.log('Change received!', payload) + }) + .subscribe() +``` + + + + + +```py +# Not yet implemented +``` + + + + + + +```dart +import 'package:supabase/supabase.dart'; + +void main() async { + final client = SupabaseClient('supabaseUrl', 'supabaseKey'); + + // Listen to realtime database changes, using subscribe() + final response = await client + .from('countries') + .on(SupabaseEventTypes.all, (payload) { + print('Something happened: ${payload.eventType}'); + }) + .subscribe((String event, {String? errorMsg}) { + print('event: $event error: $errorMsg'); + }); +} +``` + + + + + + +You can even [listen to Row Level changes](/docs/reference/javascript/subscribe#listening-to-row-level-changes). + + + + + + +```js +const mySubscription = supabase + .from('countries:id.eq.200') + .on('UPDATE', handleRecordUpdated) + .subscribe() +``` + + + + + +```py +# Not yet implemented +``` + + + + + + +```dart +import 'package:supabase/supabase.dart'; + +void main() async { + final client = SupabaseClient('supabaseUrl', 'supabaseKey'); + + // You can even listen to Row Level changes + final response = await client + .from('countries:id.eq.200') + .on(SupabaseEventTypes.update, (payload) { + print('Something happened: ${payload.eventType}'); + }) + .subscribe((String event, {String? errorMsg}) { + print('event: $event error: $errorMsg'); + }); +} +``` + + + + + + + +## Next steps + +- View the [Client Docs](/docs/reference/javascript/installing) +- Sign in: [app.supabase.com](https://app.supabase.com) diff --git a/apps/reference/docs/guides/database.mdx b/apps/reference/docs/guides/database.mdx new file mode 100644 index 00000000000..2ee6736a54c --- /dev/null +++ b/apps/reference/docs/guides/database.mdx @@ -0,0 +1,218 @@ +--- +id: database +title: Database +description: Use Supabase to manage your data. +sidebar_label: Overview +--- + +Every Supabase project comes with a full [Postgres](https://www.postgresql.org/) database, a free and open source +database which is considered one of the world's most stable and advanced databases. + +## Postgres or PostgreSQL? + +PostgreSQL the database was derived from the POSTGRES Project, a package written at the University of California at Berkeley in 1986. +This package included a query language called "PostQUEL". + +In 1994, Postgres95 was built on top of POSTGRES code, adding an SQL language interpreter as a replacement for PostQUEL. +Eventually, Postgres95 was renamed to PostgreSQL to reflect the SQL query capability. + +After this, many people referred to it as Postgres since it's less prone to confusion. Supabase is all about +simplicity, so we also refer to it as Postgres. + +## Features + +### Table View + +You don't have to be a database expert to start using Supabase. Our table view makes Postgres as easy to use as a spreadsheet. + +![Table View.](/img/table-view.png) + +### Relationships + +Dig into the relationships within your data. + + + +### Clone tables + +You can duplicate your tables, just like you would inside a spreadsheet. + + + +### The SQL Editor + +Supabase comes with a SQL Editor. You can also save your favorite queries to run later! + + + +### Additional features + +- Supabase extends Postgres with realtime functionality using our [Realtime Server](https://github.com/supabase/realtime). +- Every project is a full Postgres database, with `postgres` level access. +- Managed backups - Supabase handles all your database backups.[^backups] +- Data imports - import directly from a CSV or excel spreadsheet. + +[^backups] Database backups do _NOT_ include objects stored via the Storage API, as the database only includes metadata about these objects. Restoring an old backup will not restore objects that have been deleted since then. + +### Extensions + +To expand the functionality of your Postgres database, you can use extensions. +You can enable Postgres extensions with the click of a button within the Supabase dashboard. + + + +[Learn more](/docs/guides/database/extensions) about all the extensions provided on Supabase. + +## Tips + +### Realtime + +Supabase provides a realtime engine on top of Postgres, so that you can listen to changes as they happen. +Our realtime engine uses the built-in replication functionality of Postgres. + +Realtime server broadcasts database changes to authorized users depending on your Row Level Security (RLS) policies. +We recommend that you enable row level security and set row security policies on tables that you add to the publication. +However, you may choose to disable RLS on a table and have changes broadcast to all connected clients. + +You can manage the realtime system, simply by +[updating](/docs/guides/database/replication) the `supabase_realtime` publication. + +For example to enable realtime only for individual tables: + +```sql +begin; + -- remove the realtime publication + drop publication if exists supabase_realtime; + + -- re-create the publication but don't enable it for any tables + create publication supabase_realtime; +commit; + +-- add a table to the publication +alter publication supabase_realtime add table products; + +-- add other tables to the publication +alter publication supabase_realtime add table posts; +``` + +By default only "new" values are sent, but if you want to receive the old record (previous values) whenever you `update` or `delete` a record, +you can update the replica identity of your tables, setting it to `full`: + +```sql +alter table your_table replica identity full; +``` + +### Migrating between projects + +Migrating projects can be achieved using standard PostgreSQL tooling. This is particularly useful for older projects (e.g. to use a newer Postgres version). + +#### Before you begin + +- Make sure [Postgres](https://www.postgresql.org/download/) is installed so you can run `psql` and `pg_dump`. +- Create a new Supabase project. +- If you enabled Database Webhooks on your old project, enable it on your new project. +- Store the old project's database URL as `$OLD_DB_URL` and the new project's as `$NEW_DB_URL`. + +#### Migrate the database + +1. Run `ALTER ROLE postgres SUPERUSER` in the _old_ project's SQL editor +2. Run `pg_dump --clean --if-exists --quote-all-identifiers -h $OLD_DB_URL -U postgres > dump.sql` from your terminal +3. Run `ALTER ROLE postgres NOSUPERUSER` in the _old_ project's SQL editor +4. Run `ALTER ROLE postgres SUPERUSER` in the _new_ project's SQL editor +5. Run `psql -h $NEW_DB_URL -U postgres -f dump.sql` from your terminal +6. Run `TRUNCATE storage.objects` in the _new_ project's SQL editor +7. Run `ALTER ROLE postgres NOSUPERUSER` in the _new_ project's SQL editor + +#### Migrate storage objects + +This script moves storage objects from one project to another. If you have more than 10k objects, we can move the objects for you. Just contact us at [support@supabase.io](mailto:support@supabase.io). + +```js +const { createClient } = require('@supabase/supabase-js') + +const OLD_PROJECT_URL = 'https://xxx.supabase.co' +const OLD_PROJECT_SERVICE_KEY = 'old-project-service-key-xxx' + +const NEW_PROJECT_URL = 'https://yyy.supabase.co' +const NEW_PROJECT_SERVICE_KEY = 'new-project-service-key-yyy' + +;(async () => { + const oldSupabaseRestClient = createClient(OLD_PROJECT_URL, OLD_PROJECT_SERVICE_KEY, { + schema: 'storage', + }) + const oldSupabaseClient = createClient(OLD_PROJECT_URL, OLD_PROJECT_SERVICE_KEY) + const newSupabaseClient = createClient(NEW_PROJECT_URL, NEW_PROJECT_SERVICE_KEY) + + // make sure you update max_rows in postgrest settings if you have a lot of objects + // or paginate here + const { data: oldObjects, error } = await oldSupabaseRestClient.from('objects').select() + if (error) { + console.log('error getting objects from old bucket') + throw error + } + + for (const objectData of oldObjects) { + console.log(`moving ${objectData.id}`) + try { + const { data, error: downloadObjectError } = await oldSupabaseClient.storage + .from(objectData.bucket_id) + .download(objectData.name) + if (downloadObjectError) { + throw downloadObjectError + } + + const { _, error: uploadObjectError } = await newSupabaseClient.storage + .from(objectData.bucket_id) + .upload(objectData.name, data, { + upsert: true, + contentType: objectData.metadata.mimetype, + cacheControl: objectData.metadata.cacheControl, + }) + if (uploadObjectError) { + throw uploadObjectError + } + } catch (err) { + console.log('error moving ', objectData) + console.log(err) + } + } +})() +``` + +#### Caveats + +- The new project will have the old project's Storage buckets, but not the objects. You will need to migrate Storage objects manually. + +### Resetting your project password + +When you create a new project in Supabase we ask for a password. You can use this password to connect directly to your Postgres database. + +If you forget your password, you can reset it from the Dashboard under the database settings page. + +Read more in [Database Configuration](/docs/guides/database/managing-passwords). + +### Changing the timezone of your server. + +Your database is initialized with the UTC timezone. We recommend keeping it this way, as it is helpful for time calculations. +If, however, you want to update the timezone, you can do so using any of the [database timezones](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + +For example: + +```sql +alter database postgres set timezone to 'America/New_York'; +``` + +Read more in [Database Configuration](/docs/guides/database/managing-timezones). + +## Next steps + +- Read more about [Postgres](/docs/postgres/server/about) +- Sign in: [app.supabase.com](https://app.supabase.com) diff --git a/apps/reference/docs/guides/database/arrays.mdx b/apps/reference/docs/guides/database/arrays.mdx new file mode 100644 index 00000000000..63c5a12716d --- /dev/null +++ b/apps/reference/docs/guides/database/arrays.mdx @@ -0,0 +1,175 @@ +--- +id: arrays +title: 'Working With Arrays' +description: How to use arrays in PostgreSQL and the Supabase API. +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +PostgreSQL supports flexible [array types](https://www.postgresql.org/docs/12/arrays.html). These arrays are also supported in the Supabase Dashboard and in the JavaScript API. + +## Create a table with an array column + +Create a test table with a text array (an array of strings): + + + + + +1. Go to the [Table editor](https://app.supabase.com/project/_/editor) page in the Dashboard. +1. Click **New Table** and create a table with the name `arraytest`. +1. Click **Save**. +1. Click **New Column** and create a column with the name `textarray`, type `text`, and select **Define as array**. +1. Click **Save**. + + + + + +```sql +CREATE TABLE arraytest (id integer NOT NULL, textarray text ARRAY); +``` + + + + +## Insert a record with an array value + + + + + +1. Go to the [Table editor](https://app.supabase.com/project/_/editor) page in the Dashboard. +1. Select the `arraytest` table. +1. Click **Insert row** and add `["Harry", "Larry", "Moe"]`. +1. Click **Save.** + + + + + +```sql +INSERT INTO arraytest (id, textarray) VALUES (1, ARRAY['Harry', 'Larry', 'Moe']); +``` + + + + +Insert a record from the JavaScript client: + +```js +const { data, error } = await supabase + .from('arraytest') + .insert([{ id: 2, textarray: ['one', 'two', 'three', 'four'] }]) +``` + + + + + +## View the results + + + + + +1. Go to the [Table editor](https://app.supabase.com/project/_/editor) page in the Dashboard. +1. Select the `arraytest` table. + +You should see: + +| id | textarray | +| --- | ----------------------- | +| 1 | ["Harry","Larry","Moe"] | + + + + +```sql +SELECT * FROM arraytest; +``` + +You should see: + +| id | textarray | +| --- | ----------------------- | +| 1 | ["Harry","Larry","Moe"] | + + + + +## Query array data + +PostgreSQL uses 1-based indexing (e.g., `textarray[1]` is the first item in the array). + + + + + +To select the first item from the array and get the total length of the array: + +```js +SELECT textarray[1], array_length(textarray, 1) FROM arraytest; +``` + +returns: + +| textarray | array_length | +| --------- | ------------ | +| Harry | 3 | + + + + + +This returns the entire array field: + +```js +const { data, error } = await supabase.from('arraytest').select('textarray[]') +console.log(JSON.stringify(data, null, 2)) +``` + +returns: + +```js +[ + { + textarray: ['Harry', 'Larry', 'Moe'], + }, +] +``` + + + + +## Resources + +- [Supabase JS Client](https://github.com/supabase/supabase-js) +- [Supabase Account - Free Tier OK](https://supabase.com) +- [PostgreSQL Arrays](https://www.postgresql.org/docs/12/arrays.html) diff --git a/apps/reference/docs/guides/database/connecting-to-postgres.mdx b/apps/reference/docs/guides/database/connecting-to-postgres.mdx new file mode 100644 index 00000000000..183c12580d4 --- /dev/null +++ b/apps/reference/docs/guides/database/connecting-to-postgres.mdx @@ -0,0 +1,135 @@ +--- +id: connecting-to-postgres +title: 'Database Connections' +description: There are various ways to connect to your Postgres database. +--- + +Supabase provides several options for programmatically connecting to your Postgres database: + +## Types of Connection + +- HTTP connections using the API. +- Direct connections using Postgres' standard connection system. +- Connection pooling using PgBouncer. + +### API vs Direct vs Pooling + +- The API is an auto-generated REST inteface. You should use this for all browser and application interactions. +- A "direct connection" is when a connection is made to the database using Postgres' native connection implementation. You should use this for tools which are always alive - usually installed on a long-running server. +- A "connection pool" is a system (external to Postgres) which keeps connections "open". You should use this for serverless functions and tools which disconnect from the database frequently. + +Why would you use a connection pool? Primarily because the way that Postgres handles connections isn't very scalable for a large number of _temporary_ connections. +You can use these simple questions to determine which connection method to use: + +- Are you connecting to a database and _maintaining_ a connection? If yes, use a direct connection. +- Are you connecting to your database and then _disconnecting_ immediately (e.g. a serverless environment)? If yes, use a connection pool. + +## API + +Supabase provides an auto-updating [API](/docs/guides/api). This is the easiest way to get started if you are managing data (fetching, inserting, updating). + +### Interfaces + +We provides several types of API to suit your preferences and use-case: + +- [REST](/docs/guides/api#rest-api): interact with your database through a REST interface. +- [GraphQL](/docs/guides/api#graphql-api): interact with your database through a GraphQL interface. +- [Realtime](/docs/guides/api#realtime-api): listen to database changes over websockets. + +You cannot manage the database schema via the API (for security reasons). To do that you can use the dashboard or connect directly to your database. + +### API URL and Keys + +You can find the API URL and Keys in the [Dashboard](https://app.supabase.com/project/_/settings/api). + + + +## Direct connections + +Every Supabase project provides a full Postgres database. You can connect to the database using any tool which supports Postgres. + +### Finding your connection string + +1. Go to the `Settings` section. +2. Click `Database`. +3. Find your Connection Info and Connection String. Direct connections are on port `5432`. + + + +## Connection Pool + +Connection pools are useful for managing a large number of _temporary_ connections. For example, if you are using [Prisma](/docs/guides/integrations/prisma) deployed to a Serverless environment. + +### How connection pooling works + +A "connection pool" is a system (external to Postgres) which manages connections, rather than PostgreSQL's native system. Supabase uses [PgBouncer](https://www.pgbouncer.org/) for connection pooling. + +When a client makes a request, PgBouncer "allocates" an available connection to the client. +When the client transaction or session is completed the connection is returned to the pool and is free to be used by another client. + +![Connection pooling](/img/guides/database/connection-pool.png) + +### Pool modes + +Pool Mode determines how PgBouncer handles a connection. + +#### Session + +When a new client connects, a connection is assigned to the client until it disconnects. Afterward, the connection is returned back to the pool. + +All PostgreSQL features can be used with this option. + +#### Transaction + +This is the suggested option for serverless functions. A connection is only assigned to the client for the duration of a transaction. Two consecutive transactions from the same client +could be executed over two different connections. + +Some session-based PostgreSQL features such as prepared statements are not available with this option. +A comprehensive list of incompatible features can be found [here](https://www.pgbouncer.org/features.html). + +#### Statement + +This is the most granular option. Connections are returned to the pool after every statement. Transactions with multiple statements are not allowed. This is best used when `AUTOCOMMIT` is in use. + +### Finding the connection pool config + +1. Go to the `Settings` section. +2. Click `Database`. +3. Find your Connection Info and Connection String. Connection pooling is on port `6543`. + + + +## Connecting with SSL + +Use this when connecting to your database to prevent snooping and man-in-the-middle attacks. + +Obtain your connection info and Server root certificate from your application’s dashboard. +![Connection Info and Certificate.](/img/guides/database/connection-info-cert.png) + +Assuming you’ve downloaded your certificate and it’s located at `$HOME/Downloads/prod-ca-2021.cer`, and your Host address is `db.abcdefghijklm.supabase.co` you can connect to the DB with +SSL enabled as illustrated below: + +1. With `psql` + +``` +psql "sslmode=verify-full sslrootcert=$HOME/Downloads/prod-ca-2021.cer host=db.abcdefghijklm.supabase.co dbname=postgres user=postgres" +``` + +2. With `pgAdmin` + a. Register a new Postgres server + ![Register a new postgres server.](/img/guides/database/register-server-pgAdmin.png) + + b. Name your server to your liking and add the connection info. + ![Name Postgres Server.](/img/guides/database/name-pg-server.png) + ![Add Connection Info.](/img/guides/database/add-pg-server-conn-info.png) + +3. Navigate to the SSL tab and change the SSL mode to Require. Next navigate to the Root certificate input, it will open up a + file-picker modal. Select the certificate you downloaded from your Supabase dashboard and save the server details. PgAdmin + should now be able to connect to your Postgres via SSL. + ![Add Connection Info.](/img/guides/database/add-ssl-config.png) diff --git a/apps/reference/docs/guides/database/extensions.mdx b/apps/reference/docs/guides/database/extensions.mdx new file mode 100644 index 00000000000..fceef7106e5 --- /dev/null +++ b/apps/reference/docs/guides/database/extensions.mdx @@ -0,0 +1,62 @@ +--- +id: extensions +title: Overview +description: Using Postgres extensions. +--- + +import ExtensionsComponent from '@site/src/components/Extensions' +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +Extensions are exactly as they sound - they "extend" the database with functionality which isn't part of the Postgres core. +Supabase has pre-installed some of the most useful open source extensions. + + +### Enable and disable extensions + + + + + +1. Go to the [Database](https://app.supabase.com/project/_/database/tables) page in the Dashboard. +2. Click **Extensions** in the sidebar. +3. Enable or disable an extension. + + + + + + + +```sql +-- Example: enable the "pgtap" extension and ensure it is installed +create extension pgtap with schema extensions; + +-- Example: disable the "pgtap" extension +drop extension pgtap; +``` + +Even though the SQL code is `create extension`, this is the equivalent of "enabling the extension". +To disable an extension call `drop extension`. + +:::caution +Enabling some extensions with `create extension with schema extensions` may lead to permission issues (e.g., `dblink`, `http`, `pg_cron`). +::: + + + + + + +### Full list of extensions + +Supabase is pre-configured with over 50 extensions. You can also install your own SQL extensions directly in the database through our SQL editor. + + diff --git a/apps/reference/docs/guides/database/extensions/http.mdx b/apps/reference/docs/guides/database/extensions/http.mdx new file mode 100644 index 00000000000..3ae3da1b654 --- /dev/null +++ b/apps/reference/docs/guides/database/extensions/http.mdx @@ -0,0 +1,122 @@ +--- +id: http +title: "http: RESTful Client" +description: An HTTP Client for PostgreSQL Functions. +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +The `http` extension allows you to call RESTful endpoints within Postgres. + +## Quick demo + + + +## Overview + +Let's cover some basic concepts: + +- REST: stands for REpresentational State Transfer. It's simply a way to request data from external services. +- RESTful APIs are servers which accept HTTP "calls". The calls are typically: + - `GET` − Read only access to a resource. + - `POST` − Creates a new resource. + - `DELETE` − Removes a resource. + - `PUT` − Updates an existing resource or creates a new resource. + +You can use the `http` extension to make these network requests from Postgres. + +## Usage + + +### Enable the extension + + + + + +1. Go to the [Database](https://app.supabase.com/project/_/database/tables) page in the Dashboard. +2. Click on **Extensions** in the sidebar. +3. Search for "http" and enable the extension. + + + + +```sql +-- Example: enable the "http" extension +create extension http with schema extensions; + +-- Example: disable the "http" extension +drop extension if exists http; +``` + +Even though the SQL code is `create extension`, this is the equivalent of "enabling the extension". +To disable an extension, call `drop extension`. + +It's good practice to create the extension within a separate schema (like `extensions`) to keep your database clean. + + + + + +### Available functions + +While the main usage is simply `http('http_request')`, there are 5 wrapper functions for specific functionality: + +- `http_get()` +- `http_post()` +- `http_put()` +- `http_delete()` +- `http_head()` + +### Returned values + +A successful call to a web URL from the `http` extension returns a record with the following fields: + +- `status`: integer +- `content_type`: character varying +- `headers`: http_header[] +- `content`: character varying. Typically you would want to cast this to `jsonb` using the format `content::jsonb` + +## Examples + +### Simple `GET` example + +```sql +select + "status", "content"::jsonb +from + http_get('https://jsonplaceholder.typicode.com/todos/1'); +``` + + +### Simple `POST` example + +```sql +select + "status", "content"::jsonb +from + http_post( + 'https://jsonplaceholder.typicode.com/posts', + '{ "title": "foo", "body": "bar", "userId": 1 }', + 'application/json' + ); +``` + + +## Resources + +- Official [`http` GitHub Repository](https://github.com/pramsey/pgsql-http) diff --git a/apps/reference/docs/guides/database/extensions/pgtap.mdx b/apps/reference/docs/guides/database/extensions/pgtap.mdx new file mode 100644 index 00000000000..484a50f7afd --- /dev/null +++ b/apps/reference/docs/guides/database/extensions/pgtap.mdx @@ -0,0 +1,126 @@ +--- +id: pgtap +title: "pgTAP: Unit Testing" +description: Unit testing in PostgreSQL. +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +`pgTAP` is a unit testing extension for PostgreSQL. + +## Overview + +Let's cover some basic concepts: + +- Unit tests: allow you to test small parts of a system (like a database table!). +- TAP: stands for [Test Anything Protocol](http://testanything.org/). It is an framework which aims to simplify the error reporting during testing. + +## Usage + +### Enable the extension + + + + + +1. Go to the [Database](https://app.supabase.com/project/_/database/tables) page in the Dashboard. +2. Click on **Extensions** in the sidebar. +3. Search for "pgtap" and enable the extension. + + + + + + +```sql +-- Enable the "pgtap" extension +create extension pgtap with schema extensions; + +-- Disable the "pgtap" extension +drop extension if exists pgtap; +``` + +Even though the SQL code is `create extension`, this is the equivalent of "enabling the extension". +To disable an extension you can call `drop extension`. + +It's good practice to create the extension within a separate schema (like `extensions`) to keep your database clean. + + + + + +### Managing tests + +It's a good practice to keep all your tests in a separate schema. + +```sql +create schema tests; +``` + +### Creating a test + + +@TODO + +- Create a plan +- We should come up with a recommendation on how to run the tests. Via a function? External scripts? +- Eventually this can be done via our CLI + + +### Running a test + +@TODO + + +## Examples + +Let's look at a few different tests which could be helpful in your project. + + +### Testing tables + + +```sql +begin; +select plan( 1 ); + +select has_table( 'profiles' ); + +select * from finish(); +rollback; +``` + +API: + +- [`has_table()`](https://pgtap.org/documentation.html#has_table) + + +### Testing columns + +```sql +begin; +select plan( 1 ); + +select has_column( 'profiles', 'id' ); +select col_is_pk( 'profiles', 'id' ); + +select * from finish(); +rollback; +``` + +API: + +- [`has_column()`](https://pgtap.org/documentation.html#has_column) +- [`col_is_pk()`](https://pgtap.org/documentation.html#col_is_pk) + +## Resources + +- Official [`pgTAP` documentation](https://pgtap.org/) diff --git a/apps/reference/docs/guides/database/extensions/plv8.mdx b/apps/reference/docs/guides/database/extensions/plv8.mdx new file mode 100644 index 00000000000..1eed5c92bac --- /dev/null +++ b/apps/reference/docs/guides/database/extensions/plv8.mdx @@ -0,0 +1,146 @@ +--- +id: plv8 +title: "plv8: JavaScript Language" +description: JavaScript language for PostgreSQL. +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +The `plv8` extension allows you use JavaScript within Postgres. + +## Overview + +While Postgres natively runs SQL, it can also run other "procedural languages". +`plv8` allows you to run JavaScript code - specifically any code that runs on the [V8 JavaScript engine](https://v8.dev). + +It can be used for database functions, triggers, queries and more. + +## Usage + +### Enable the extension + + + + + +1. Go to the [Database](https://app.supabase.com/project/_/database/tables) page in the Dashboard. +2. Click on **Extensions** in the sidebar. +3. Search for "plv8" and enable the extension. + + + + +```sql +-- Example: enable the "plv8" extension +create extension plv8; + +-- Example: disable the "plv8" extension +drop extension if exists plv8; +``` + +Even though the SQL code is `create extension`, this is the equivalent of "enabling the extension". +To disable an extension, call `drop extension`. + +Procedural languages are automatically installed within `pg_catalog`, so you don't need to specify a schema. + + + + +### Create `plv8` functions + +Functions written in `plv8` are written just like any other PostgreSQL functions, only +with the `language` identifier set to `plv8`. + +```sql +create or replace function function_name() +returns void as $$ + // V8 JavaScript + // code + // here +$$ language plv8; +``` + +You can call `plv8` functions like any other Postgres function: + + + + + +```sql +select function_name(); +``` + + + + +```js +const { data, error } = supabase.rpc('function_name') +``` + + + + +## Examples + +### Scalar functions + +A [scalar function](https://plv8.github.io/#scalar-function-calls) is anything that takes in some user input and returns a single result. + +```sql +create or replace function hello_world(name text) +returns text as $$ + + let output = `Hello, ${name}!`; + return output; + +$$ language plv8; +``` + +### Executing SQL + +You can execute SQL within `plv8` code using the [`plv8.execute` function](https://plv8.github.io/#plv8-execute). + +```sql +create or replace function update_user(id bigint, first_name text) +returns smallint as $$ + + var num_affected = plv8.execute( + 'update profiles set first_name = $1 where id = $2', + [first_name, id] + ); + + return num_affected; +$$ language plv8; +``` + +### Set-returning functions + +A [set-returning function](https://plv8.github.io/#set-returning-function-calls) is anything that returns a full set of results - for example, rows in a table. + +```sql +create or replace function get_messages() +returns setof messages as $$ + + var json_result = plv8.execute( + 'select * from messages' + ); + + return json_result; +$$ language plv8; +``` + +## Resources + +- Official [`plv8` documentation](https://plv8.github.io/) +- [plv8 GitHub Repository](https://github.com/plv8/plv8) diff --git a/apps/reference/docs/guides/database/extensions/uuid-ossp.mdx b/apps/reference/docs/guides/database/extensions/uuid-ossp.mdx new file mode 100644 index 00000000000..0fdb296c6b7 --- /dev/null +++ b/apps/reference/docs/guides/database/extensions/uuid-ossp.mdx @@ -0,0 +1,98 @@ +--- +id: uuid-ossp +title: "uuid-ossp: Unique Identifiers" +description: A UUID generator for PostgreSQL. +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +The `uuid-ossp` extension can be used to generate a `UUID`. + + +## Overview + +A `UUID` is a "Universally Unique Identifer" and it is, for practical purposes, unique. +This makes them particularly well suited as Primary Keys. It is occasionally referred to as a `GUID`, which stands for "Globally Unique Identifer". + +## Usage + +### Enable the extension + + + + + +1. Go to the [Database](https://app.supabase.com/project/_/database/tables) page in the Dashboard. +2. Click on **Extensions** in the sidebar. +3. Search for "uuid-ossp" and enable the extension. + +**Note**: +Currently `uuid-ossp` extension is enabled by default and cannot be disabled. + + + + +```sql +-- Example: enable the "uuid-ossp" extension +create extension "uuid-ossp" with schema extensions; + +-- Example: disable the "uuid-ossp" extension +drop extension if exists "uuid-ossp"; +``` + +Even though the SQL code is `create extension`, this is the equivalent of "enabling the extension". +To disable an extension, call `drop extension`. + +It's good practice to create the extension within a separate schema (like `extensions`) to keep your database clean. + +**Note**: +Currently `uuid-ossp` extension is enabled by default and cannot be disabled. + + + + + +### The `uuid` type + +Once the extension is enabled, you now have access to a `uuid` type. + +### `uuid_generate_v1()` + +Creates a UUID value based on the combination of computer’s MAC address, current timestamp, and a random value. + +### `uuid_generate_v4()` + +Creates UUID values based solely on random numbers. + +## Examples + +### Within a query + +```sql +select uuid_generate_v4(); +``` + +### As a Primary Key + +Automatically create a unique, random ID in a table: + +```sql +create table contacts ( + id uuid default uuid_generate_v4(), + first_name text, + last_name text, + + primary key (id) +); +``` + + +## Resources + +- [The Basics Of PostgreSQL `UUID` Data Type](https://www.postgresqltutorial.com/postgresql-uuid/) diff --git a/apps/reference/docs/guides/database/full-text-search.mdx b/apps/reference/docs/guides/database/full-text-search.mdx new file mode 100644 index 00000000000..53698afc5d3 --- /dev/null +++ b/apps/reference/docs/guides/database/full-text-search.mdx @@ -0,0 +1,630 @@ +--- +id: full-text-search +title: "Full Text Search" +description: How to use full text search in PostgreSQL. +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + +Postgres has built-in functions to handle `Full Text Search` queries. This is like a "search engine" within Postgres. + + +## Preparation + +For this guide we'll use the following example data: + + + + + + +```sql +create table books ( + id serial primary key, + title text, + author text, + description text +); + +insert into books (title, author, description) +values + ('The Poky Little Puppy','Janette Sebring Lowrey','Puppy is slower than other, bigger animals.'), + ('The Tale of Peter Rabbit','Beatrix Potter','Rabbit eats some vegetables.'), + ('Tootle','Gertrude Crampton','Little toy train has big dreams.'), + ('Green Eggs and Ham','Dr. Seuss','Sam has changing food preferences and eats unusually colored food.'), + ('Harry Potter and the Goblet of Fire','J.K. Rowling','Fourth year of school starts, big drama ensues.'); +``` + + + + +| id | title | author | description | +| ---- | ---- | ---- | ----------- | +| 1 | The Poky Little Puppy | Janette Sebring Lowrey | Puppy is slower than other, bigger animals. | +| 2 | The Tale of Peter Rabbit | Beatrix Potter | Rabbit eats some vegetables. | +| 3 | Tootle | Gertrude Crampton | Little toy train has big dreams. | +| 4 | Green Eggs and Ham | Dr. Seuss | Sam has changing food preferences and eats unusually colored food. | +| 5 | Harry Potter and the Goblet of Fire | J.K. Rowling | Fourth year of school starts, big drama ensues. | + + + + + +## Usage + +The functions we'll cover in this guide are: + +### `to_tsvector()` + +Converts your data into searchable "tokens". `to_tsvector()` stands for "to text search vector". For example: + +```sql +select to_tsvector('green eggs and ham') + +-- Returns 'egg':2 'green':1 'ham':4 +``` + +Collectively these tokens are called a "document" which Postgres can use for comparisons. + +### `to_tsquery()` + +Converts a query string into "tokens" to match. `to_tsquery()` stands for "to text search query". + +This conversion step is important because we will want to "fuzzy match" on keywords. +For example if a user searches for "eggs", and a column has the value "egg", we probably still want to return a match. + + +### Match: `@@` + +The `@@` symbol is the "match" symbol for Full Text Search. It returns any matches between a `to_tsvector` result and a `to_tsquery` result. + +Take the following example: + + + + +```sql +select * +from books +where title = 'Harry'; +``` + + + + +```js +const { data, error } = await supabase + .from('books') + .select() + .eq('title', 'Harry') +``` + + + + + +```dart +final result = await client + .from('books') + .select() + .eq('title', 'Harry') + .execute(); +``` + + + + + +The equality symbol above (`=`) is very "strict" on what it matches. In a full text search context, we might want to find all "Harry Potter" books and so we can rewrite the +example above: + + + + +```sql +select * +from books +where to_tsvector(title) @@ to_tsquery('Harry'); +``` + + + + +```js +const { data, error } = await supabase + .from('books') + .select() + .textSearch('title', `'Harry'`) +``` + + + + +```dart +final result = await client + .from('books') + .select() + .textSearch('title', "'Harry'") + .execute(); +``` + + + + +## Basic Full Text Queries + +### Search a single column + +To find all `books` where the `description` contain the word `big`: + + + + +```sql +select + * +from + books +where + to_tsvector(description) + @@ to_tsquery('big'); +``` + + + + +```js +const { data, error } = await supabase + .from('books') + .select() + .textSearch('description', `'big'`) +``` + + + + +```dart +final result = await client + .from('books') + .select() + .textSearch('description', "'big'") + .execute(); +``` + + + + +| id | title | author | description | +| -- | ----------------------------------- | ----------------- | ----------------------------------------------- | +| 3 | Tootle | Gertrude Crampton | Little toy train has big dreams. | +| 5 | Harry Potter and the Goblet of Fire | J.K. Rowling | Fourth year of school starts, big drama ensues. | + + + + +### Search multiple columns + +To find all `books` where `description` or `title` contain the word `little`: + + + + +```sql +select + * +from + books +where + to_tsvector(description || ' ' || title) -- concat columns, but be sure to include a space to separate them! + @@ to_tsquery('little'); +``` + + + + +| id | title | author | description | +| -- | --------------------- | ---------------------- | ------------------------------------------- | +| 1 | The Poky Little Puppy | Janette Sebring Lowrey | Puppy is slower than other, bigger animals. | +| 3 | Tootle | Gertrude Crampton | Little toy train has big dreams. | + + + + +### Match all search words + +To find all `books` where `description` contains BOTH of the words `little` and `big`, we can use the `&` symbol: + + + + +```sql +select + * +from + books +where + to_tsvector(description) + @@ to_tsquery('little & big'); -- use & for AND in the search query +``` + + + + +```js +const { data, error } = await supabase + .from('books') + .select() + .textSearch('description', `'little' & 'big'`) +``` + + + + +```dart +final result = await client + .from('books') + .select() + .textSearch('description', "'little' & 'big'") + .execute(); +``` + + + + +| id | title | author | description | +| -- | ------ | ----------------- | -------------------------------- | +| 3 | Tootle | Gertrude Crampton | Little toy train has big dreams. | + + + + +### Match any search words + +To find all `books` where `description` contain ANY of the words `little` or `big`, use the `|` symbol: + + + + +```sql +select + * +from + books +where + to_tsvector(description) + @@ to_tsquery('little | big'); -- use | for OR in the search query +``` + + + + +```js +const { data, error } = await supabase + .from('books') + .select() + .textSearch('description', `'little' | 'big'`) +``` + + + + +```dart +final result = await client + .from('books') + .select() + .textSearch('description', "'little' | 'big'") + .execute(); +``` + + + + +| id | title | author | description | +| -- | --------------------- | ---------------------- | ------------------------------------------- | +| 1 | The Poky Little Puppy | Janette Sebring Lowrey | Puppy is slower than other, bigger animals. | +| 3 | Tootle | Gertrude Crampton | Little toy train has big dreams. | + + + + +Notice how searching for `big` includes results with the word `bigger` (or `biggest`, etc). + +## Creating Indexes + +Now that we have Full Text Search working, let's create an `index`. This will allow Postgres to "build" the documents pre-emptively so that they +don't need to be created at the time we execute the query. This will make our queries much faster. + +### Searchable columns + +Let's create a new column `fts` inside the `books` table to store the searchable index of the `title` and `description` columns. + +We can use a special feature of Postgres called +[Generated Columns](https://www.postgresql.org/docs/current/ddl-generated-columns.html) +to ensure that the index is updated any time the values in the `title` and `description` columns change. + + + + +```sql +alter table + books +add column + fts tsvector generated always as (to_tsvector('english', description || ' ' || title)) stored; + +create index books_fts on books using gin (fts); -- generate the index + +select id, fts +from books; +``` + + + + +| id | fts | +| -- | --------------------------------------------------------------------------------------------------------------- | +| 1 | 'anim':7 'bigger':6 'littl':10 'poki':9 'puppi':1,11 'slower':3 | +| 2 | 'eat':2 'peter':8 'rabbit':1,9 'tale':6 'veget':4 | +| 3 | 'big':5 'dream':6 'littl':1 'tootl':7 'toy':2 'train':3 | +| 4 | 'chang':3 'color':9 'eat':7 'egg':12 'food':4,10 'green':11 'ham':14 'prefer':5 'sam':1 'unus':8 | +| 5 | 'big':6 'drama':7 'ensu':8 'fire':15 'fourth':1 'goblet':13 'harri':9 'potter':10 'school':4 'start':5 'year':2 | + + + + +### Search using the new column + +Now that we've created and populated our index, we can search it using the same techniques as before: + + + + +```sql +select + * +from + books +where + fts @@ to_tsquery('little & big'); +``` + + + + +```js +const { data, error } = await supabase + .from('books') + .select() + .textSearch('fts', `'little' & 'big'`) +``` + + + + +```dart +final result = await client + .from('books') + .select() + .textSearch('fts', "'little' & 'big'") + .execute(); +``` + + + + +| id | title | author | description | fts | +| -- | ------ | ----------------- | -------------------------------- | ------------------------------------------------------- | +| 3 | Tootle | Gertrude Crampton | Little toy train has big dreams. | 'big':5 'dream':6 'littl':1 'tootl':7 'toy':2 'train':3 | + + + + +## Query Operators + +Visit [PostgreSQL: Text Search Functions and Operators](https://www.postgresql.org/docs/current/functions-textsearch.html) +to learn about additional query operators you can use to do more advanced `full text queries`, such as: + +### Proximity: `<->` + +The proximity symbol is useful for searching for terms that are a certain "distance" apart. +For example, to find the phrase `big dreams`, where the a match for "big" is followed immediately by a match for "dreams": + + + + + +```sql +select + * +from + books +where + to_tsvector(description) @@ to_tsquery('big <-> dreams'); +``` + + + + +```js +const { data, error } = await supabase + .from('books') + .select() + .textSearch('description', `'big' <-> 'dreams'`) +``` + + + + +```dart +final result = await client + .from('books') + .select() + .textSearch('description', "'big' <-> 'dreams'") + .execute(); +``` + + + + + +We can also use the `<->` to find words within a certain distance of eachother. For example to find `year` and `school` within 2 words of each other: + + + + +```sql +select + * +from + books +where + to_tsvector(description) @@ to_tsquery('year <2> school'); +``` + + + + +```js +const { data, error } = await supabase + .from('books') + .select() + .textSearch('description', `'year' <2> 'school'`) +``` + + + + +```dart +final result = await client + .from('books') + .select() + .textSearch('description', "'year' <2> 'school'") + .execute(); +``` + + + + + +### Negation: `!` + +The negation symbol can be used to find phrases which _don't_ contain a search term. +For example, to find records that have the word `big` but not `little`: + + + + +```sql +select + * +from + books +where + to_tsvector(description) @@ to_tsquery('big & !little'); +``` + + + + +```js +const { data, error } = await supabase + .from('books') + .select() + .textSearch('description', `'big' & !'little'`) +``` + + + + +```dart +final result = await client + .from('books') + .select() + .textSearch('description', "'big' & !'little'") + .execute(); +``` + + + + + +## Resources + +* [PostgreSQL: Text Search Functions and Operators](https://www.postgresql.org/docs/12/functions-textsearch.html) + + + diff --git a/apps/reference/docs/guides/database/functions.mdx b/apps/reference/docs/guides/database/functions.mdx new file mode 100644 index 00000000000..507643e7a31 --- /dev/null +++ b/apps/reference/docs/guides/database/functions.mdx @@ -0,0 +1,362 @@ +--- +id: functions +title: Database Functions +description: Creating and using Postgres functions. +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + +Postgres has built-in support for [SQL functions](https://www.postgresql.org/docs/current/sql-createfunction.html). +These functions live inside your database, and they can be [used with the API](/docs/reference/javascript/rpc). + +## Quick demo + + + +## Getting started + +Supabase provides several options for creating database functions. You can use the Dashboard or create them directly using SQL. +We provide a SQL editor within the Dashboard, or you can [connect](/docs/guides/database/connecting/connecting-to-postgres) to your database +and run the SQL queries yourself. + + +1. Go to the "SQL editor" section. +2. Click "New Query". +3. Enter the SQL to create or replace your Database function. +4. Click "Run" or cmd+enter (ctrl+enter). + + +## Simple Functions + +Let's create a basic Database Function which returns a string "hello world". + +```sql +create or replace function hello_world() -- 1 +returns text -- 2 +language sql -- 3 +as $$ -- 4 + select 'hello world'; -- 5 +$$; --6 + +``` + +
+Show/Hide Details + +At it's most basic a function has the following parts: + +1. `create or replace function hello_world()`: The function declaration, where `hello_world` is the name of the function. You can use either `create` when creating a new function or `replace` when replacing an existing function. Or you can use `create or replace` together to handle either. +2. `returns text`: The type of data that the function returns. If it returns nothing, you can `returns void`. +3. `language sql`: The language used inside the function body. This can also be a procedural language: `plpgsql`, `plv8`, `plpython`, etc. +4. `as $$`: The function wrapper. Anything enclosed inside the `$$` symbols will be part of the function body. +5. `select 'hello world';`: A simple function body. The final `select` statement inside a function body will be returned if there are no statements following it. +6. `$$;`: The closing symbols of the function wrapper. + +
+ +
+ +After the Function is created, we have several ways of "executing" the function - either directly inside the database using SQL, or with one of the client libraries. + + + + + +```sql +select hello_world(); +``` + + + + +```js +const { data, error } = await supabase + .rpc('hello_world') +``` + +Reference: [rpc()](/docs/reference/javascript/rpc) + + + + +```dart +final res = await supabase + .rpc('hello_world') + .execute(); +``` + +Reference: [rpc()](/docs/reference/dart/rpc) + + + + + + +## Returning data sets + +Database Functions can also return data sets from [Tables](/docs/guides/database/tables) or Views. + +For example, if we had a database with some Star Wars data inside: + + + + + +```sql +create table planets ( + id serial primary key, + name text +); + +insert into planets (id, name) +values + (1, 'Tattoine'), + (2, 'Alderaan'), + (3, 'Kashyyyk'); + +create table people ( + id serial primary key, + name text, + planet_id bigint references planets +); + +insert into people (id, name, planet_id) +values + (1, 'Anakin Skywalker', 1), + (2, 'Luke Skywalker', 1), + (3, 'Princess Leia', 2), + (4, 'Chewbacca', 3); +``` + + + + +

Planets

+ +| id | name | +| ---- | ---- | +| 1 | Tattoine | +| 2 | Alderaan | +| 3 | Kashyyyk | + +

People

+ +| id | name | planet_id | +| ---- | ---- | ---- | +| 1 | Anakin Skywalker | 1 | +| 2 | Luke Skywalker | 1 | +| 3 | Princess Leia | 2 | +| 4 | Chewbacca | 3 | + +
+ +
+ + +We could create a function which returns all the planets: + +```sql +create or replace function get_planets() +returns setof planets +language sql +as $$ + select * from planets; +$$; +``` + +Because this function returns a table set, we can also apply filters and selectors. For example, if we only wanted the first planet: + + + + + +```sql +select * +from get_planets() +where id = 1; +``` + + + + +```js +const { data, error } = supabase + .rpc('get_planets') + .eq('id', 1) +``` + + + + +```dart +final res = await supabase + .rpc('get_planets') + .eq('id', 1) + .execute(); +``` + + + + + + +## Passing parameters + +Let's create a Function to insert a new planet into the `planets` table and return the new ID. Note that this time we're using the `plpgsql` language. + +```sql +create or replace function add_planet(name text) +returns bigint +language plpgsql +as $$ +declare + new_row bigint; +begin + insert into planets(name) + values (add_planet.name) + returning id into new_row; + + return new_row; +end; +$$; +``` + +Once again, you can execute this function either inside your database using a `select` query, or with the client libraries: + + + + + +```sql +select * from add_planet('Jakku'); +``` + + + + +```js +const { data, error } = await supabase + .rpc('add_planet', { name: 'Jakku' }) +``` + + + + + +```dart +final res = await supabase + .rpc('add_planet', params: { 'name': 'Jakku' }) + .execute(); +``` + + + + + + +## Suggestions + +### Database Functions vs Edge Functions + +For data-intensive operations we recommend using [Database Functions](/docs/guides/database/functions), which are executed within your database +and can be called remotely using the [REST and GraphQL API](/docs/guides/database/api). + +For use-cases which require low-latency we recommend [Edge Functions](/docs/guides/functions), which are globally-distributed and can be written in Typescript. + +### Security `definer` vs `invoker` + +Postgres allows you to specify whether you want the function to be executed as the user _calling_ the function (`invoker`), or as the _creator_ of the function (`definer`). For example: + +```sql +create function hello_world() +returns text +language plpgsql +security definer set search_path = public +as $$ +begin + select 'hello world'; +end; +$$; +``` + +It is best practice to use `security invoker` (which is also the default). If you ever use `security definer`, you _must_ set the `search_path`. +This limits the potential damage if you allow access to schemas which the user executing the function should not have. + +## Resources + + +- Official Client libraries: [JavaScript](/docs/reference/javascript/rpc) and [Dart](/docs/reference/dart/rpc) +- Community client libraries: [github.com/supabase-community](https://github.com/supabase-community) +- PostgreSQL Official Docs: [Chapter 9. Functions and Operators](https://www.postgresql.org/docs/current/functions.html) +- PostgreSQL Reference: [CREATE FUNCTION](https://www.postgresql.org/docs/9.1/sql-createfunction.html) + +## Deep Dive + +### Create Database Functions + + + +### Call Database Functions using JavaScript + + + +### Using Database Functions to call an external API + + diff --git a/apps/reference/docs/guides/database/json.mdx b/apps/reference/docs/guides/database/json.mdx new file mode 100644 index 00000000000..0af74c68906 --- /dev/null +++ b/apps/reference/docs/guides/database/json.mdx @@ -0,0 +1,278 @@ +--- +id: json +title: 'JSON' +description: Using the JSON data type in PostgreSQL. +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +PostgreSQL supports [JSON functions and operators](https://www.postgresql.org/docs/current/functions-json.html) which gives flexibility when storing data inside a database column. + +PostgreSQL supports two types of JSON columns: `JSON` and `JSONB`. +The recommended type is `JSONB` for almost all cases. +When you use the `JSONB` format, the data is parsed when it's put into the database so it's faster when querying and also it can be indexed. + +## Create a table with a JSON column + + + + + +1. Go to the [Table Editor](https://app.supabase.com/project/_/editor) page in the Dashboard. +2. Click **New Table** and create a table called `books`. +3. Include a primary key with the following properties: + - Name: `id` + - Type: `int8` + - Default value: `Automatically generate as indentity` +4. Click **Save**. +5. Click **New Column** and add 3 columns with the following properties: + - **title** column + - Name: `title` + - Type: `text` + - **author** column + - Name: `author` + - Type: `text` + - **metadata** column + - Name: `metadata` + - Type: `jsonb` + + + + + +```sql +create table books ( + id serial primary key, + title text, + author text, + metadata jsonb +); +``` + + + + +## Insert data into the table + + + + + +1. Go to the [Table Editor](https://app.supabase.com/project/_/editor) page in the Dashboard. +2. Select the `books` table in the sidebar. +3. Click **+ Insert row** and add 5 rows with the following properties: + +| id | title | author | metadata | +| --- | ----------------------------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------- | +| 1 | The Poky Little Puppy | Janette Sebring Lowrey | {"ages":[3,6],"price":5.95,"description":"Puppy is slower than other, bigger animals."} | +| 2 | The Tale of Peter Rabbit | Beatrix Potter | {"ages":[2,5],"price":4.49,"description":"Rabbit eats some vegetables."} | +| 3 | Tootle | Gertrude Crampton | {"ages":[2,5],"price":3.99,"description":"Little toy train has big dreams."} | +| 4 | Green Eggs and Ham | Dr. Seuss | {"ages":[4,8],"price":7.49,"description":"Sam has changing food preferences and eats unusually colored food."} | +| 5 | Harry Potter and the Goblet of Fire | J.K. Rowling | {"ages":[10,99],"price":24.95,"description":"Fourth year of school starts, big drama ensues."} | + + + + + +```sql +insert into books + (title, author, metadata) +values + ( + 'The Poky Little Puppy', + 'Janette Sebring Lowrey', + '{"description":"Puppy is slower than other, bigger animals.","price":5.95,"ages":[3,6]}' + ), + ( + 'The Tale of Peter Rabbit', + 'Beatrix Potter', + '{"description":"Rabbit eats some vegetables.","price":4.49,"ages":[2,5]}' + ), + ( + 'Tootle', + 'Gertrude Crampton', + '{"description":"Little toy train has big dreams.","price":3.99,"ages":[2,5]}' + ), + ( + 'Green Eggs and Ham', + 'Dr. Seuss', + '{"description":"Sam has changing food preferences and eats unusually colored food.","price":7.49,"ages":[4,8]}' + ), + ( + 'Harry Potter and the Goblet of Fire', + 'J.K. Rowling', + '{"description":"Fourth year of school starts, big drama ensues.","price":24.95,"ages":[10,99]}' + ); +``` + + + + + +```js +const { data, error } = await supabase.from('books').insert([ + { + title: 'The Poky Little Puppy', + author: 'Janette Sebring Lowrey', + metadata: { + description: 'Puppy is slower than other, bigger animals.', + price: 5.95, + ages: [3, 6], + }, + }, + { + title: 'The Tale of Peter Rabbit', + author: 'Beatrix Potter', + metadata: { description: 'Rabbit eats some vegetables.', price: 4.49, ages: [2, 5] }, + }, + { + title: 'Tootle', + author: 'Gertrude Crampton', + metadata: { description: 'Little toy train has big dreams.', price: 3.99, ages: [2, 5] }, + }, + { + title: 'Green Eggs and Ham', + author: 'Dr. Seuss', + metadata: { + description: 'Sam has changing food preferences and eats unusually colored food.', + price: 7.49, + ages: [4, 8], + }, + }, + { + title: 'Harry Potter and the Goblet of Fire', + author: 'J.K. Rowling', + metadata: { + description: 'Fourth year of school starts, big drama ensues.', + price: 24.95, + ages: [10, 99], + }, + }, +]) +``` + + + + +## View the data + + + + + +```sql +select * +from books; +``` + + + + + +```js +const { data, error } = await supabase.from('books').select('*') +console.log(JSON.stringify(data, null, 2)) +``` + + + + + +| id | title | author | metadata | +| --- | ----------------------------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------- | +| 1 | The Poky Little Puppy | Janette Sebring Lowrey | {"ages":[3,6],"price":5.95,"description":"Puppy is slower than other, bigger animals."} | +| 2 | The Tale of Peter Rabbit | Beatrix Potter | {"ages":[2,5],"price":4.49,"description":"Rabbit eats some vegetables."} | +| 3 | Tootle | Gertrude Crampton | {"ages":[2,5],"price":3.99,"description":"Little toy train has big dreams."} | +| 4 | Green Eggs and Ham | Dr. Seuss | {"ages":[4,8],"price":7.49,"description":"Sam has changing food preferences and eats unusually colored food."} | +| 5 | Harry Potter and the Goblet of Fire | J.K. Rowling | {"ages":[10,99],"price":24.95,"description":"Fourth year of school starts, big drama ensues."} | + +The data as it appears here has the `JSONB` fields in a different order than when inserted. As mentioned earlier, data is parsed as its inserted when using the JSONB format. + + + + +## Query the `JSONB` data + +Select the title, description, price, and age range for each book. + + + + + +```sql +select + title, + metadata -> 'description' AS description, + metadata -> 'price' as price, + metadata -> 'ages' -> 0 as low_age, + metadata -> 'ages' -> 1 as high_age +from + books; +``` + + + + + +```js +const { data, error } = await supabase + .from('books') + .select( + 'title,description:metadata->description,price:metadata->price,low_age:metadata->ages->0,high_age:metadata->ages->1' + ) +console.log(JSON.stringify(data, null, 2)) +``` + + + + + +| title | description | price | low_age | high_age | +| ----------------------------------- | ------------------------------------------------------------------ | ----- | ------- | -------- | +| The Poky Little Puppy | Puppy is slower than other, bigger animals. | 5.95 | 3 | 6 | +| The Tale of Peter Rabbit | Rabbit eats some vegetables. | 4.49 | 2 | 5 | +| Tootle | Little toy train has big dreams. | 3.99 | 2 | 5 | +| Green Eggs and Ham | Sam has changing food preferences and eats unusually colored food. | 7.49 | 4 | 8 | +| Harry Potter and the Goblet of Fire | Fourth year of school starts, big drama ensues. | 24.95 | 10 | 99 | + + + + +Note that the `->` operator returns JSONB data. If you want TEXT/STRING data returned, use the `->>` operator. + +- metadata -> 'description' (returns a JSON object) +- metadata ->> 'description' (returns STRING/TEXT data) + +## Resources + +- [Supabase JS Client](https://github.com/supabase/supabase-js) +- [PostgreSQL: JSON Functions and Operators](https://www.postgresql.org/docs/12/functions-json.html) +- [PostgreSQL JSON types](https://www.postgresql.org/docs/12/datatype-json.html) diff --git a/apps/reference/docs/guides/database/managing-passwords.mdx b/apps/reference/docs/guides/database/managing-passwords.mdx new file mode 100644 index 00000000000..2d878632b43 --- /dev/null +++ b/apps/reference/docs/guides/database/managing-passwords.mdx @@ -0,0 +1,32 @@ +--- +id: managing-passwords +title: "Passwords" +description: How to change your PostgreSQL database password. +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +Your PostgreSQL database is the core of your Supabase project, so it's important that it has a strong, secure password at all times. + +If you use special symbols in your postgres password, you must remember to [percent-encode](https://en.wikipedia.org/wiki/Percent-encoding) your password later if using the postgres connection string e.g. `postgresql://postgres:p%3Dword@db.cvwawazfelidkloqmbma.supabase.co:5432/postgres` + + +### Changing your project password + +When you created your project you were also asked to enter a password. This is actually the password for your database, specifically for the `postgres` user. +You can update this from the Dashboard under the [database settings](https://app.supabase.com/project/_/settings/database) page. + +## Creating a secure password + +It's absolutely critical that you store your customers' data safely. Here are some tips for creating a secure password. + +- Use a password manager to generate it. +- Make a long password (12 characters at least). +- Don't use any common dictionary words. +- Use both upper and lower case characters, numbers, and special symbols. + +## Resources + +- [PostgreSQL `ALTER USER` Documentation](https://www.postgresql.org/docs/12/sql-alteruser.html) + diff --git a/apps/reference/docs/guides/database/managing-timezones.mdx b/apps/reference/docs/guides/database/managing-timezones.mdx new file mode 100644 index 00000000000..6092dd779b0 --- /dev/null +++ b/apps/reference/docs/guides/database/managing-timezones.mdx @@ -0,0 +1,85 @@ +--- +id: managing-timezones +title: "Timezones" +slug: managing-timezones +description: How to change your database timezone. +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + +Every Supabase database is set to UTC timezone by default. We strongly recommend keeping it this way, even if your users are in a different location. +This is because it makes it much easier to calculate differences between timezones if you adopt the mental model that "everything in my database is in UTC time". + + +### Change timezone + + + + + + + +```sql +alter database postgres +set timezone to 'America/New_York'; +``` + + + + + + +### Full list of timezones + +Get a full list of timezones supported by your database. This will return the following columns: + +- `name`: Time zone name +- `abbrev`: Time zone abbreviation +- `utc_offset`: Offset from UTC (positive means east of Greenwich) +- `is_dst`: True if currently observing daylight savings + + + + + + +```sql +select name, abbrev, utc_offset, is_dst +from pg_timezone_names() +order by name; +``` + + + + + + +### Search for a specific timezone + +Use `ilike` (case insensitive search) to find specific timezones. + + + + + +```sql +select * +from pg_timezone_names() +where name ilike '%york%'; +``` + + + + + \ No newline at end of file diff --git a/apps/reference/docs/guides/database/replication.mdx b/apps/reference/docs/guides/database/replication.mdx new file mode 100644 index 00000000000..1ed979fa4a2 --- /dev/null +++ b/apps/reference/docs/guides/database/replication.mdx @@ -0,0 +1,94 @@ +--- +id: replication +title: "Replication" +slug: replication +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + +Replication is a technique for copying the data from one database to another. Supabase uses replication functionality to provide a real-time API. Replication is useful for: + +- Spreading out the "load." For example, if your database has a lot of reads, you might want to split it between two databases. +- Reducing latency. For example, you may want one database in London to serve your European customers, and one in New York to serve the US. + +Replication is done through _publications_, a method of choosing which changes to send to other systems (usually another Postgres database). Publications can be managed in the [Dashboard](https://app.supabase.com) or with SQL. + +## Manage publications in the Dashboard + +1. Go to the [Database](https://app.supabase.com/project/_/database/tables) page in the Dashboard. +2. Click on **Replication** in the sidebar. +3. Control which database events are sent by toggling **Insert**, **Update**, and **Delete**. +4. Control which tables broadcast changes by selecting **Source** and toggling each table. + + + +## Create a publication + +This publication contains changes to all tables. + +```sql +create publication publication_name +for all tables; +``` + +## Create a publication to listen to individual tables + +```sql +create publication publication_name +for table table_one, table_two; +``` + +## Add tables to an existing publication + +```sql +alter publication publication_name +add table table_name; +``` + +## Listen to `insert` + +```sql +create publication publication_name +for all tables +with (publish = 'insert'); +``` + +## Listen to `update` + +```sql +create publication publication_name +for all tables +with (publish = 'update'); +``` + +## Listen to `delete` + +```sql +create publication publication_name +for all tables +with (publish = 'delete'); +``` + +## Remove a publication + +```sql +drop publication if exists publication_name; +``` + +## Recreate a publication + +If you're recreating a publication, it's best to do it in a transaction to ensure the operation succeeds. + +```sql +begin; + -- remove the realtime publication + drop publication if exists publication_name; + + -- re-create the publication but don't enable it for any tables + create publication publication_name; +commit; +``` diff --git a/apps/reference/docs/guides/database/sql-to-api.mdx b/apps/reference/docs/guides/database/sql-to-api.mdx new file mode 100644 index 00000000000..4a07440ae3a --- /dev/null +++ b/apps/reference/docs/guides/database/sql-to-api.mdx @@ -0,0 +1,83 @@ +--- +id: sql-to-api +title: 'Converting SQL to JavaScript API' +description: Implementing common SQL patterns in the JavaScript API +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + + + +Select a set of columns from a single table with where, order by, and limit clauses. + +```sql +select first_name, last_name, team_id, age from players +where age between 20 and 24 and team_id <> 'STL' +order by last_name, first_name desc +limit 20 +``` + +```js +const { data, error } = await supabase + .from('players') + .select('first_name,last_name,team_id,age') + .gte('age', 20) + .lte('age', 24) + .not('team_id', 'eq', 'STL') + .order('last_name', { ascending: true }) // or just .order('last_name') + .order('first_name', { ascending: false }) + .limit(20) +``` + +Select all columns from a single table with a complex where clause: OR AND OR + +```sql +select * from players +where ((team_id = 'CHN' or team_id is null) and (age > 35 or age is null)) +``` + +```js +const { data, error } = await supabase + .from('players') + .select() // or .select('*') + .or('team_id.eq.CHN,team_id.is.null') + .or('age.gt.35,age.is.null') // additional filters imply "AND" + .not('team_id', 'eq', 'STL') +``` + +Select all columns from a single table with a complex where clause: AND OR AND + +```sql +select * from players +where ((team_id = 'CHN' and age > 35) or (team_id <> 'CHN' and age is not null)) +``` + +```js +const { data, error } = await supabase + .from('players') + .select() // or .select('*') + .or('and(team_id.eq.CHN,age.gt.35),and(team_id.neq.CHN,.not.age.is.null)') +``` + +Get a count of rows, but don't return any data. + +```sql +select count(*) from players +where team_id = 'NYM' +``` + +```js +const { data, error } = await supabase + .from('players') + .select('*', { count: 'exact', head: true }) // exact, planned, or executed + .eq('team_id', 'NYM') +``` + +## Resources + +- [Supabase Account - Free Tier OK](https://supabase.com) +- [Postgrest Operators](https://postgrest.org/en/stable/api.html#operators) +- [Supabase API: JavaScript select](/docs/reference/javascript/select) +- [Supabase API: JavaScript modifiers](/docs/reference/javascript/using-modifiers) +- [Supabase API: JavaScript filters](/docs/reference/javascript/using-filters) diff --git a/apps/reference/docs/guides/database/tables.mdx b/apps/reference/docs/guides/database/tables.mdx new file mode 100644 index 00000000000..f04015df257 --- /dev/null +++ b/apps/reference/docs/guides/database/tables.mdx @@ -0,0 +1,514 @@ +--- +id: tables +title: Tables and Data +description: Creating and using Postgres tables. +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +Tables are where you store your data. + +Tables are similar to excel spreadsheets. They contain columns and rows. +For example, this table has 3 "columns" (`id`, `name`, `description`) and 4 "rows" of data: + +| `id` | `name` | `description` | +| ---- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1 | The Phantom Menace | Two Jedi escape a hostile blockade to find allies and come across a young boy who may bring balance to the Force. | +| 2 | Attack of the Clones | Ten years after the invasion of Naboo, the Galactic Republic is facing a Separatist movement. | +| 3 | Revenge of the Sith | As Obi-Wan pursues a new threat, Anakin acts as a double agent between the Jedi Council and Palpatine and is lured into a sinister plan to rule the galaxy. | +| 4 | Star Wars | Luke Skywalker joins forces with a Jedi Knight, a cocky pilot, a Wookiee and two droids to save the galaxy from the Empire's world-destroying battle station. | + +There are a few important differences from a spreadsheet, but it's a good starting point if you're new to Relational databases. + +## Creating Tables + +When creating a table, it's best practice to add columns at the same time. + +![Tables and columns](/img/guides/database/tables-columns.png) + +You must define the "data type" of each column when it is created. You can add and remove columns at any time after creating a table. + +Supabase provides several options for creating tables. You can use the Dashboard or create them directly using SQL. +We provide a SQL editor within the Dashboard, or you can [connect](/docs/guides/database/connecting/connecting-to-postgres) to your database +and run the SQL queries yourself. + + + + + + + +1. Go to the [Table Editor](https://app.supabase.com/project/_/editor) page in the Dashboard. +2. Click **New Table** and create a table with the name `todos`. +3. Click **Save**. +4. Click **New Column** and create a column with the name `task` and type `text`. +5. Click **Save**. + + + + +```sql +create table movies ( + id bigint generated by default as identity primary key, + name text, + description text +); +``` + + + + +:::note +When naming tables, use lowercase and underscores instead of spaces (e.g., `table_name`, not `Table Name`). +::: + +## Columns + +You must define the "data type" when you create a column. + +### Data types + +Every column is a predefined type. PostgreSQL provides many [default types](https://www.postgresql.org/docs/current/datatype.html), and you can even design your own (or use extensions) +if the default types don't fit your needs. + +
+Show/Hide default data types + +| `Name` | `Aliases` | `Description` | +| --------------------------------- | ----------- | ---------------------------------------------------------------- | +| bigint | int8 | signed eight-byte integer | +| bigserial | serial8 | autoincrementing eight-byte integer | +| bit | | fixed-length bit string | +| bit varying | varbit | variable-length bit string | +| boolean | bool | logical Boolean (true/false) | +| box | | rectangular box on a plane | +| bytea | | binary data (“byte array”) | +| character | char | fixed-length character string | +| character varying | varchar | variable-length character string | +| cidr | | IPv4 or IPv6 network address | +| circle | | circle on a plane | +| date | | calendar date (year, month, day) | +| double precision | float8 | double precision floating-point number (8 bytes) | +| inet | | IPv4 or IPv6 host address | +| integer | int, int4 | signed four-byte integer | +| interval \[ fields \] | | time span | +| json | | textual JSON data | +| jsonb | | binary JSON data, decomposed | +| line | | infinite line on a plane | +| lseg | | line segment on a plane | +| macaddr | | MAC (Media Access Control) address | +| macaddr8 | | MAC (Media Access Control) address (EUI-64 format) | +| money | | currency amount | +| numeric | decimal | exact numeric of selectable precision | +| path | | geometric path on a plane | +| pg_lsn | | PostgreSQL Log Sequence Number | +| pg_snapshot | | user-level transaction ID snapshot | +| point | | geometric point on a plane | +| polygon | | closed geometric path on a plane | +| real | float4 | single precision floating-point number (4 bytes) | +| smallint | int2 | signed two-byte integer | +| smallserial | serial2 | autoincrementing two-byte integer | +| serial | serial4 | autoincrementing four-byte integer | +| text | | variable-length character string | +| time \[ without time zone \] | | time of day (no time zone) | +| time with time zone | timetz | time of day, including time zone | +| timestamp \[ without time zone \] | | date and time (no time zone) | +| timestamp with time zone | timestamptz | date and time, including time zone | +| tsquery | | text search query | +| tsvector | | text search document | +| txid_snapshot | | user-level transaction ID snapshot (deprecated; see pg_snapshot) | +| uuid | | universally unique identifier | +| xml | | XML data | + +
+ +
+ +You can "cast" columns from one type to another, however there can be some incompatibilities between types. +For example, if you cast a `timestamp` to a `date`, you will lose all the time information that was previously saved. + +### Primary Keys + +A table can have a "primary key" - a unique identifier for every row of data. A few tips for Primary Keys: + +- It's recommended to create a Primary Key for every table in your database. +- You can use any column as a primary key, as long as it is unique for every row. +- It's common to use a `uuid` type or a numbered `identity` column as your primary key. + +```sql +create table movies ( + id bigint generated always as identity primary key +); +``` + +In the example above, we have: + +1. created a column called `id` +1. assigned the data type `bigint` +1. instructed the database that this should be `generated always as identity`, which means that Postgres will automatically assign a unique number to this column. +1. Becuase it's unique, we can also use it as our `primary key`. + +We could also use `generated by default as identity`, which would allow us to insert our own unique values. + +```sql +create table movies ( + id bigint generated by default as identity primary key +); +``` + +## Loading data + +There are several ways to load data in Supabase. You can load data directly into the database or using the [APIs](/docs/guides/api). +Use the "Bulk Loading" instructions if you are loading large data sets. + +### Basic data loading + + + + + +```sql +insert into movies + (name, description) +values + ('The Empire Strikes Back', 'After the Rebels are brutally overpowered by the Empire on the ice planet Hoth, Luke Skywalker begins Jedi training with Yoda.'), + ('Return of the Jedi', 'After a daring mission to rescue Han Solo from Jabba the Hutt, the Rebels dispatch to Endor to destroy the second Death Star.'); +``` + + + + + +```sql +const { data, error } = await supabase + .from('movies') + .insert([{ + name: 'The Empire Strikes Back', + description: 'After the Rebels are brutally overpowered by the Empire on the ice planet Hoth, Luke Skywalker begins Jedi training with Yoda.' + }, { + name: 'Return of the Jedi', + description: 'After a daring mission to rescue Han Solo from Jabba the Hutt, the Rebels dispatch to Endor to destroy the second Death Star.' + }]) +``` + + + + + +```sql +final res = await supabase + .from('movies') + .insert([{ + name: 'The Empire Strikes Back', + description: 'After the Rebels are brutally overpowered by the Empire on the ice planet Hoth, Luke Skywalker begins Jedi training with Yoda.' + }, { + name: 'Return of the Jedi', + description: 'After a daring mission to rescue Han Solo from Jabba the Hutt, the Rebels dispatch to Endor to destroy the second Death Star.' + }]).execute(); +``` + + + + +### Bulk data loading + +When inserting large data sets it's best to use PostgreSQL's [COPY](https://www.postgresql.org/docs/current/sql-copy.html) command. +This loads data directly from a file into a table. There are several file formats available for copying data: text, csv, binary, JSON, etc. + +For example, if you wanted to load a CSV file into your movies table: + +```csv title="./movies.csv" +"The Empire Strikes Back", "After the Rebels are brutally overpowered by the Empire on the ice planet Hoth, Luke Skywalker begins Jedi training with Yoda." +"Return of the Jedi", "After a daring mission to rescue Han Solo from Jabba the Hutt, the Rebels dispatch to Endor to destroy the second Death Star." +``` + +You would [connect](/docs/guides/database/connecting-to-postgres#direct-connections) to your database directly and load the file with the COPY command: + +```bash +psql -h DATABASE_URL -p 5432 postgres -U postgres \ + -c "COPY movies FROM './movies.csv';" +``` + +## Joining tables with Foreign Keys + +Tables can be "joined" together using Foreign Keys. + +![Foreign Keys](/img/guides/database/foreign-keys.png) + +This is where the "Relational" naming comes from, as data typically forms some sort of relationship. + +In our "movies" example above, we might want to add a "category" for each movie (for example, "Action", or "Documentary"). +Let's create a new table called `categories` and "link" our `movies` table. + +```sql +create table categories ( + id bigint generated always as identity primary key, + name text -- category name +); + +alter table movies + add column category_id bigint references categories; +``` + +You can also create "many-to-many" relationships by creating a "join" table. +For example if you had the following situations: + +- You have a list of `movies`. +- A movie can have several `actors`. +- An `actor` can perfom in several movies. + + + + + + + + + + + +```sql +create table movies ( + id bigint generated by default as identity primary key, + name text, + description text +); + +create table actors ( + id bigint generated by default as identity primary key, + name text +); + +create table performances ( + id bigint generated by default as identity primary key, + movie_id bigint not null references movies, + actor_id bigint not null references actors +); +``` + + + + +## Schemas + +Tables belong to `schemas`. Schemas are a way of organizing your tables, often for security reasons. + +![Schemas and tables](/img/guides/database/schema-tables.png) + +If you don't explicitly pass a schema when creating a table, Postgres will assume that you want to create the table in the `public` schema. + +We can create schemas for organizing tables. For example, we might want a private schema which is hidden from our API: + +```sql +create schema private; +``` + +Now we can create tables inside the `private` schema: + +```sql +create table salaries ( + id bigint generated by default as identity primary key, + salary bigint not null, + actor_id bigint not null references public.actors +); +``` + +## Views + +A View is a convenient shortcut to a query. Creating a view does not involve new tables or data. When run, an underlying query is executed, returning its results to the user. + +:::caution + +By default, PostgreSQL views bypass Row Level Security unless you change their owner (see https://github.com/supabase/supabase/discussions/901). PostgreSQL v15 (coming soon) will have a more intuitive control for this through [security invoker views](https://www.depesz.com/2022/03/22/waiting-for-postgresql-15-add-support-for-security-invoker-views/) and the previous step won't be needed. + +::: + +Say we have the following tables from a database of a university: + +**`students`** + +| id | name | type | +| --- | ---------------- | ------------- | +| 1 | Princess Leia | undergraduate | +| 2 | Yoda | graduate | +| 3 | Anakin Skywalker | graduate | + +**`courses`** + +| id | title | code | +| --- | ------------------------ | ------- | +| 1 | Introduction to Postgres | PG101 | +| 2 | Authentication Theories | AUTH205 | +| 3 | Fundamentals of Supabase | SUP412 | + +**`grades`** + +| id | student_id | course_id | result | +| --- | ---------- | --------- | ------ | +| 1 | 1 | 1 | B+ | +| 2 | 1 | 3 | A+ | +| 3 | 2 | 2 | A | +| 4 | 3 | 1 | A- | +| 5 | 3 | 2 | A | +| 6 | 3 | 3 | B- | + +Creating a view consisting of all the three tables will look like this: + +```sql +create view transcripts as + select + students.name, + students.type, + courses.title, + courses.code, + grades.result + from grades + left join students on grades.student_id = students.id + left join courses on grades.course_id = courses.id; + +alter view transcripts owner to authenticated; +``` + +Once done, we can now access the underlying query with: + +```sql +select * from transcripts; +``` + +### When to use views + +Views provide the several benefits: + +- Simplicity +- Consistency +- Logical Organization +- Security + +#### Simplicity + +As a query becomes complex it becomes a hassle to call it. Especially when we run it at regularly. In the example above, instead of repeatedly running: + +```sql +select + students.name, + students.type, + courses.title, + courses.code, + grades.result +from grades +left join students on grades.student_id = students.id +left join courses on grades.course_id = courses.id; +``` + +We can run this instead: + +```sql +select * from transcripts; +``` + +Additionally, a view behaves like a typical table. We can safely use it in table `JOIN`s or even create new views using existing views. + +#### Consistency + +Views ensure that the likelihood of mistakes decreases when repeatedly executing a query. In our example above, we may decide that we want to exclude the course _Introduction to Postgres_. The query would become: + +```sql +select + students.name, + students.type, + courses.title, + courses.code, + grades.result +from grades + left join students on grades.student_id = students.id + left join courses on grades.course_id = courses.id +where courses.code != 'PG101'; +``` + +Without a view, we would need to go into every dependent query to add the new rule. This would increase in the likelihood of errors and inconsistencies, as well as introducing a lot of effort for a developer. With views, we can alter just the underlying query in the view **transcripts**. The change will be applied to all applications using this view. + +#### Logical Organization + +With views, we can give our query a name. This is extremely useful for teams working with the same database. Instead of guessing what a query is supposed to do, a well-named view can easily explain it. For example, by looking at the name of the view **transcripts**, we can infer that the underlying query might involve the **students**, **courses**, and **grades** tables. + +#### Security + +Views can restrict the amount and type of data presented to a user. Instead of allowing a user direct access to a set of tables, we provide them a view instead. We can prevent them from reading sensitive columns by excluding them from the underlying query. + +### Materialized Views + +A [materialized view](https://www.postgresql.org/docs/12/rules-materializedviews.html) is a form of view but it also stores the results to disk. In subsequent reads of a materialized view, the time taken to return its results would be much faster than a conventional view. This is because the data is readily available for a materialized view while the conventional view executes the underlying query each time it is called. + +Using our example above, a materialized view can be created like this: + +```sql +create materialized view transcripts as + select + students.name, + students.type, + courses.title, + courses.code, + grades.result + from grades + left join students on grades.student_id = students.id + left join courses on grades.course_id = courses.id; +``` + +Reading from the materialized view is the same as a conventional view: + +```sql +select * from transcripts; +``` + +### Refreshing materialized views + +Unfortunately, there is a trade-off - data in materialized views are not always up to date. We need to refresh it regularly to prevent the data from becoming too stale. To do so: + +```sql +refresh materialized view transcripts; +``` + +It's up to you how regularly refresh your materialized views, and it's probably different for each view depending on its use-case. + +### Materialized views vs Conventional views + +Materialized views are useful when execution times for queries or views are too slow. These could likely occur in views or queries involving multiple tables and billions of rows. When using such a view, however, there should be tolerance towards data being outdated. Some use-cases for materialized views are internal dashboards and analytics. + +Creating a materialized view is not a solution to inefficient queries. You should always seek to optimize a slow running query even if you are implementing a materialized view. + +## Resources + +- [Official Docs: Create table](https://www.postgresql.org/docs/current/sql-createtable.html) +- [Official Docs: Create view](https://www.postgresql.org/docs/12/sql-createview.html) +- [PostgreSQL Tutorial: Create tables](https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-create-table/) +- [PostgreSQL Tutorial: Add column](https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-add-column/) +- [PostgreSQL Tutorial: Views](https://www.postgresqltutorial.com/postgresql-views/) diff --git a/apps/reference/docs/guides/database/timeouts.mdx b/apps/reference/docs/guides/database/timeouts.mdx new file mode 100644 index 00000000000..2436c5dc0db --- /dev/null +++ b/apps/reference/docs/guides/database/timeouts.mdx @@ -0,0 +1,27 @@ +--- +id: timeouts +title: Timeouts +description: Timeouts and optimization +--- + +By default, Supabase limits the maximum statement execution time to _3 seconds_ for users accessing the API using the anon key, and _8 seconds_ for authenticated users. Additionally, all users are subject to a global limit of _2 minutes_. This serves as a backstop against resource exhaustion due to either poorly written queries, or abusive usage. + +### Changing the default timeout + +The timeout values were picked as a reasonable default for the majority of use-cases, but can be modified using the [`alter role`](https://www.postgresql.org/docs/current/sql-alterrole.html) statement: + +```sql +alter role authenticated set statement_timeout = '15s'; +``` + +You can also update the statement timeout for a session: + +```sql +set statement_timeout to 60000; -- 1 minute in milliseconds +``` + +### Statement Optimization + +All Supabase projects come with the [`pg_stat_statements`](https://www.postgresql.org/docs/current/pgstatstatements.html) extension installed, which tracks planning and execution statistics for all statements executed against it. These statistics can be used in order to diagnose the performance of your project. + +This data can further be used in conjunction with the [`explain`](https://www.postgresql.org/docs/current/using-explain.html) functionality of Postgres to optimize your usage. diff --git a/apps/reference/docs/guides/examples.mdx b/apps/reference/docs/guides/examples.mdx new file mode 100644 index 00000000000..70035bdfdb3 --- /dev/null +++ b/apps/reference/docs/guides/examples.mdx @@ -0,0 +1,159 @@ +--- +id: examples +title: Examples and Resources +description: 'Examples you can use to get started with Supabase' +--- + +We have a [set of examples](https://github.com/supabase/supabase/tree/master/examples) in our [main repository](https://github.com/supabase/supabase) to help you get started. + +## Featured + + +### Supabase Crash Course + +By [Traversy Media](https://www.youtube.com/watch?v=7uKQBl9uZ00). + + + +### Build an App With Supabase and NextJS + +By [@jlengstorf](https://twitter.com/jlengstorf) and [@jonmeyers_io](https://twitter.com/jonmeyers_io). + + + + +### Is Supabase Legit + +By [Fireship](https://www.youtube.com/watch?v=WiwfiVdfRIc). + + + +## Official Examples + +### Todo List + +Build a basic Todo List with Supabase and your favorite frontend framework: + +- [Expo Todo List.](https://github.com/supabase/supabase/tree/master/examples/todo-list/expo-todo-list) +- [Next.js Todo List.](https://github.com/supabase/supabase/tree/master/examples/todo-list/nextjs-todo-list) +- [React Todo List.](https://github.com/supabase/supabase/tree/master/examples/todo-list/react-todo-list) +- [Svelte Todo List.](https://github.com/supabase/supabase/tree/master/examples/todo-list/sveltejs-todo-list) +- [Vue 3 Todo List (Typescript).](https://github.com/supabase/supabase/tree/master/examples/todo-list/vue3-ts-todo-list) +- [Angular Todo List.](https://github.com/supabase/supabase/tree/master/examples/todo-list/angular-todo-list) +- [Nuxt 3 Todo List.](https://github.com/nuxt-community/supabase-module/tree/main/demo) + +### Auth examples + +- [Supabase Auth with vanilla JavaScript.](https://github.com/supabase/supabase/tree/master/examples/auth/javascript-auth). Use Supabase without any frontend frameworks. +- [Supabase Auth with Next.js SSR.](https://github.com/supabase/supabase/tree/master/examples/nextjs-with-supabase-auth) Uses cookies to persist auth between the server and the client. +- [Supabase Auth with RedwoodJS.](https://redwood-playground-auth.netlify.app/supabase) Try out Supabase authentication in the [RedwoodJS](https://redwoodjs.com) Authentication Playground complete with OAuth support and code samples. + +### Collaborative + +- [Next.js Slack Clone.](https://github.com/supabase/supabase/tree/master/examples/slack-clone/nextjs-slack-clone) + +## Community + +### Courses + +- Build a FullStack App with Next.js, Supabase & Prisma by [@gdangel0](https://twitter.com/gdangel0): [Free course](https://themodern.dev/courses/build-a-fullstack-app-with-nextjs-supabase-and-prisma-322389284337222224) + +### Libraries + +- D (in development): [GitHub](https://github.com/csharpdf/dupabase) +- Dart (in development): [GitHub](https://github.com/supabase/supabase-dart) +- Python (in development): [GitHub](https://github.com/supabase/supabase-py) +- C# (in development): [GitHub](https://github.com/supabase/supabase-csharp) +- Kotlin (in development): [GitHub](https://github.com/supabase-community/postgrest-kt) +- `useSupabase`: Supabase React Hooks. [GitHub](https://github.com/gbibeaul/use-supabase) +- `vue-supabase`: Supabase Vue wrapper. [GitHub](https://github.com/supabase/vue-supabase) +- `vue-3-supabase`: Supabase Vue 3 wrapper. [GitHub](https://github.com/DidoMarchet/vue-3-supabase) +- `nuxt-supabase`: Supabase Nuxt wrapper. [GitHub](https://github.com/supabase/nuxt-supabase) +- `@nuxtjs/supabase`: Supabase Nuxt 3 module. [GitHub](https://github.com/nuxt-community/supabase-module) +- `react-supabase`: Supabase React Hooks. [Docs](https://react-supabase.vercel.app) [GitHub](https://github.com/tmm/react-supabase) +- ` @triniwiz/nativescript-supabase`: Supabase NativeScript. [GitHub](https://github.com/triniwiz/nativescript-plugins/tree/master/packages/nativescript-supabase) + +### Guides + +- Supabase Auth with Redwood. [Docs](https://redwoodjs.com/tutorial/authentication) +- Supabase Auth with Sapper SSR. [Blog](https://dev.to/jakobbouchard/how-to-setup-supabase-auth-with-sapper-ssr-13od) +- Switch from Firebase Auth to Supabase Auth. [Blog](https://msyyn.medium.com/switch-from-firebase-auth-to-supabase-auth-the-open-source-firebase-alternative-509746952b1b) +- Setting up Umami Analytics with Supabase. [Blog](https://dev.to/jakobbouchard/setting-up-umami-with-vercel-and-supabase-3a73) +- Creating New Supabase Users In NextJS. [Blog](https://www.aboutmonica.com/blog/creating-new-supabase-users-in-next-js) +- Creating Protected Routes In NextJS With Supabase. [Blog](https://www.aboutmonica.com/blog/creating-protected-routes-in-next-js-with-supabase) +- Migrate from Google Cloud Storage (GCS) to Supabase Storage [Gist](https://gist.github.com/danalloway/86f79efd5ca336ff7364554ac3104014) +- Subscriptions with Supabase and Stripe Billing [Blog](https://www.sandromaglione.com/2021/04/29/supabase-auth-create-stripe-customer-subscription-supabase-stripe-billing-part-1/) +- Flutter Supabase Authentication [Blog](https://www.sandromaglione.com/2021/04/24/flutter-supabase-authentication/) +- Supabase in 6 minutes [Video](https://www.youtube.com/watch?v=c8DNV9yl0mg) +- Let's build SupaAuth - Build an Authentication System using Supabase, Next.js and Typescript [6-part Blog Series](https://aalam.in/blog/supabase-auth-intro-setup-next) +- In-depth self-hosting guide using Nginx [Blog](https://dev.to/chronsyn/self-hosting-with-supabase-1aii) +- Build an Email and Social Auth for Next JS with Supabase, Tailwind CSS 3.0 and TypeScript [Blog](https://creativedesignsguru.com/next-js-supabase-auth/) +- Link Shortener using Supabase and Ory [3-part Blog Series](https://www.ory.sh/tutorial-url-shortener-supabase-ory-integration-backend/) + +### Example apps + +- Supabase + Stripe + Next.js. [GitHub](https://github.com/vercel/nextjs-subscription-payments) +- Supabase + Svelte Trello clone. [GitHub](https://github.com/joshnuss/supabase-kanban) +- Supabase + Expo Starter. [GitHub](https://github.com/codingki/react-native-expo-template/tree/master/template-typescript-bottom-tabs-supabase-auth-flow) +- Supabase + Nest.js. [GitHub](https://github.com/hiro1107/nestjs-supabase-auth) +- Supabase + Cloudflare Workers. [GitHub](https://github.com/supabase/supabase/tree/master/examples/with-cloudflare-workers) +- Supabase + Cloudflare Workers + Webpack. [GitHub](https://github.com/signalnerve/supabase-workers-proxy) +- Realtime chat app with Supabase + React. [GitHub](https://github.com/shwosner/realtime-chat-supabase-react) +- Repository.surf: GitHub insights dashboard. [GitHub](https://github.com/supabase/repository.surf) +- Supabase + React Native Instagram Clone. [GitHub](https://github.com/NiketanG/instaclone) +- KeepLink: Simple bookmark service with tags and archive. [GitHub](https://github.com/fengkx/keeplink) +- Supabase + Next.js (Next.js Starter Kit) [GitHub](https://github.com/one-aalam/next-starter-kit/tree/auth-supabase) +- Supabase + Svelte (Svelte Starter Kit) [GitHub](https://github.com/one-aalam/svelte-starter-kit) +- Supabase + SolidJS (SolidJS Starter Kit) [GitHub](https://github.com/one-aalam/solid-starter-kit) +- Supabase + Nuxt3 (Nuxt Starter Kit) [GitHub](https://github.com/one-aalam/nuxt-starter-kit) +- Supabase + Remix (Remix Starter Kit) [GitHub](https://github.com/one-aalam/remix-starter-kit) +- Supabase + Angular (Angular Starter Kit) [GitHub](https://github.com/one-aalam/ng-starter-kit) +- Supabase + Nuxt3 + nuxtjs/supabase [Github](https://github.com/nuxt-community/supabase-module/tree/main/demo) +- Supabase + Ory Kratos & Ory Oathkeeper [Github](https://github.com/ory/examples/tree/master/kratos-keto-oathkeeper-supabase) +- Supabase + Ory Cloud [Github](https://github.com/ory/examples/tree/master/supabase-ory-cloud) + +### Blog Posts + +- Realtime Subscriptions using Vue + Supabase. [Blog](https://dev.to/ftonato/realtime-subscriptions-using-vue-supabase-1e11) +- Creating a microblog using Vue + Supabase. [Blog](https://dev.to/ftonato/creating-a-microblog-using-vue-supabase-31p) +- Track Real-time Page Views. [Blog](https://codebycorey.com/blog/page-views-nextjs-supabase) +- Supabase as a Sentry alternative. [Blog](http://kopi.cloud/blog/2021/sentry-supabase/) +- Using Supabase with Chartbrew. [Blog](https://chartbrew.com/blog/how-to-visualize-your-supabase-data-with-chartbrew/) +- Authentication with Supabase and React. [Blog](https://hyperfoo.io/posts/supabase-authentication-react) +- Supabase Schema Visualizer. [Blog](https://dev.to/zernonia/supabase-schema-visualizer-no-installation-login-49kg) +- Create a real-time UI using Next.js + Supabase. [Blog](https://pablopunk.com/posts/how-to-create-a-real-time-ui-with-nextjs-and-supabase) +- How to add Twitter auth quickly with Supabase to your Next.js site ⚡ [Blog](https://blog.avneesh.tech/how-to-add-twitter-auth-quickly-with-supabase-to-your-nextjs-site) +- Under the hood: Architecture and Technology Stack of Supabase ⚡ [Blog](https://www.workingsoftware.dev/tech-stack-and-architecture-of-supabase/) + +### Podcasts + +- [Software Engineering Daily](https://softwareengineeringdaily.com/2020/10/15/supabase-open-source-firebase-with-paul-copplestone/) +- [Heavy Bit](https://www.heavybit.com/library/podcasts/jamstack-radio/ep-71-open-source-firebase-alternative-with-paul-copplestone-of-supabase/) +- [Log Rocket](https://podrocket.logrocket.com/9) +- [FS Jam](https://fsjam.org/episodes/episode-33-supabase-with-paul-copplestone) + + diff --git a/apps/reference/docs/guides/functions.mdx b/apps/reference/docs/guides/functions.mdx new file mode 100644 index 00000000000..c2294657e3b --- /dev/null +++ b/apps/reference/docs/guides/functions.mdx @@ -0,0 +1,296 @@ +--- +id: functions +title: Edge Functions +description: 'Globally distributed Typescript functions.' +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' +const examples = [ + { + name: 'With supabase-js', + description: 'Use the Supabase client inside your Edge Function.', + href: 'https://github.com/supabase/supabase/tree/master/examples/edge-functions', + }, + { + name: 'With CORS headers', + description: 'Send CORS headers for invoking from the browser.', + href: 'https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions/browser-with-cors/index.ts', + }, + { + name: 'React Native with Stripe', + description: 'Full example for using Supabase and Stripe, with Expo.', + href: 'https://github.com/supabase-community/expo-stripe-payments-with-supabase-functions', + }, + { + name: 'Flutter with Stripe', + description: 'Full example for using Supabase and Stripe, with Flutter.', + href: 'https://github.com/supabase-community/flutter-stripe-payments-with-supabase-functions', + }, +] + +Edge Functions are server-side Typescript functions, distributed globally at the edge - close to your users. They can be used for listening to webhooks or integrating your Supabase project with third-parties, like Stripe. + +Edge Functions are developed using [Deno](https://deno.com), which offers a few benefits to you as a developer: + +- It is open source. +- It is portable. Supabase Edge Functions run locally, and on any other Deno-compatible platform (including self-hosted infrastructure). +- It is Typescript first and supports WASM. +- Edge Functions are globally distributed for low-latency. + +## Quickstart + +Learn how to develop Edge Functions in less than 7 minutes: + + + +## Prerequisites + +Follow the steps to prepare your Supabase project on your local machine. + +- Install the Supabase CLI. [Docs](/docs/reference/cli/installing-and-updating). +- Login to the CLI using the command: `supabase login`. [Docs](/docs/reference/cli/supabase-login). +- Initialize Supabase inside your project using the command: `supabase init`. [Docs](/docs/guides/local-development#getting-started). +- Link to your Remote Project using the command `supabase link --project-ref your-project-ref`. [Docs](/docs/reference/cli/supabase-link). +- Optional: Setup your environment: Follow [this setup guide](https://deno.land/manual/getting_started/setup_your_environment) to integrate the Deno language server with your editor. + +## Getting Started + +Let's build an Edge Function locally, then deploy it to the Supabase Platform. + +### Creating a function + +Let's create a new Edge Function called `hello-world` inside your project: + +```bash +supabase functions new hello-world +``` + +This creates a function stub in your `supabase` folder at `./functions/hello-world/index.ts`. + +### Deploy to production + +```bash +supabase functions deploy hello-world +``` + +This command bundles your Edge Function from `./functions/hello-world/index.ts` and deploys it to the Supabase platform. +The command outputs a URL to the Supabase Dashboard which you can open to find view more details. Let's open the link to find the execution command. + +:::note + +By default Edge Functions require a valid JWT to be send in the authorization header. This header is automatically set when invoking your function via a Supabase client library. + +If you want to use Edge Functions to handle webhooks (e.g. [Stripe payment webhooks](https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions/stripe-webhooks), or [chat bot webhooks](https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions/telegram-bot) etc.), you need to pass the `--no-verify-jwt` flag when deploying your function. + +::: + +### Executing Remote Functions + +You can execute Edge Functions using curl. Copy the curl command from the Dashboard. It should look like this: + +```bash +curl --request POST 'https://.functions.supabase.co/hello-world' \ + --header 'Authorization: Bearer ANON_KEY' \ + --header 'Content-Type: application/json' \ + --data '{ "name":"Functions" }' +``` + +If you receive an error `Invalid JWT`, find the `ANON_KEY` of your project in the Dashboard under `Settings > API`. + +After invoking your Edge Function you should see the response `{ "message":"Hello Functions!" }`. + +## Debugging your Functions + +You can debug your deployed Edge Functions using the "Functions" section of the Dashboard. There are two types debugging tools available: + +- Invocations: shows the Request and Response for each execution. +- Logs: shows any platform events, including deployments and errors. + +![Function invocations.](/img/guides/functions/function-logs.png) + +## Developing locally + +You can run your Edge Function locally using [`supabase functions serve`](/docs/reference/cli/supabase-functions-serve): + +```bash +supabase start # start the supabase stack +supabase functions serve hello-world # start the Function watcher +``` + +The `functions serve` command has hot-reloading capabilities. It will watch for any changes to your files and restart the Deno server. + +### Invoking Functions locally + +While serving your local Function, you can execute it using curl: + +```bash +curl --request POST 'http://localhost:54321/functions/v1/hello-world' \ + --header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24ifQ.625_WdcF3KHqz5amU0x2X5WWHP-OEs_4qj0ssLNHzTs' \ + --header 'Content-Type: application/json' \ + --data '{ "name":"Functions" }' +``` + +You should see the response `{ "message":"Hello Functions!" }`. + +
+Implementation details + +- All Edge Functions are `POST` requests. +- The `Authorization` header is required. You can use either the `ANON` key, the `SERVICE_ROLE` key, or a logged-in user's JWT. +- The Function is proxied through the local API (`http://localhost:54321`) + +
+
+ +If you execute Function with a different payload the response will change.
+Modify the `--data '{"name":"Functions"}'` line to `--data '{"name":"World"}'` and try invoking the command again! + +## Secrets and Environment Variables + +It's common that you will need to use sensitive information or environment-specific variables inside your Edge Functions. You can access these using Deno's built-in handler + +```js +Deno.env.get(MY_SECRET_NAME) +``` + +### Default secrets + +By default, Edge Functions have access to these secrets: + +- `SUPABASE_URL`: The API gateway for your Supabase project. +- `SUPABASE_ANON_KEY`: The `anon` key for your Supabase API. This is safe to use in a browser when you have [Row Level Security](/docs/guides/auth/row-level-security) enabled. +- `SUPABASE_SERVICE_ROLE_KEY`: The `service_role` key for your Supabase API. This is safe to use in Edge Functions, but it should NEVER be used in a browser. This key will bypass [Row Level Security](/docs/guides/auth/row-level-security). +- `SUPABASE_DB_URL`: The URL for your [PostgreSQL database](/docs/guides/database). You can use this to connect directly to your database. + +### Local secrets + +Let's create a local file for storing our secrets, and inside it we can store a secret `MY_NAME`: + +```jsx +echo "MY_NAME=Yoda" >> ./supabase/.env.local +``` + +This creates a new file `./supabase/.env.local` for storing your local development secrets. + +:::caution + +Never check your .env files into Git! + +::: + +Now let's access this environment variable `MY_NAME` inside our Function. Anywhere in your function, add this line: + +```jsx +console.log(Deno.env.get('MY_NAME')) +``` + +Now we can invoke our function locally, by serving it with our new `.env.local` file: + +```bash +supabase functions serve hello-world --env-file ./supabase/.env.local +``` + +When the function starts you should see the name “Yoda” output to the terminal. + +### Production secrets + +Let's create a `.env` for production. In this case we'll just use the same as our local secrets: + +```bash +cp ./supabase/.env.local ./supabase/.env +``` + +This creates a new file `./supabase/.env` for storing your production secrets. + +:::caution + +Never check your `.env` files into Git! + +::: + +Let's push all the secrets from the `.env` file to our remote project using [`supabase secrets set`](/docs/reference/cli/supabase-secrets-set): + +```bash +supabase secrets set --env-file ./supabase/.env + +# You can also set secrets individually using: +supabase secrets set MY_NAME=Chewbacca +``` + +You don't need to re-deploy after setting your secrets. + +To see all the secrets which you have set remotely, use [`supabase secrets list`](/docs/reference/cli/supabase-secrets-list): + +```bash +supabase secrets list +``` + +## Examples + +You can find a list of useful [Edge Function Examples](https://github.com/supabase/supabase/tree/master/examples/edge-functions) in our GitHub repository. + +
+
+ {examples.map((x) => ( + + ))} +
+
+ +## Suggestions + +### Database Functions vs Edge Functions + +For data-intensive operations we recommend using [Database Functions](/docs/guides/database/functions), which are executed within your database +and can be called remotely using the [REST and GraphQL API](/docs/guides/api). + +For use-cases which require low-latency we recommend [Edge Functions](/docs/guides/functions), which are globally-distributed and can be written in Typescript. + + +### Organizing your Edge Functions + +We recommend developing “fat functions”. This means that you should develop few large functions, rather than many small functions. One common pattern when developing Functions is that you need to share code between two or more Functions. To do this, you can store any shared code in a folder prefixed with an underscore (`_`). We recommend this folder structure: + +```bash +└── supabase + ├── functions + │ ├── _shared + │ | ├── supabaseAdmin.ts # Supabase client with SERVICE_ROLE key + │ │ └── supabaseClient.ts # Supabase client with ANON key + │ ├── function-one # use hyphens to name functions + │ │ └── index.ts + │ └── function-two + │ └── index.ts + ├── migrations + └── config.toml +``` + +### Naming Edge Functions + +We recommend using hyphens to name functions because hyphens are the most URL-friendly of all the naming conventions (snake_case, camelCase, PascalCase). + +## Limitations + +- Deno Deploy limitations + - Deno does not support outgoing connections to ports `25`, `465`, and `587`. + - Cannot write to File System +- Edge Functions + - Local development - only one function at a time + - Supabase Functions only supports `POST` requests. + - Supabase Functions do not support HTML responses. diff --git a/apps/reference/docs/guides/hosting/docker.mdx b/apps/reference/docs/guides/hosting/docker.mdx new file mode 100644 index 00000000000..798d5e02999 --- /dev/null +++ b/apps/reference/docs/guides/hosting/docker.mdx @@ -0,0 +1,113 @@ +--- +id: docker +title: Self-hosting with Docker +description: How to configure and deploy Supabase. +sidebar_label: Docker +--- + +Docker is the easiest way to get started with self-hosted Supabase. + +## Before you begin + +You need the following installed in your system: + +- [Docker](https://docs.docker.com/engine/install/) and [docker-compose](https://docs.docker.com/compose/install/) +- [Git](https://git-scm.com/downloads) + +## Quick Start + +### Get the code + +Checkout the docker directory in the Supabase repo: + +```sh +# Get the code +git clone --depth 1 https://github.com/supabase/supabase + +# Go to the docker folder +cd supabase/docker + +# Copy the fake env vars +cp .env.example .env + +# Start +docker-compose up +``` + +Now visit [http://localhost:3000](http://localhost:3000) to start using Supabase Studio. + + +## Securing your setup + +While we provided you with some example secrets for getting started, you should NEVER deploy your Supabase setup using the defaults we have provided. + +Please follow these steps to secure your Docker setup. We [strongly recommend](/docs/guides/hosting/overview#managing-your-secrets) using a secrets manager when deploying to production. + +### Generate API Keys + +Use your `JWT_SECRET` to generate a `anon` and `service` API keys using the [JWT generator](/docs/guides/hosting/overview#api-keys). + +Replace the values in these files: + +- `.env`: + - `ANON_KEY` - replace with an `anon` key + - `SERVICE_ROLE_KEY` - replace with a `service` key +- `volumes/api/kong.yml` + - `anon` - replace with an `anon` key + - `service_role` - replace with a `service` key + +### Update Secrets + +Update the `.env` file with your own secrets. In particular, these are required: + +- `POSTGRES_PASSWORD`: the password for the `postgres` role. +- `JWT_SECRET`: used by PostgREST and GoTrue, among others. +- `SITE_URL`: the base URL of your site. +- `SMTP_*`: mail server credentials. You can use any SMTP server. + + +### Securing the Dashboard + +The Docker setup doesn't include a management database for managing users and logins. If you plan to deploy the Studio to the web we suggest you put it behind a web proxy with Basic Auth or hide it behind a VPN. + +## Configuration + +Each system can be [configured](/docs/guides/hosting/overview#configuration) to suit your particular use-case. + +To keep the setup simple, we made some choices that may not be optimal for production: + +- the database is in the same machine as the servers +- Storage uses the filesystem backend instead of S3 +- Auth should be configured with a production-ready SMTP server + +### Using an external database + +We strongly [recommend](/docs/guides/hosting/overview#managing-your-database) that you decouple your database from `docker-compose` before deploying. +The middleware will run with any PostgreSQL database that has logical replication enabled. The following environment variables should be updated +in the `.env` file to point to your external database: + +```env title=".env" +POSTGRES_PASSWORD=your-super-secret-and-long-postgres-password + +POSTGRES_HOST=db +POSTGRES_DB=postgres +POSTGRES_USER=postgres +POSTGRES_PORT=5432 +``` + +Once you have done this, you can safely comment out the `db` section of the `docker-compose` file, and remove any instances where the services `depends_on` the `db` image. + + +## Deploying + +See the following guides to deploy Docker Compose setup using your preferred tool and platform: + +- [Docker Swarm](https://docs.docker.com/engine/swarm/stack-deploy/) +- [AWS Fargate](https://aws.amazon.com/blogs/containers/deploy-applications-on-amazon-ecs-using-docker-compose/) +- [Using Kompose for Kubernetes](https://kubernetes.io/docs/tasks/configure-pod-container/translate-compose-kubernetes/) + + +## Next steps + +- Got a question? [Ask here](https://github.com/supabase/supabase/discussions). +- Sign in: [app.supabase.com](https://app.supabase.com) diff --git a/apps/reference/docs/guides/hosting/overview.mdx b/apps/reference/docs/guides/hosting/overview.mdx new file mode 100644 index 00000000000..db903c65d9c --- /dev/null +++ b/apps/reference/docs/guides/hosting/overview.mdx @@ -0,0 +1,158 @@ +--- +id: overview +title: Self Hosting +sidebar_label: Overview +description: Getting started with Self Hosting. +--- + +import JwtGenerator from '@site/src/components/JwtGenerator' + +There are several ways to use Supabase: + +- [Supabase Cloud](https://app.supabase.com): you don't need to deploy anything. We will manage and scale your infrastructure. +- [Docker](/docs/guides/hosting/docker): deploy to your own infrastructure. +- Kubernetes: coming soon. + +## Architecture + +Supabase is a combination of open source tools, each specifically chosen for Enterprise-readiness. + +If the tools and communities already exist, with an MIT, Apache 2, or equivalent open license, we will use and support that tool. +If the tool doesn't exist, we build and open source it ourselves. + +![Supabase Architecture](/img/supabase-architecture.png) + +- [Kong](https://github.com/Kong/kong) is a cloud-native API gateway. +- [GoTrue](https://github.com/netlify/gotrue) is an SWT based API for managing users and issuing SWT tokens. +- [PostgREST](http://postgrest.org/) is a web server that turns your PostgreSQL database directly into a RESTful API +- [Realtime](https://github.com/supabase/realtime) is an Elixir server that allows you to listen to PostgreSQL inserts, updates, and deletes using websockets. Realtime polls Postgres' built-in replication functionality for database changes, converts changes to JSON, then broadcasts the JSON over websockets to authorized clients. +- [Storage](https://github.com/supabase/storage-api) provides a RESTful interface for managing Files stored in S3, using Postgres to manage permissions. +- [postgres-meta](https://github.com/supabase/postgres-meta) is a RESTful API for managing your Postgres, allowing you to fetch tables, add roles, and run queries, etc. +- [PostgreSQL](https://www.postgresql.org/) is an object-relational database system with over 30 years of active development that has earned it a strong reputation for reliability, feature robustness, and performance. + + + + + +## Configuration + +Each system has a number of configuration options which can be found in the relevant product documentation. + +- [Postgres](https://hub.docker.com/_/postgres/) +- [PostgREST](https://postgrest.org/en/stable/configuration.html) +- [Realtime](https://github.com/supabase/realtime#server-set-up) +- [GoTrue](https://github.com/supabase/gotrue) +- [Storage](https://github.com/supabase/storage-api) +- [Kong](https://docs.konghq.com/install/docker/) + +## Managing your database + +It is recommended that you decouple your database from the middleware so that you can upgrade the middleware without any downtime. +The "middleware" is everything except Postgres, and it should work with any Postgres provider (such as AWS RDS), or your own Postgres cluster. + +### Database Extensions + +Supabase requires some Postgres extensions to be enabled by default for the API and Auth system to work. You can find the extensions inside the +[schema initialization script](https://github.com/supabase/supabase/blob/master/docker/volumes/db/init/00-initial-schema.sql). + + +We recommend installing all extensions into an `extensions` schema. This will keep your API clean, +since all tables in the `public` schema are exposed via the API. + +```sql +create schema if not exists extensions; +create extension if not exists "uuid-ossp" with schema extensions; +create extension if not exists pgcrypto with schema extensions; +create extension if not exists pgjwt with schema extensions; +``` + +##### `uuid-ossp` + +For UUID functions, required for PostgreSQL <13. + + +##### `pgcrypto` and `pgjwt` + + +For working with JWT and Auth functions. + +### Database Roles + +Supabase creates several default roles in your Postgres database. To restore defaults at any time you can run the commands inside the +[schema initialization script](https://github.com/supabase/supabase/blob/master/docker/volumes/db/init/00-initial-schema.sql). + +##### `postgres` + +The default PostgreSQL role. This has admin privileges. + +##### `anon` + +For "anonymous access". This is the role which the API (PostgREST) will use when a user _is not_ logged in. + +##### `authenticator` + +A special role for the API (PostgREST). It has very limited access, and is used to validate a JWT and then +"change into" another role determined by the JWT verification. + +##### `authenticated` + +For "authenticated access". This is the role which the API (PostgREST) will use when a user _is_ logged in. + +##### `service_role` + +For elevated access. This role is used by the API (PostgREST) to bypass Row Level Security. + +##### `supabase_auth_admin` + +Used by the Auth middleware to connect to the database and run migration. Access is scoped to the `auth` schema. + +##### `supabase_storage_admin` + +Used by the Auth middleware to connect to the database and run migration. Access is scoped to the `storage` schema. + +##### `dashboard_user` + +For running commands via the Supabase UI. + +##### `supabase_admin` + +Supabase Administrative role for maintaining your database. + +## API Keys + +The API Gateway (Kong) uses JWT to authenticate access through to the database. The JWT should correspond to a relevant Postgres Role, +and Supabase is designed to work with 2 roles: an `ANON_KEY` for unauthenticated access and a `SERVICE_KEY` for elevated access. + +Use this tool to generate keys: + + + +## Managing your secrets + +Many components inside Supabase use secure secrets and passwords. These are listed in the self-hosting +[env file](https://github.com/supabase/supabase/blob/master/docker/.env.example), but we strongly recommend using a +secrets manager when deploying to production. Plain text files like dotenv lead to accidental costly leaks. + +Some suggested systems include: + +- [Doppler](https://www.doppler.com/) +- [Key Vault](https://docs.microsoft.com/en-us/azure/key-vault/general/overview) by Azure +- [Secrets Manager](https://aws.amazon.com/secrets-manager/) by AWS +- [Secrets Manager](https://cloud.google.com/secret-manager) by GCP +- [Vault](https://www.hashicorp.com/products/vault) by Hashicorp + +## Migrating and Upgrading + +If you have decoupled your database from the middleware, then you should be able to redeploy the latest middleware at any time as long as it has no breaking changes. +Supabase is evolving fast, and we'll continue to improve the migration strategy as part of our core offering. + +We realize that database migrations are difficult, and this is one of the problems we plan to make easy for developers. + +## Deployment options + +While Supabase officially supports Docker, we have several other deployment strategies managed by the community: + +- [supabase-docker](/docs/guides/hosting/docker) (Official) +- [supabase-kubernetes](https://github.com/supabase-community/supabase-kubernetes) (Unofficial) +- [supabase-terraform](https://github.com/supabase-community/supabase-terraform) (Unofficial) +- [supabase-traefik](https://github.com/supabase-community/supabase-traefik) (Unofficial) diff --git a/apps/reference/docs/guides/hosting/platform.mdx b/apps/reference/docs/guides/hosting/platform.mdx new file mode 100644 index 00000000000..3543469ad40 --- /dev/null +++ b/apps/reference/docs/guides/hosting/platform.mdx @@ -0,0 +1,35 @@ +--- +id: platform +title: Supabase Platform +description: Getting started with the Supabase platform. +--- + + +Supabase is a hosted platform which makes it very simple to get started without needing to manage any infrastructure. + +Visit [app.supabase.com](https://app.supabase.com) and sign in to start creating projects. + +## Organizations + +Organizations are a way to group your projects. Every Organization can be configured with different Team members and billing settings. + +### Managing Team Members + +You can invite your Team members into your Organizations so that you can collaborate on projects. + + + +## Projects + +Each project on Supabase comes with these features: + +- A dedicated Postgres database. [Learn more](/docs/guides/database) +- Auto-generated APIs. [Learn more](/docs/guides/api) +- Auth and User management. [Learn more](/docs/guides/auth) +- Storage. [Learn more](/docs/guides/storage) + +## Next Steps + +- Sign in to [app.supabase.com](https://app.supabase.com) diff --git a/apps/reference/docs/guides/integrations/appsmith.mdx b/apps/reference/docs/guides/integrations/appsmith.mdx new file mode 100644 index 00000000000..ff9d330752a --- /dev/null +++ b/apps/reference/docs/guides/integrations/appsmith.mdx @@ -0,0 +1,151 @@ +--- +id: appsmith +title: 'Appsmith' +description: 'Get started with Supabase and Appsmith, an open-source framework for building internal tools.' +--- + +This guide explains how to quickly build a Support Dashboard by connecting a Supabase back-end to an Appsmith front-end. + +[Appsmith](https://www.appsmith.com/) is an open-source framework for building internal tools. It lets you drag-and-drop UI components to build pages, connect to any API, database or GraphQL source and write logic with JavaScript objects. + +If you don’t have an Appsmith account, create one [here](https://app.appsmith.com/user/signup). + +Let’s get started! + +## Step 1: Set up your Backend on Supabase + +- On the [Supabase dashboard](https://app.supabase.com), click `New project` and set the name to **Support Dashboard** + +![create-project-supabase-01](/img/guides/integrations/appsmith/create-project-supabase-01.png) + +- Create a new table by clicking on the Create Table option on the side navigation. +- Supabase provides many ways to add data to the tables, from writing queries to creating schemas using UI to simply uploading CSV files. For our support dashboard, we will be creating the **tickets** table by uploading the [CSV file](https://raw.githubusercontent.com/vihar/datasets/master/tickets.csv) on Supabase. + +![create-table-supabase-02](/img/guides/integrations/appsmith/create-table-supabase-02.png) + +The database is now set up. + +## Step 2: Connect the database to Appsmith + +- Note down the database connection information under Project Settings in Supabase. + +![project-settings-supabase-03](/img/guides/integrations/appsmith/project-settings-supabase-03.png) + +- On Appsmith, create a new application under the dashboard under your preferred organization. +- Click on the `+` icon next to Datasources on the left navigation bar under Page1 +- Next, click on Create New tab and choose PostgreSQL datasource, you’ll see the following screenshot: + +![create-datasource-appsmith-04](/img/guides/integrations/appsmith/create-datasource-appsmith-04.png) + +- Fill out the form to connect to your Supabase instance. Click **Test** to test connection and then **Save** to save the datasource + +![connect-supabase-datasource-05](/img/guides/integrations/appsmith/connect-supabase-datasource-05.png) + +## Step 3: Build UI on Appsmith + +- Click on the + icon next to widgets and drag and drop a Tab widget. We can configure using the property pane by clicking on the cog icon on the top-right corner. +- As seen in the below screenshot, we have added four tabs to support the dashboard. + +![property-pane-appsmith-06](/img/guides/integrations/appsmith/property-pane-appsmith-06.png) + +- Add widgets to the **Home** tab to create the dashboard as shown in the screenshot below. For eg: **Critical Open Issues** is a **Text** widget and below it is an **Input** widget which we will bind later to display the number of open tickets. + +- Set up the **New** button to open a modal which will have a form to raise a new ticket. + +![bind-query-appsmith-07](/img/guides/integrations/appsmith/bind-query-appsmith-07.png) + +- In the modal widget, add a few widgets to accept input when creating a new ticket. Please refer to the screenshot below. + +![modal-appsmith-08](/img/guides/integrations/appsmith/modal-appsmith-08.png) + +## Step 4: Writing Queries in Appsmith and binding data to widgets + +- Click on the + icon next to Datasources on the navigation bar and click New Query next to the Supabase connection here to create a new query. + +![create-query-appsmith-09](/img/guides/integrations/appsmith/create-query-appsmith-09.png) + +- Rename the query to create_new_ticket under the query pane; here we can write SQL that can collect the data from the widgets using mustache templates. + +```jsx +INSERT INTO PUBLIC."tickets"("id","createdAt","user","updatedAt","description", +"status","priority","category","assignedTo") +VALUES('{{appsmith.store.ticket.id}}','{{moment().format('yyyy-mm-ddHH:MM:ss')}}','{{c_user.text}}', +'{{moment().format('yyyy-mm-ddHH:MM:ss')}}','{{c_description.text}}','{{c_status.selectedOptionValue}}', +'{{c_property.selectedOptionValue}}', +'{{c_category.selectedOptionValue}}','{{c_assignee.selectedOptionValue}}'); +``` + +- Click the **Confirm** button on the modal and under **Events**, set the **onClick** property to execute the create_new_ticket query. +- Create a second query named **get_tickets** that will list all the tickets. + + **** + +```jsx +SELECT * FROM public."tickets"; +``` + +- Drag and drop a table widget under the **Assigned To Me** tab. Open the property pane and add the following snippet under **Table Data** to bind the query results. + +```jsx +{{get_tickets.data.filter(t => t.assignedTo === 'confidence@appsmith.com' && t.status !== 'closed')}} +``` + +- Drag and drop a table widget under the **Resolved** tab. Open the property pane and add the following snippet under **Table Data** to bind the query results. + +```jsx +{{get_tickets.data.filter(t => t.status === 'open')}} +``` + +- Drag and drop a table widget under the **Closed** tab. Open the property pane and add the following snippet under **Table Data** to bind the query results. + +```jsx +{{get_tickets.data.filter(t => t.status === 'closed')}} +``` + +## Step 5: Creating Charts in Appsmith + +- On the **Home** tab, click on the first Chart widget. Add Title **Open Issues By Category**. Change the **Chart Type** property to **Column Chart**. +- Update the x-axis and y-axis Labels under **Axis** on the property pane. +- Add the following code snippet under the **Series Data** property to bind the data to be displayed on the x and y axes. + +```jsx +[ + { + "x": "Hardware", + "y": {{get_tickets.data.filter(t => t.status==='open' && t.category==='hardware').length}} + }, + { + "x": "Software", + "y": {{get_tickets.data.filter(t => t.status==='open' && t.category==='software').length}} + }, + { + "x": "Other", + "y": {{get_tickets.data.filter(t => t.status==='open' && t.category==='other').length}} + } +] +``` + +- The second chart will be a pie chart. Add the title, axes labels as mentioned above, +- Add the following code snippet under the **Series Data** property of the pie chart. + +```jsx +[ + { + "x": "High", + "y": {{get_tickets.data.filter(t => t.status==='open' && t.priority==='high').length}} + }, + { + "x": "Medium", + "y": {{get_tickets.data.filter(t => t.status==='open' && t.priority==='medium').length}} + }, + { + "x": "Low", + "y": {{get_tickets.data.filter(t => t.status==='open' && t.priority==='low').length}} + } +] +``` + +## Resources +- [Appsmith](https://www.appsmith.com/) official website. +- [Appsmith GitHub](https://github.com/appsmithorg). +- [Appsmith](https://docs.appsmith.com/) documentation. \ No newline at end of file diff --git a/apps/reference/docs/guides/integrations/auth0.mdx b/apps/reference/docs/guides/integrations/auth0.mdx new file mode 100644 index 00000000000..03dc5270dff --- /dev/null +++ b/apps/reference/docs/guides/integrations/auth0.mdx @@ -0,0 +1,458 @@ +--- +id: auth0 +title: 'Auth0' +description: 'Swap out Supabase authentication with Auth0. Let Auth0 handle tokens and signing users in and out, while Supabase enforces authorization policies with Row Level Security (RLS).' +--- + +This guide steps through building a Next.js application with Auth0 and Supabase. We configure Auth0 to handle authenticating users and managing tokens, while writing our authorization logic in Supabase - using Row Level Security policies. + +> Note: This guide is heavily inspired by the [Using Next.js and Auth0 with Supabase](https://auth0.com/blog/using-nextjs-and-auth0-with-supabase/) article on [Auth0's blog](https://auth0.com/blog/). Check it out for a practical step-by-step guide on integrating Auth0 and Supabase. + +The full code example for this guide can be found [here](https://github.com/dijonmusters/supabase-auth0-example). + +[Auth0](https://auth0.com/) is an authentication and authorization platform, offering numerous strategies to authenticate and manage users. It provides fine-grain control over how users sign in to your application, the token that is generated, and what data is stored about your users. + +[Next.js](https://nextjs.org/) is a web application framework built on top of React. We will be using it for this example, as it allows us to write server-side logic within our application. Auth0 have also written a [very well integrated authentication library](https://www.npmjs.com/package/@auth0/nextjs-auth0) specifically for Next.js. + +> Note: API routes (serverless functions) in Next.js closely resemble the structure of Node server frameworks - such as Express, Koa and Fastify. The server-side logic in this guide could easily be refactored in one of these frameworks and managed as a separate application to the front-end. + +If you don’t have an Auth0 account, create one [here](https://auth0.com/signup). + +You will also need a Supabase account, which can be created by signing in [here](https://app.supabase.com/). + +## Step 1: Creating an Auth0 tenant + +From the Auth0 dashboard, click the menu to the right of the Auth0 logo, and select `Create tenant`. + +![Create tenant from Auth0 dashboard](/img/guides/integrations/auth0/IYzHxeW.png) + +Enter a `Domain` for your tenant - this will need to be unique. + +Select a `Region` - this should be geographically close to the majority of your users. + +Select `Development` for `Environment Tag` - this should be production when you're ready to go live. + +![Auth0 tenant settings](/img/guides/integrations/auth0/iSA3E0J.png) + +## Step 2: Setting up an Auth0 application + +From the sidebar menu, select `Applications` > `Applications` and click `Create Application`. + +Give your application a name, select the `Regular Web Applications` option and click `Create`. + +![Auth0 application settings](/img/guides/integrations/auth0/ANU4Wez.png) + +Select `Settings` and navigate to the `Application URIs` section, and update the following: + +`Allowed Callback URLs`: `http://localhost:3000/api/auth/callback` + +`Allowed Logout URLs`: `http://localhost:3000` + +Scroll to the bottom of the `Settings` section and reveal the `Advanced Settings`. + +Select `OAuth` and set `JSON Web Token Signature` to `RS256`. + +Confirm `OIDC Conformant` is `Enabled`. + +Click `Save` to update the settings. + +## Step 3: Creating a Supabase project + +From your [Supabase dashboard](https://app.supabase.com/), click `New project`. + +Enter a `Name` for your Supabase project. + +Enter a secure `Database Password`. + +Select the same `Region` you selected for your Auth0 tenant. + +Click `Create new project`. + +![New Supabase project settings](/img/guides/integrations/auth0/qnmJEU7.png) + +## Step 4: Creating data in Supabase + +From the sidebar menu in the [Supabase dashboard](https://app.supabase.com/), click `Table editor`, then `New table`. + +Enter `todo` as the `Name` field. + +Select `Enable Row Level Security (RLS)`. + +Create two new columns: + +- `title` as `text` +- `user_id` as `text` +- `is_complete` as `bool` with the default value `false` + +Click `Save` to create the new table. + +![Todo table](/img/guides/integrations/auth0/33kqP4K.png) + +From the `Table editor` view, select the `todo` table and click `Insert row`. + +Fill out the `title` field and click `Save`. + +![New row settings](/img/guides/integrations/auth0/mEhHAWC.png) + +Click `Insert row` and add a couple of extra todos. + +![List of todos](/img/guides/integrations/auth0/dLOvhdq.png) + +## Step 5: Building a Next.js app + +Create a new Next.js project: + +```bash +npx create-next-app +``` + +Create a `.env.local` file and enter the following values: + +``` +AUTH0_SECRET=any-secure-value +AUTH0_BASE_URL=http://localhost:3000 +AUTH0_ISSUER_BASE_URL=https://..auth0.com +AUTH0_CLIENT_ID=get-from-auth0-dashboard +AUTH0_CLIENT_SECRET=get-from-auth0-dashboard +NEXT_PUBLIC_SUPABASE_URL=get-from-supabase-dashboard +NEXT_PUBLIC_SUPABASE_KEY=get-from-supabase-dashboard +SUPABASE_SIGNING_SECRET=get-from-supabase-dashboard +``` + +> Note: Auth0 values can be found under `Settings > Basic Information` for your application. + +![Auth0 settings](/img/guides/integrations/auth0/o07FaoV.png) + +> Note: Supabase values can be found under `Settings > API` for your project. + +![Supabase settings](/img/guides/integrations/auth0/r1GAfLo.png) + +Restart your Next.js development server to read in the new values from `.env.local`. + +```bash +npm run dev +``` + +## Step 6: Install Auth0 Next.js library + +Install the `@auth0/nextjs-auth0` library. + +```bash +npm i @auth0/nextjs-auth0 +``` + +Create a new file `pages/api/auth/[...auth0].js` and add: + +```jsx +// pages/api/auth/[...auth0].js + +import { handleAuth } from '@auth0/nextjs-auth0' + +export default handleAuth() +``` + +> Note: This will create a few API routes for us. The main ones we will use are `/api/auth/login` and `/api/auth/logout` to handle signing users in and out. + +Open `pages/_app.js` and wrap our `Component` with the `UserProvider` from Auth0: + +```jsx +// pages/_app.js + +import React from 'react' +import { UserProvider } from '@auth0/nextjs-auth0' + +const App = ({ Component, pageProps }) => { + return ( + + + + ) +} + +export default App +``` + +Update `pages/index.js` to ensure the user is logged in to view the landing page. + +```jsx +// pages/index.js + +import styles from '../styles/Home.module.css' +import { withPageAuthRequired } from '@auth0/nextjs-auth0' +import Link from 'next/link' + +const Index = ({ user }) => { + return ( +
+

+ Welcome {user.name}!{' '} + + Logout + +

+
+ ) +} + +export const getServerSideProps = withPageAuthRequired() + +export default Index +``` + +> Note: `withPageAuthRequired` will automatically redirect the user to `/api/auth/login` if they are not currently logged in. + +Test this is working by navigating to `http://localhost:3000` which should redirect you to an Auth0 sign in screen. + +![Auth0 sign in screen](/img/guides/integrations/auth0/xLRL7S7.png) + +Either `Sign up` for a new account, or click `Continue with Google` to sign in. + +You should now be able to view the landing page. + +![Landing page](/img/guides/integrations/auth0/YdBKRy6.png) + +## Step 7: Sign Auth0 token for Supabase + +Currently, neither Supabase or Auth0 allow for a custom signing secret to be set for their JWT. They also use different [signing algorithms](https://auth0.com/docs/configure/applications/signing-algorithms). + +Therefore, we need to extract the bits we need from Auth0's JWT, and sign our own to send to Supabase. + +We can do that using Auth0's `afterCallback` function, which gets called anytime the user authenticates. + +Install the `jsonwebtoken` library. + +```bash +npm i jsonwebtoken +``` + +Update `pages/api/auth/[...auth0].js` with the following: + +```jsx +// pages/api/auth/[...auth0].js + +import { handleAuth, handleCallback } from '@auth0/nextjs-auth0' +import jwt from 'jsonwebtoken' + +const afterCallback = async (req, res, session) => { + const payload = { + userId: session.user.sub, + exp: Math.floor(Date.now() / 1000) + 60 * 60, + } + + session.user.accessToken = jwt.sign(payload, process.env.SUPABASE_SIGNING_SECRET) + + return session +} + +export default handleAuth({ + async callback(req, res) { + try { + await handleCallback(req, res, { afterCallback }) + } catch (error) { + res.status(error.status || 500).end(error.message) + } + }, +}) +``` + +Our `payload` for the JWT will contain our user's unique identifier from Auth0 - `session.user.sub` and an expiry of 1 hour. + +We are signing this JWT using Supabase's signing secret, so Supabase will be able to validate it is authentic and hasn't been tampered with in transit. + +> Note: We need to sign the user out and back in again to run the `afterCallback` function, and create our new token. + +Now we just need to send the token along with the request to Supabase. + +## Step 8: Requesting data from Supabase + +Create a new file called `utils/supabase.js` and add the following: + +```jsx +// utils/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 + ) + + if (access_token) { + supabase.auth.session = () => ({ + access_token, + }) + } + + return supabase +} + +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. + +Let's load our `todos` from Supabase in our landing page! + +```jsx +// pages/index.js + +import styles from '../styles/Home.module.css' +import { withPageAuthRequired } from '@auth0/nextjs-auth0' +import { getSupabase } from '../utils/supabase' +import Link from 'next/link' +import { useEffect } from 'react' + +const Index = ({ user }) => { + const [todos, setTodos] = useState([]) + const supabase = getSupabase(user.accessToken) + + useEffect(() => { + const fetchTodos = async () => { + const { data } = await supabase.from('todo').select('*') + setTodos(data) + } + + fetchTodos() + }, []) + + return ( +
+

+ Welcome {user.name}!{' '} + + Logout + +

+ {todos?.length > 0 ? ( + todos.map((todo) =>

{todo.content}

) + ) : ( +

You have completed all todos!

+ )} +
+ ) +} + +export const getServerSideProps = withPageAuthRequired() + +export default Index +``` + +Alternatively, we could fetch todos on the server using the `getServerSideProps` function. + +```jsx +// pages/index.js + +import styles from '../styles/Home.module.css' +import { withPageAuthRequired, getSession } from '@auth0/nextjs-auth0' +import { getSupabase } from '../utils/supabase' +import Link from 'next/link' + +const Index = ({ user, todos }) => { + return ( +
+

+ Welcome {user.name}!{' '} + + Logout + +

+ {todos?.length > 0 ? ( + todos.map((todo) =>

{todo.content}

) + ) : ( +

You have completed all todos!

+ )} +
+ ) +} + +export const getServerSideProps = withPageAuthRequired({ + async getServerSideProps({ req, res }) { + const { + user: { accessToken }, + } = await getSession(req, res) + + const supabase = getSupabase(accessToken) + + const { data: todos } = await supabase.from('todo').select('*') + + return { + props: { todos }, + } + }, +}) + +export default Index +``` + +Either way, when we reload our application, we are still getting the empty state for todos. + +![Empty todo list](/img/guides/integrations/auth0/XgEMwnN.png) + +This is because we enabled Row Level Security, which blocks all requests by default. To enable our user to select their `todos` we need to write a policy. + +## Step 9: Write a policy to allow select + +Our policy will need to know who our currently logged in user is to determine whether or not they should have access. Let's create a PostgreSQL function to extract the current user from our new JWT. + +Navigate back to the Supabase dashboard, select `SQL` from the sidebar menu, and click `New query`. This will create a new query called `new sql snippet`, which will allow us to run any SQL against our Postgres database. + +Write the following and click `Run`. + +```sql +create or replace function auth.user_id() returns text as $$ + select nullif(current_setting('request.jwt.claims', true)::json->>'userId', '')::text; +$$ language sql stable; +``` + +This will create a function called `auth.user_id()`, which will inspect the `userId` field of our JWT payload. + +> Note: To learn more about PostgreSQL functions, check out [our deep dive video](https://www.youtube.com/watch?v=MJZCCpCYEqk). + +Let's create a policy that checks whether this user is the owner of the todo. + +Select `Authentication` from the Supabase sidebar menu, click `Policies`, and then `New Policy` on the `todo` table. + +![Create new policy](/img/guides/integrations/auth0/M7XyhHe.png) + +From the modal, select `Create a policy from scratch` and add the following. + +![Policy settings for SELECT](/img/guides/integrations/auth0/wuWz3am.png) + +This policy is calling the function we just created to get the currently logged in user's ID `auth.user_id()` and checking whether this matches the `user_id` column for the current `todo`. If it does, then it will allow the user to select it, otherwise it will continue to deny. + +Click `Review` and then `Save policy`. + +> Note: To learn more about RLS and policies, check out [our deep dive video](https://www.youtube.com/watch?v=Ow_Uzedfohk). + +The last thing we need to do is update the `user_id` columns for our existing `todos`. + +Head back to the Supabase dashboard, and select `Table editor` from the sidebar. + +![User ID null in Supabase Table Editor](/img/guides/integrations/auth0/dLOvhdq.png) + +Each of our `user_id` columns are set to `NULL`! + +To get the ID for our Auth0 user, head over to the Auth0 dashboard, select `User Management` from the sidebar, click `Users` and select your test user. + +![List of users in Auth0 dashboard](/img/guides/integrations/auth0/GdXS013.png) + +Copy their `user_id`. + +![User ID in Auth0 dashboard](/img/guides/integrations/auth0/tbvd0Uj.png) + +Update each row in Supabase. + +![User ID set to Auth0 user](/img/guides/integrations/auth0/tPu4Tt8.png) + +Now when we refresh our application, we should finally see our list of `todos`! + +> Note: Check out [the repo](https://github.com/dijonmusters/supabase-auth0-example/blob/main/pages/index.js) for an example of writing new `todos` to Supabase. + +## Resources + +- [Auth0](https://auth0.com/) official website. +- [Auth0 blog](https://auth0.com/blog/). +- [Using Next.js and Auth0 with Supabase article](https://auth0.com/blog/using-nextjs-and-auth0-with-supabase/). +- [Auth0 community](https://community.auth0.com/). +- [Auth0 documentation](https://auth0.com/docs/). diff --git a/apps/reference/docs/guides/integrations/clerk.mdx b/apps/reference/docs/guides/integrations/clerk.mdx new file mode 100644 index 00000000000..8e625843f9f --- /dev/null +++ b/apps/reference/docs/guides/integrations/clerk.mdx @@ -0,0 +1,184 @@ +--- +id: clerk +title: 'Clerk' +description: 'This guide explains how to connect your Supabase database with Clerk, a powerful authentication provider built for the modern web.' +--- + +This guide explains how to connect your Supabase database with [Clerk](https://clerk.dev), an authentication provider built for the modern web. + +Clerk authenticates users, manages session tokens, and provides user management functionality that can be used in combination with the authorization logic available in Supabase through PostgreSQL Row Level Security (RLS) policies. + +This guide assumes you have a Supabase account and database project already set up. + +If you don't have a Clerk account, you can [create one now](https://dashboard.clerk.dev/sign-up). + +## Step 1: Create JWT template + +The first step is to create a new Clerk application from your Clerk Dashboard if you haven't done so already. You can choose whichever authentication strategy and social login providers you prefer. For more information, check out Clerk's [guide](https://docs.clerk.dev/popular-guides/setup-your-application). + +After your Clerk application has been created, use the lefthand menu to navigate to the **JWT Templates** page. + +Click on the button to create a new template based on Supabase. + +![Create Supabase JWT template from Clerk dashboard](/img/guides/integrations/clerk/01_supabase-template.png) + +This will pre-populate the default claims required by Supabase. You can include additional claims or modify them as necessary. [Shortcodes](https://docs.clerk.dev/popular-guides/jwt-templates#shortcodes) are also available for adding dynamic values. + +ℹ️ Note the name of the JWT template (which you can change) because this will be needed later. + +![JWT template claims](/img/guides/integrations/clerk/02_jwt-claims.png) + +## Step 2: Sign JWT with Supabase secret + +Supabase requires JWTs be signed with the HS256 signing algorithm and use their signing key. Find the JWT secret key in your Supabase project under **Settings** > **API** in the **Config** section. + +![Sign with Supabase secret](/img/guides/integrations/clerk/03_jwt-secret.png) + +Click to reveal the JWT secret, copy it, and then paste it in the Signing key field in the Clerk JWT template. + +![Paste signing key](/img/guides/integrations/clerk/04_signing-key.png) + +After the key is added, click the **Apply Changes** button to save your template. + +## Step 3: Configure client + +The next step is to configure your client. Supabase provides an official [JavaScript/TypeScript client library](https://github.com/supabase/supabase-js) and there are [libraries in other languages](https://supabase.com/docs/reference/javascript/installing) built by the community. + +This guide will use a Next.js project with the JS client as an example, but the mechanism of setting the authentication token should be similar with other libraries and frameworks. + +Assuming a Next.js application, set the following environment variables in an `.env.local` file: + +```bash +NEXT_PUBLIC_CLERK_FRONTEND_API=your-frontend-api +NEXT_PUBLIC_SUPABASE_URL=your-supabase-url +NEXT_PUBLIC_SUPABASE_KEY=your-supabase-anon-key +``` + +**Note**: If you're using Create React App, replace the `NEXT_PUBLIC` prefix with `REACT_APP` + +Your Clerk Frontend API can be found on the [API Keys](https://dashboard.clerk.dev/last-active?path=api-keys) screen. + +![Clerk Frontend API](/img/guides/integrations/clerk/05_clerk-frontend-api.png) + +To get the ones needed for Supabase, navigate to the same Settings > API page as before and locate the anon public key and URL. + +![Supabase keys](/img/guides/integrations/clerk/06_supabase-keys.png) + +**Note**: It is recommended that you enable [Row Level Security](https://supabase.com/docs/guides/auth/row-level-security) (RLS) for your database tables and configure access policies as needed. + +After setting those three environment variables, you should be able to start up your application development server. + +Install the JavaScript client for Supabase with: + +```bash +npm install @supabase/supabase-js +``` + +Initialize the Supabase client by passing it the environment variables. + +This can be saved to a common file, for example as `lib/supabaseClient.js` + +```jsx +import { createClient } from '@supabase/supabase-js'; + +const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; +const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_KEY; + +export const supabase = createClient(supabaseUrl, supabaseKey); +export default supabase; +``` + +## Step 4: Set up Clerk Provider + +Install the latest Clerk Next.js SDK by running the following: + +```bash +npm install @clerk/nextjs@next +``` + +**Note**: There is also a Clerk library for [React](https://github.com/clerkinc/javascript/tree/main/packages/react) and [React Native with Expo](https://github.com/clerkinc/javascript/tree/main/packages/expo). + +After the package is installed, wrap your application with the `` component. + +In a Next.js application, this is typically done in `pages/_app.js`: + +```jsx +import { ClerkProvider } from '@clerk/nextjs'; + +function MyApp({ Component, pageProps }) { + return ( + + + + ); +} + +export default MyApp; +``` + +## Step 5: Set auth token with Supabase + +In order to access the custom JWT, you can use the `getToken` function returned by the Clerk `useAuth` hook and pass it the name of your template (hopefully you remembered from earlier). + +**Note**: The `getToken({ template: })` call is asynchronous and returns a Promise that needs to be resolved before accessing the token value. This token is short-lived for better security and should be called before every request to your Supabase backend. The caching and refreshing of the token is handled automatically by Clerk. + +Call `supabase.auth.setAuth(token)` to override the JWT on the current client. The JWT will then be sent to Supabase with all subsequent network requests. + +```jsx +import { useAuth } from '@clerk/nextjs'; +import supabase from '../lib/supabaseClient'; + +export default function Home() { + const { getToken } = useAuth(); + + const fetchData = async () => { + // TODO #1: Replace with your JWT template name + const token = await getToken({ template: 'supabase' }); + + supabase.auth.setAuth(token); + + // TODO #2: Replace with your database table name + const { data, error } = await supabase.from('your_table').select(); + + // TODO #3: Handle the response + }; + + return ( + + ); +} +``` + +## Access user ID in RLS policies + +It is common practice to need access to the user identifier on the database level, especially when working with RLS policies in Postgres. Although Supabase provides a special function `auth.uid()` to extract the user ID from the JWT, this does not work with Clerk. The workaround is to write a custom SQL function to read the `sub` property from the JWT claims. + +In the **SQL Editor** section of the Supabase dashboard, click New Query and enter the following: + +```sql +create or replace function requesting_user_id() +returns text +language sql stable +as $$ + select nullif(current_setting('request.jwt.claims', true)::json->>'sub', '')::text; +$$; +``` + +This will create a `requesting_user_id()` function that can be used within an RLS policy. + +For example, this policy would check that the user making the request is authenticated and matches the `user_id` column of a todos table. + +## Access user ID in table column + +If you would like the requesting user ID from the JWT to automatically populate a text type column in your database table, you can set the **Default Value** field to the previously defined `requesting_user_id()` function. + +![Set requesting_user_id() as default value](/img/guides/integrations/clerk/07_requesting-user-id.png) + +## Resources + +- [Clerk + Supabase starter repo](https://github.com/clerkinc/clerk-supabase-starter) +- [Next.js + Supabase + Clerk tutorial](https://clerk.dev/blog/nextjs-supabase-todos-with-multifactor-authentication) +- [Clerk guide for Next.js Authentication](https://docs.clerk.dev/get-started/nextjs) +- [Clerk Community Discord channel](https://discord.com/invite/b5rXHjAg7A) diff --git a/apps/reference/docs/guides/integrations/dashibase.mdx b/apps/reference/docs/guides/integrations/dashibase.mdx new file mode 100644 index 00000000000..6383dc02a7e --- /dev/null +++ b/apps/reference/docs/guides/integrations/dashibase.mdx @@ -0,0 +1,239 @@ +--- +id: dashibase +title: 'Dashibase' +description: 'Create a CRUD app with Supabase and Dashibase in 15 mins.' +--- + +import ThemedImage from '@theme/ThemedImage' +import useBaseUrl from '@docusaurus/useBaseUrl' + +Let’s build an app together! + +This guide walks you through how to build a CRM for superheroes using Supabase on the backend and Dashibase on the front. + +[Dashibase](https://dashibase.com/) is a lightning-fast way to build your app dashboard so that your end users can manage their data. You get a full dashboard UI right out of the box. Not boilerplate code. Not drag-and-drop. Not individual components. + +## Step 1. Write down your idea + +Let’s say we want to build a CRM for Marvel Cinematic Universe. With the multiverse, the superheroes would need a CRM to stay in touch. + +Here is the information we want our users to store in our app: + +1. Name +2. Universe +3. Email +4. Last contacted date +5. Relationship: Never met, Acquaintance, Close +6. Can he/she fly? +7. History + +## Step 2. Set up your Supabase project + +First, sign up for a Supabase account and create a new project. We are naming our project MultiverseCRM. + + + +Next, set up the table for our data. Our table is called ‘contacts'. + +To store the various information we want, we need to set up the following columns: + +1. Name (text) +2. Universe (int4) +3. Email (text) +4. Last contacted date (date) +5. Relationship: Never met, Acquaintance, Close (text) +6. Can he/she fly? (boolean) +7. History (text) + +We also need a `user` column, which is a [foreign key](https://supabase.com/docs/guides/database/tables#joining-tables-with-foreign-keys) to the auth.users table so that we can keep track of which user these contacts belong to. To do that, add another column, name it ‘user’, and click on the chainlink button to add the foreign key relation. Then, select ‘users’ and ‘id’. + + + +This is what the columns should look like: + + + +Congrats! You have set up the backend of your app. + +## Step 3. Set up your frontend with Dashibase + +Let’s hop over to [Dashibase](https://dashibase.com/). + +When you log in to your new account, you will see an empty dashboard. + + + +The first things to do are to name our app, pick a URL, and connect our Supabase project. You can find your Supabase URL and Anon Key in your Supabase project > Settings > API. + + + +Connecting your Supabase project to Dashibase is as simple as that. + +Next, let’s create a page where our users can view, add, and edit their contacts. Simply click on “Add page”. + +Here are the settings we use for our Contacts page: + +- Name: Contacts +- Page URL: /contacts +- Supabase table: contacts (This is automatically pulled from your Supabase project. If you have multiple tables, you can select the relevant one.) +- Display: list (We will display our contacts in a list for now.) +- Read-only: false (Our users should be able to edit their contacts.) +- ID column: id (This is the ID of each contact in our database. If you are not using ‘id’ as your ID column, feel free to change this.) +- User column: user (This is the `user` column we created earlier.) + + + +Then, we will add the attributes for each contact so that our users can view or edit them: + +1. Name (text) +2. Universe (text) +3. Email (text) +4. Last contacted date (date) +5. Relationship: Never met, Acquaintance, Close (single select) +6. Can he/she fly? (boolean) +7. History (long text) + + + + +When you use the 'Single Select' type, you will get to add the options you want. + + + +Let’s customize our contacts a little. We will set Name, Universe, and Email as required fields. + + + +Then, we will hide History from the list because it can get too long. Our users will still be able to view a contact’s history by clicking on the contact in the dashboard. + + + +Finally, we will try the card display (under the page settings). + + + +The cards look pretty good in the preview. We will use that for now. + +**Once done, just hit “Save” and “Deploy”. Your app is now live!** + +One quick thing: You want to add your app URL to your Supabase project > Settings > Authentication > Additional redirect URLs. This redirects your users to your app when they sign up. + + + +## Step 4: Share your app + +Your app comes with signup and login pages right out of the box. You don’t have to spend time building that at all. + + + +When you are ready, share your app with your family, friends, and followers! + +P.S. You can check out our app at [https://multiversecrm.app.dashibase.com](https://multiversecrm.app.dashibase.com/). You can add new contacts and edit or delete existing contacts. You can also filter or sort to look for certain contacts. + + + +Fun fact: Both Dashibase and apps created with Dashibase have light and dark modes out of the box. Toggle the light/dark mode for this page to see them! + +## Resources + +- [Dashibase website](https://dashibase.com/) +- [Dashibase open-source repo](https://github.com/dashibase/dashibase) +- [Dashibase Twitter](https://twitter.com/dashibase) \ No newline at end of file diff --git a/apps/reference/docs/guides/integrations/directus.mdx b/apps/reference/docs/guides/integrations/directus.mdx new file mode 100644 index 00000000000..ef9a8855a5c --- /dev/null +++ b/apps/reference/docs/guides/integrations/directus.mdx @@ -0,0 +1,128 @@ +--- +id: directus +title: 'Directus' +description: "In this guide, we will show you how to create a Supabase project, install the Directus platform locally and configure the two to connect." +--- + +In this guide, we will demonstrate how to create a new Supabase project, install a fresh instance of the Directus platform, then configure the two to work together seamlessly. If you're unfamiliar with either of these systems, don’t worry! We’ll start off with an overview of each platform and explain how they complement each other, noting any overlap in capabilities. + +## Introduction + +![Supabase App](/img/guides/integrations/directus/supabase-20220608A.webp) + +[Supabase](​​https://supabase.com/) is an open-source Firebase alternative that provides a PostgreSQL database, storage, authentication, and a dynamic REST API based on your schema. While it is possible to self-host Supabase on your own infrastructure, this article will focus on Supabase Cloud’s Free tier, which is the fastest and easiest way to get started. + +![Directus App](/img/guides/integrations/directus/directus-20220608A.webp) + +[Directus](https://directus.io/) is an open-source data platform that layers on top of any SQL database, providing a powerful suite of tools. The Directus Engine provides dynamic REST and GraphQL APIs based on your schema, hooks and automation, authentication and access control, and file transformations. Directus Studio enables engineers and non-technical users alike to browse, manage, and visualize database content through a no-code app. + +--- + +Supabase is a suite of open-source tools making Postgres databases, file storage, authentication, and edge functions more accessible to developers of all skill levels. Directus is also developer tooling and additionally provides a Data Studio that is safe and intuitive enough for anyone, including non-technical users, to use. This is the crucial bit that gives the two platforms such a strong “network effect.” + +When these two systems are brought together, you get a scalable datastore, limitless connectivity options, and a no-code app that allows your technical and business teams to collaborate together efficiently. + +The two platforms share an overlap of capabilities that deepens their integration and offers developers the freedom of choice across a broader spectrum of connectivity. Key areas of intersection include: + +The ability to generate *powerful* APIs dynamically to connect data +User management and fine-grained access control +Digital asset storage and management. + +More importantly, Directus and Supabase share a common vision for your data, making them quite symbiotic. Both solutions are completely open-source, with self-hosted and cloud deployment options available. They are unopinionated in their approach, with vendor-agnostic data storage, and they both focus on providing a polished developer experience along with comprehensive documentation. + +By linking the Supabase database with your Directus Project, *you get a superset of data tools.* You'll benefit from Supabase's Postgres database and its *dev-centric* admin app with the raw power to run SQL queries, ***as well as*** the Directus no-code app, which enables intuitive permissions-based data access for the whole team. + +Let’s dive into how we actually set up and link these two platforms to create a modern data stack powerhouse. + +## Create a Supabase Project + +As mentioned, while you can [deploy Supabase locally](https://supabase.com/docs/guides/local-development). For the purpose of this guide, we’ll use Supabase Cloud: + +1. Create a **Supabase** account by signing in with GitHub. +2. Give your organization a name (this can be changed later). +3. Click **New Project** and select your organization. +4. Follow the prompts, setting a project Name, Database Password, Region, and Pricing Plan, then click **Create New Project**. +5. After your project has been provisioned, navigate to **Settings > Database** in the sidebar. +6. Scroll down to **Connection Info** and take note of your database’s **Host**, **Database Name**, **Port**, **User**, and **Password**. You will need to enter this during your Directus project setup. + +## Optional: Add PostGIS to Support Geometry and Mapping + +To take full advantage of the built-in geometry and mapping features Directus offers, we recommend enabling Geometric Data Support. To add PostGIS, follow these steps: + +![Enable PostGis](/img/guides/integrations/directus/enable-PostGIS-20220608A.webp) + +1. From the sidebar, navigate to **Database > Extensions**. +2. Use the search bar to look up `PostGIS`. +3. Toggle the PostGIS option to enable it. + +## Set up Directus + +At the time of writing this article, [Directus Cloud](https://directus.cloud/) does not yet support hybrid deployments for connecting an external database. So, we’ll be deploying a self-hosted instance to connect with Supabase. To install a self-hosted instance of Directus that’s connected to our Supabase project, follow these steps: + +1. Run the following command in your terminal: + +```bash +npm init directus-project example-project +``` + +2. Using the up/down arrow keys, select `Postgres` from the list: + +```bash +? Choose your database client Postgres +``` + +3. Next, you will be prompted to input database credentials. Add in the Supabase Database Connection Info noted above as follows: + +- **Database Host** – The IP address for your database. +- **Port** – Port number your database is running on. +- **Database Name** – Name of your existing database. +- **Database User** – Name of existing user in database. +- **Database Password** – Password to enter database. +- **Enable SSL** – Select Y for yes or N for no. +- **Root** – The root name. + +4. Now, simply set an email and password for your first Directus admin account. To be clear, this is Directus-specific, and is unrelated to your database user: + +```bash +Create your first admin user: +? Email: admin@example.com +? Password: ******** +``` + +Once this is complete, you should see details about your new project: + +```bash +Your project has been created at /example-project. +The configuration can be found in /example-project/.env +``` + +5. Lastly, navigate to your new project folder (in this case `example-project`) and start the platform: + +```bash +cd example-project +npx directus start +``` +**Please note:** To prevent public accessibility when using the supabase-js library,turn on row level security (RLS) on all these tables inside of the Supabase Dashboard. By default when RLS is turned on these tables cannot be read from or written to with the supabase-js library. + +That’s it! Your project is now up and running locally. You can access the Directus Studio in the browser via the URL displayed, and log in with the Directus admin credentials you entered above: + +```bash +✨ Server started at http://localhost:8055 +``` + +In a matter of minutes, we’ve created a flexible data backend, with access to an intuitive no-code app for managing and visualizing data along with a robust connectivity toolkit. This modern data stack is flexible and scalable enough to power any data-driven project… all you need to do is build the frontend! + +## Next Steps + +From here, the sky's the limit on what you can build. You’ll probably want to invite some new collaborators to your project and start architecting your data model. + +Below are some additional resources to dive in and start exploring these two platforms: + +**Directus** +- See the [Directus guides](https://directus.io/guides/). +- Join the Directus community on [Discord](https://directus.chat/). +- Check out the source code on the official [Directus GitHub Repo](https://github.com/directus/directus). + +**Supabase** +- Explore the [Supabase documentation](https://supabase.com/docs) +- Join the Supabase community on [Discord](https://discord.supabase.com/) diff --git a/apps/reference/docs/guides/integrations/draftbit.mdx b/apps/reference/docs/guides/integrations/draftbit.mdx new file mode 100644 index 00000000000..56e5eabd09a --- /dev/null +++ b/apps/reference/docs/guides/integrations/draftbit.mdx @@ -0,0 +1,231 @@ +--- +id: draftbit +title: 'Draftbit' +description: 'Connect your Supabase postgres database to your Low-code mobile app.' +--- + +This guide explains how to connect a Supabase back-end to a Draftbit front-end and then configure all CRUD operations necessary to build a simple mobile app. + +[Draftbit](https://draftb.it/3Fkbask) is a "pro-code" low-code mobile app building platform. Draftbit exports React Native source code that is 100% run on open-source languages and libraries. + +Draftbit is back-end agnostic and connects to Supabase via REST API. + +> Note: For the demonstration purpose of this guide, we are using a pre-populated database in Supabase. We are calling `Groceries`. To follow along, rename it any way you prefer. + +![Prepopulated Database](/img/guides/integrations/draftbit/prepopulated-database.png) + +If you don’t have a Draftbit account, create one [here](https://draftb.it/3Fkbask). Once you’ve got your account set up, Create a New App. You can select `Start From a Blank App` for this demo and proceed to the Builder interface. + +## Step 1: Get the RESTful endpoint and Project API key + +To connect the REST API in the Draftbit app, the following fields are required: + +- Base URL of the REST API, which is in the format: `https://.supabase.co/rest/v1` where the `` (the space between `Bearer` and `` is required). Click **Add** after adding the value. +- Enter another key name to access the API Key such as `Api_Key_Header`. When making the service connection in the next section, it will be passed as the header `apiKey` value. +- The value of this key requires you to enter an authorization token that starts with syntax is ``. Click **Add** after adding the value. +- Click **Save** to save these keys and close the modal. + +![Add header values in Draftbit](/img/guides/integrations/draftbit/authheader.png) + +## Step 3: Add Supabase RESTful endpoint in Draftbit + +In your Draftbit builder interface: + +- Open the **API & Cloud Services** modal from the top menu bar. +- From the **Connect a service** menu, click on **Rest API**. + +- In Step 1: Enter a name for your REST API. Then, paste your `Base URL` (from the first section) into the Base URL field. +- In Step 2: Under **Key** add `Authorization` and `apikey`. Then, under **Value**, select the global variables (from the previous section) to add the actual values for both keys. +- Click Save. + +![Create a API service in Draftbit](/img/guides/integrations/draftbit/service.png) + +## Making API requests with Supabase & Draftbit + +### GET request to Fetch all records + +In this section, let's populate a Fetch component with all the data from a simple Supabase and then display the data fetched from the Supabase data table in a List component. + +For reference, here is a how the Components tree looks like for this screen: + +![Components tree](/img/guides/integrations/draftbit/ctree.png) + +The next step is to create an endpoint. Let's try fetching all the data using a `GET` HTTP request. Select the Supabase service in the **API & Cloud Services** modal, and then: + +- Click **Add endpoint**. +- In Step 1: enter the name for the endpoint. Make sure the **Method** select is `GET`. +- In Step 2: add the base name path: `/groceries/select=*`, where `groceries` is the table name in Supabase. +- In Step 4: click the **Test** button next to the Endpoint input to verify the response coming from the Supabase. +- Click Save. + +![Creating a GET request endpoint](/img/guides/integrations/draftbit/get-request.gif) + +In the Builder, on the app screen: + +- Select the Fetch component in the Components tree and go to the [Data tab from Properties Panel](doc:introduction-to-the-builder#properties-panel). +- For **Service**, select the name of the Supabase Service. +- For **Endpoint**, select the endpoint you want to fetch the data from. +- Select the List component in the Components and go to the [Data tab from Properties Panel](doc:introduction-to-the-builder#properties-panel). In Data, select `Top-Level Response` from the dropdown menu. +- Then, select the Text component in the Components and then go to the Data tab from the Properties Panel. +- Add a `{{varName}}` value (inside the curly braces) to represent a column field from the Supabase. For example, add `{{title}}` to represent the column name from the Supabase Base. +- Under **Variables**, you will see the variable name defined in the previous step. From the dropdown menu, select the appropriate field that represents the data field. + +![Fetching data on app screen](/img/guides/integrations/draftbit/fetchall.gif) + +### GET request to fetch single row + +Open the **API & Cloud services** modal from the top menu, select the Supabase service, and then: + +- Click **Add endpoint**. +- In Step 1: enter a name for the endpoint. +- In Step 2: add the `/groceries/column-name=eq.{{column-name}}` variable. Then, add a Test value for the `{{column-name}}`. For example, it can be the `title` or the `id`. +- In Step 4: click the **Test** button next to the Endpoint input to verify the response coming from the Supabase. +- Click Save. + +![Creating endpoint to fetch a single row](/img/guides/integrations/draftbit/getsingle.gif) + +On app screen: + +- Select the Fetch component in the Components tree and go to the Data tab from Properties Panel +- For **Service**, select the name of the Supabase Service. +- For **endpoint**, select the endpoint you want to fetch the data from. +- Set the value for the `id` in the Configuration > URL Structure section to Navigation > id. +- Select the List component in the Components and go to the Data tab from Properties Panel. In Data, select `Top-Level Response` from the dropdown menu. +- Then, select the Text component in the Components and then go to the Data tab from the Properties Panel. +- Add a `{{varName}}` value (inside the curly braces) to represent the column field from the Supabase. For example, add `{{title}}` to represent the field and value from the Supabase data table. +- Under **Variables**, you will see the variable name defined in the previous step. From the dropdown menu, select the appropriate field that represents the data field. + +![Displaying data from single row](/img/guides/integrations/draftbit/fetchsingle.png) + +### POST request to submit a new row + +Submitting new Data from the Draftbit app to Supabase's REST API requires the request to be sent using the HTTP `POST` method. + +For this section, you need to use at least one component that accepts user input and has a Field Name prop to POST data using Supabase REST API. + +You can use one of the following components in Draftbit: + +- Text Input +- Text Area/Text Field +- Checkbox +- Slider +- Radio Button Group +- Radio Button + +In addition, you need a Touchable component like a Button to attach the POST action. After you have created these components, we will create the `POST` endpoint: + +- Click **Add endpoint**. +- In Step 1: enter a name for the endpoint and select the Method to `POST`. +- In Step 2: enter the base name as path: `/groceries`. +- In Step 3: add a valid Body structure to submit a POST request. Add one or many `{{variable}}` for test values. Click Body Preview to validate the structure of the Body in the request. For the example, let's create a variable called `{{inputValue}}`. +- In Step 4: to see the new row added to the Supabase data table as JSON response inside the Builder, you have to pass a new header called `Prefer` with its value as `return=representation`. +- In Step 5: click the **Test** button next to the Endpoint input to verify the response coming from the Supabase and click Save. + +![Make a POST request to add new data to Supabase database](/img/guides/integrations/draftbit/postrequest.gif) + +Once you follow the above steps, you should get a 200 OK response with exactly the new record as a JSON you have entered for your schema. + +An example of how Body in a request will look like: + +```json +{ + "title": {{inputValue}} +} +``` + +Where `title` is the column name in your Supabase database table. + +In Draftbit, using a Touchable or a Button component, you can trigger the action **API Request** to submit the data to the endpoint. + +Now, there is a working `POST` request in Draftbit. Map its response to the components on your screen in Draftbit. + +First, for each input component, make sure you have set the Field Names (found in the Configs tab, second from the left) to unique values. For example, in the screen below, there is one TextInput field component with the value of the `Field Name` prop of `textInputValue`. + +![Field Name prop on a TextInput component](/img/guides/integrations/draftbit/textinput.png) + +Next, on your Button component, go to the Interactions tab in the Properties panel located on the far-right-hand side. Select an Action called `API request`. + +In the API request action: + +- In **Service**, select the name to Supabase API Service. +- In **Endpoint**, select the name of the Endpoint. +- Then add the configuration for the body request to be sent by selecting the values for `{{inputValue}}`. + +![Setting up the API Request to send a POST request](/img/guides/integrations/draftbit/postapirequest.png) + +After completing the above steps, you can trigger the API request to submit new data to the Supabase database. + +### PATCH request to Update a new record + +Updating an existing record from the Draftbit app to Supabase's REST API requires the request to be sent using the HTTP `PATCH` method. + +After you have created your screen components in the Draftbit builder, open the Supabase service and make the `PATCH` endpoint: + +- Click **Add endpoint**. +- In Step 1: enter a name for the endpoint and select the Method to `PATCH`. +- In Step 2: enter the base name as path: `/groceries?id=eq.{{id}}`, where `id` is the value of an existing record in the database. +- In Step 3: add a valid Body structure to submit a PATCH request. Add one or many `{{variable}}` for test values depending on the structure of your app. Click Body Preview to validate the structure of the Body in the request. For the example, let's create a variable called `{{inputValue}}`. +- In Step 5: click the **Test** button next to the Endpoint input to verify the response coming from the Supabase and click Save. + +![Creating an endpoint for PATCH request](/img/guides/integrations/draftbit/patch.gif) + +Next, on your Button component, go to the Interactions tab in the Properties panel located on the far-right-hand side. Select an Action called `API request`. + +In the API request action: + +- In **Service**, select the name to Supabase API Service. +- In **Endpoint**, select the name of the Endpoint. +- Then add the configuration for the query param, and the body request to be sent by selecting the values for `{{inputValue}}`. + +![Setting up the API Request to send a PATCH request](/img/guides/integrations/draftbit/patchapirequest.png) + +After completing the above steps, you can trigger the API request to update existing data in the Supabase database. + +### DELETE request to remove an existing record + +The `DELETE` request is to the Supabase with an item's `column-name` to remove that particular record from the table. You can use a [filter from Supabase](https://supabase.io/docs/reference/javascript/using-filters) to filter the value of a specific `column-name`. + +After you have created your screen components in the Draftbit builder, open the Supabase service and create the `DELETE` endpoint: + +- Click **Add endpoint**. +- In Step 1: enter a name for the endpoint and select the Method to `DELETE`. +- In Step 2: add `/groceries/columnName=eq.{{columnName}}`. Then, add a Test value for the `{{columnName}}`. For example, the `{{columnName}}` here can be `id` of the record. +- In Step 4: click the **Test** button next to the Endpoint input to verify the response from the Supabase. +- Click Save. + +![Creating an endpoint for DELETE request](/img/guides/integrations/draftbit/delete.gif) + +Next, on your Button component, go to the Interactions tab in the Properties panel located on the far-right-hand side. Select an Action called `API request`. + +In the API Request action: + +- In **Service**, select the name to Supabase API Service. +- In **Endpoint**, select the name of the Endpoint. +- Then, add the configuration for the query request to be sent by selecting a value. For example, in this case it will be the `id` of the record coming from the Navigation parameter. + +![Setting up the API Request to send a DELETE request](/img/guides/integrations/draftbit/deleteapirequest.gif) + +## Resources + +- [Draftbit](https://draftb.it/3Fkbask) official website. +- [Draftbit Community](https://community.draftbit.com/home). +- [Draftbit](https://docs.draftbit.com/) documentation. diff --git a/apps/reference/docs/guides/integrations/fezto.mdx b/apps/reference/docs/guides/integrations/fezto.mdx new file mode 100644 index 00000000000..42d79402524 --- /dev/null +++ b/apps/reference/docs/guides/integrations/fezto.mdx @@ -0,0 +1,27 @@ +--- +id: fezto +title: 'Frontend Zero to One' +description: 'Create an app automatically from your Supabase Postgres using OpenAPI' +--- + +[Frontend Zero to One is](https://www.fezto.xyz) is a service which creates an app for your Supabase Postgres database on-the-fly without any drag and drop, using the OpenAPI spec provided by PostgREST. + + + +# Setup + +In the [Supabase control panel](https://app.supabase.com/), open your project and click the Settings cog icon, and then "API". +You will need: +1. From the Project URL copy the project ID from https://your-project-id.supabase.co +2. From the "Project API keys" section copy the "anon" "public" API Key into the + +Paste both into the [FEZTO Supabase setup page](https://www.fezto.xyz/#/supabase) and click Launch. +You can now share and bookmark the browser URL which includes the projectID and anon key with others to launch the same app. diff --git a/apps/reference/docs/guides/integrations/pgmustard.mdx b/apps/reference/docs/guides/integrations/pgmustard.mdx new file mode 100644 index 00000000000..6efbb242ef4 --- /dev/null +++ b/apps/reference/docs/guides/integrations/pgmustard.mdx @@ -0,0 +1,65 @@ +--- +id: pgmustard +title: 'pgMustard' +description: 'Troubleshoot slow queries on Supabase with pgMustard, a visualization tool that also gives advice.' +--- + +This guide explains how to troubleshoot slow queries on Supabase using `explain` and pgMustard. + +[pgMustard](https://pgmustard.com/) is a visualization tool for [`explain analyze`](https://www.postgresql.org/docs/current/using-explain.html#USING-EXPLAIN-ANALYZE) that also gives performance tips. + +## Step 1: Get the query plan from Supabase + +Use `explain analyze` to get a query plan from Postgres. This will run the query behind the scenes, so be careful with data modification queries. + +pgMustard requires plans to be in json format, and the buffers, verbose, and settings parameters allow it to give better tips. + +So a good prefix for your query would be: + +```jsx +explain (analyze, format json, buffers, verbose, settings) +``` + +Run the query, and copy the output. + +![01-supabase-run-query](/img/guides/integrations/pgmustard/01-supabase-run-query.png) + +If you’re using the Supabase SQL Editor, this is easily copied from the cell titled `QUERY PLAN`, as seen above. + +If you have any trouble, check out pgMustard’s guide for [getting a query plan](https://www.pgmustard.com/getting-a-query-plan). + +## Step 2: Paste the query plan into pgMustard + +Paste the json output into pgMustard and press Submit. + +![02-paste-plan-pgmustard](/img/guides/integrations/pgmustard/02-paste-plan-pgmustard.png) + +## Step 3: Look through the top tips and slowest operations + +Review the top tips in pgMustard. These are scored on a scale of 0 to 5 stars, based on how much time-saving potential they have (5 stars meaning lots of potential). + +![03-review-tips-pgmustard](/img/guides/integrations/pgmustard/03-review-tips-pgmustard.png) + +Click one of the tips, or one of the operations, to see more information. + +![04-click-tip-pgmustard](/img/guides/integrations/pgmustard/04-click-tip-pgmustard.png) + +## Step 4: Consider your options + +If you get some promising suggestions, you may wish to explore them. + +If you don’t get any tips, your query might be quite fast for the amount of work it’s doing. + +For the example we saw in Step 3, let's try adding an index on the `customer_name` field in Supabase. + +![05-create-index-supabase](/img/guides/integrations/pgmustard/05-create-index-supabase.png) + +Going through Steps 1-3 again, we now get an efficient index scan, that will scale nicely as our data grows. + +![06-check-pgmustard](/img/guides/integrations/pgmustard/06-check-pgmustard.png) + +We could look into why Postgres isn’t choosing to do an index-only scan here, but pgMustard is letting us know that it doesn’t think we’ll gain much by doing so, by scoring the tip 0.3 out of 5. + +## Resources +- [pgMustard](https://www.pgmustard.com) official website. +- [pgMustard explain glossary](https://www.pgmustard.com/docs/explain). diff --git a/apps/reference/docs/guides/integrations/plasmic.mdx b/apps/reference/docs/guides/integrations/plasmic.mdx new file mode 100644 index 00000000000..ac2e6f20b05 --- /dev/null +++ b/apps/reference/docs/guides/integrations/plasmic.mdx @@ -0,0 +1,299 @@ +--- +id: plasmic +title: 'Plasmic' +description: 'Get started with Supabase and Plasmic, an open-source framework for building internal tools.' +--- + +In this guide, we will show you how to build a crowd-sourced Pokemon Pokedex, by connecting **Supabase**, an open source Firebase backend alternative, with **Plasmic**, a visual builder for the web. While many users leverage Plasmic to quickly launch and iterate on landing pages, in this tutorial we’ll show just how powerful Plasmic can be as a general-purpose visual builder for React, which can be used to design and implement fully featured read-write applications. + +You can play with the live demo here: +[https://plasmic-supabase-demo.vercel.app/](https://plasmic-supabase-demo.vercel.app/) + +You can also take a look at the Plasmic project here: +[https://studio.plasmic.app/projects/66RKaSPCwKxYjCfXWHCxn6](https://studio.plasmic.app/projects/66RKaSPCwKxYjCfXWHCxn6) + +> You’ll need to enable 3rd-party cookies in your browser for the project to properly load. + +![pokedex-screenshot](/img/guides/integrations/plasmic/application-screenshot-00.png) + +At a high level, + +- **Supabase** is used to store the database of Pokemon (backed by Postgres) and provides an authentication backend. Our code base includes React components for querying the database, displaying this data, and supporting user sessions. +- **Plasmic** is used to create the pages and visual design of the application. We import our Supabase components into the Studio, which can be visually assembled and configured there (e.g. for displaying data). +- Plasmic designed pages are rendered back into the Next.js application. + +## Step 1: Set up your Backend on Supabase + +- On the [Supabase dashboard](https://app.supabase.com/), click `New project` and set the name of the project. +By default, Supabase will already be set up for user signups with email, with users being stored in a `users` table. + +![create-project-supabase](/img/guides/integrations/plasmic/create-project-supabase-01.png) + +- Navigate to the `Table Editor` on the left side navigation bar. Here we can create a `New table` to store our Pokemon entries. Make sure you are in the `schema public` view. Create a new table called `entries`, with 6 columns: + - `id`: is a unique ID for the entry. This column should be generated automatically as the primary column. + - `user_id`: Create a relation to the `user` table by clicking on the link icon next to the column name. Here, you can select the `id` column of the `user` table. + - `name`, `description`, `imageUrl`: This will store the name, description, and imageUrl for each Pokemon. + - `inserted_at` : This will be an automatically populated column, set to when the row was first inserted. + +> Note: In this tutorial we’ve turned off “[Row Level Security (RLS)](https://supabase.com/docs/guides/auth/row-level-security)”. In practice, you will want to create policies that restrict who gets to create, edit, and delete posts. By turning this off, any user can modify the database without restrictions. +> + +![create-table-supabase](/img/guides/integrations/plasmic/create-table-supabase-02.png) + +For your convenience, feel free to import the following CSV into Supabase to pre-populate your database. In order to import, you must select `Import data via spreadsheet`, in the new table dialog box. (It does not work on existing tables.) + +[pokedex-export.csv](/img/guides/integrations/plasmic/pokedex-export.csv) + +## Step 2: Set up your codebase + +We have a working code example for you [here](https://github.com/plasmicapp/plasmic/tree/master/examples/supabase-demo). This starter comes with all of the code components you need to get started querying Supabase through Plasmic Studio. + +> Code components are React components defined in your code base that we import into Plasmic Studio for use. Your project will be configured to look for these at `http://localhost:3000/plasmic-host` You can use these components in your design, as well as style them. Check out `supabase-demo/plasmic-init.ts` to see how they are registered with Plasmic. +> + +First, clone the repo to your development machine and install the dependencies. + +```bash +git clone git@github.com:plasmicapp/plasmic.git +cd plasmic/examples/supabase-demo/ +yarn install +``` + +Copy `.env.example` to `.env.local`, which will store the environment variables when running a local development server. Add your Supabase project’s URL and public key, which you can find in the `API` tab on the left pane of your Supabase dashboard. + +Now run the dev server, which listens at `http://localhost:3000` + +```bash +yarn dev +``` + +## Step 3: Explore the existing application + +Navigate to [http://localhost:3000](http://localhost:3000) in your web browser. The project will already be set up for user signups, logins, and an admin interface for adding and editing Pokemon to the database. Feel free to sign up with your email address for an account and add Pokemon to the database. Supabase will require that you verify your email address before you can log in. + +If you pre-populated the database in Step 1. you should see the following homepage after logging in. Otherwise, feel free to add Pokemon manually via the UI. + +![application-screenshot](/img/guides/integrations/plasmic/application-screenshot-03.png) + +## Step 4: Clone the Plasmic project + +Now let’s try to make some additions! The code base is currently configured to a read-only copy of the Plasmic project. Let’s make an editable copy first. + +Open the default starter Plasmic project here: +[https://studio.plasmic.app/projects/66RKaSPCwKxYjCfXWHCxn6](https://studio.plasmic.app/projects/66RKaSPCwKxYjCfXWHCxn6) + +![clone-project-plasmic](/img/guides/integrations/plasmic/clone-project-plasmic-04.png) + +To make an editable copy, click on the `Copy Project` button in the blue bar. This will clone the project and redirect you to your copy. + +### Step 4a: Configure your code base to use the new Plasmic project + +Take note of the `project ID` and `API token`. You can find the project ID in the URL: +`https://studio.plasmic.app/projects/PROJECTID`. + +The API token can be found by clicking the `Code` button in the top bar. + +![api-token-plasmic](/img/guides/integrations/plasmic/api-token-plasmic-05.png) + +Now go back to `.env.local` and update the corresponding project ID and token fields. + +### Step 4b: Configure your Plasmic project app host + +To tell Plasmic to look for your code components on your dev server, you’ll need to update your project’s app host to `http://localhost:3000/plasmic-host`. + +> Note: At this point, you’ll need to keep your dev server running at `http://localhost:3000`for the project to load. + + + +After restarting the dev server and Plasmic Studio, you should now be able to make edits across Plasmic Studio and your codebase. + +## Step 5: Create a new page for our Pokedex gallery + +Let’s make a visual gallery for our Pokemon by using the code components from the code base. + +Create a new page called `Gallery`, and set a path for this page (`/gallery`). + + + +Insert a `SupabaseGrid` by searching the AddDrawer (by clicking the blue + button) + +> For source see `components/CodeComponents/DatabaseComponents.tsx` +> + +![add-supabasegrid-plasmic](/img/guides/integrations/plasmic/add-supabasegrid-plasmic-07.png) + +Then in the right-hand panel, configure the props on `SupabaseGrid`. + +- `tableName` should match the table you created in Supabase +- `tableColumns` are a comma-delimited list of columns you want to select from the table +- We also set the number of columns and spacing shown in the grid + +![set-props-plasmic](/img/guides/integrations/plasmic/set-props-plasmic-08.png) + +The `SupabaseGrid` will loop over the rows from the query. + +Now customize the repeated content by inserting instances of `SupabaseField`. Select the type of content and a selector string to fetch a single value. In the example below, we use `{{row.imageUrl}}` to retrieve the `imageUrl` column of the row. Apply any styling and layout you want on these elements. + +![add-supabasefield-plasmic](/img/guides/integrations/plasmic/add-supabasefield-plasmic-09.png) + +### Putting it all together (video) + +For your convenience, the following video shows you how to create the page end-to-end. + + + +## Step 6: Check your dev server + +If you have been running your development server this whole time, you’ll see that we have been automatically fetching and rebuilding your site as you make changes in Plasmic Studio. If you need to restart your dev server, just run: + +```bash +yarn dev +``` + +See the results at `http://localhost:3000/gallery`. + +## How does this all work under the hood? + +### SupabaseGrid + +`SupabaseGrid` is a code component that was registered in `plasmic-init.ts`. The `props` field is used to tell the Plasmic Studio the component prop interface, which allows us to expose these props in the right pane as shown in the screenshots earlier. See the docs for details on [component registration](https://docs.plasmic.app/learn/registering-code-components/). + +```tsx +// plasmic-init.ts +... + +PLASMIC.registerComponent(SupabaseGrid, { + name: "SupabaseGrid", + props: { + tableName: "string", + tableColumns: "string", + queryFilters: "object", + children: { + type: "slot", + defaultValue: { + type: "text", + value: "Placeholder", + }, + }, + numColumns: { + type: "number", + defaultValue: 4, + }, + columnGap: { + type: "number", + defaultValue: 16, + }, + rowGap: { + type: "number", + defaultValue: 16, + }, + count: "number", + loading: { + type: "slot", + defaultValue: { + type: "text", + value: "Loading...", + }, + }, + }, + importPath: "./components/CodeComponents/DisplayCollections", +}); +``` + +### SupabaseQuery + +`SupabaseGrid` wraps a `SupabaseQuery` component, where we perform the query based on the provided props and store the result in a `SupabaseQueryContext`. This will be used in downstream components to display the data. + +```tsx +// supabase-demo/components/CodeComponents/DatabaseComponents.tsx +export function SupabaseQuery(props: SupabaseQueryProps) { + // These props are set in the Plasmic Studio + const { children, tableName, columns, className, filters, single } = props; + const [result, setResult] = React.useState(undefined); + +... + + // Performs the Supabase query + let query = supabase.from(tableName!).select(columns + ",id"); + query = applyFilter(query, validFilters, contexts); + const { data, error, status } = await (single ? query.single() : query.order('id', { ascending: false })); + + if (error && status !== 406) { + throw error; + } else if (data) { + setResult(data); + } + +... + + // Save the result in a `SupabaseQueryContext for use with downstream components + return ( +
+ + {children} + +
+ ); +} +``` + +Note that this code component is defined in your codebase. Feel free to augment it to expose more powerful querying capabilities to the Plasmic Studio. + +### SupabaseGridCollection + +`SupabaseGrid` also nests a `SupabaseGridCollection` under the `SupabaseQuery`. This code component is a simple CSS grid, where we retrieve the Supabase query results from `SupabaseQueryContext`, and iterate over the results. For each row, we populate a `RowContext`, which will be used by the children to read the results of a single row. Note the use of `repeatedElement`, a special convenience function that enables the component’s children to be repeated. In this case, this represents a single card to be shown in the gallery. + +```tsx +// supabase-demo/components/CodeComponents/DisplayCollections.tsx + +export function SupabaseGridCollection(props: SupabaseGridCollectionProps) { + const supabaseQuery = React.useContext(SupabaseQueryContext); + const { children, columns, columnGap, rowGap, count, className, loading, testLoading } = props; + + const result = supabaseQuery; + if (!result || testLoading) { + return loading; + } + + return ( +
+ {result.slice(0, count).map((row: any, i: any) => + +
{repeatedElement(i === 0, children)}
+
+ )} +
+ ) +} +``` + +### SupabaseField + +`SupabaseField` will either render a `SupabaseTextField` or `SupabaseImgField` depending on the type. These code components simply read a single value from the contexts and display the data. + +```tsx +// supabase-demo/components/CodeComponents/DisplayCollections.tsx + +export function SupabaseTextField({ name, className }: { name?: string; className?: string }) { + const contexts = useAllContexts(); + if (!name) { + return

You need to set the name prop

+ } + return
{getPropValue(name, contexts)}
; +} +``` + +In summary, by populating state into React contexts, we can store and retrieve data for use in other code components, which can be used for arbitrarily powerful interactions in Plasmic Studio. diff --git a/apps/reference/docs/guides/integrations/prisma.mdx b/apps/reference/docs/guides/integrations/prisma.mdx new file mode 100644 index 00000000000..7906190e07a --- /dev/null +++ b/apps/reference/docs/guides/integrations/prisma.mdx @@ -0,0 +1,177 @@ +--- +id: prisma +title: 'Prisma' +description: 'Connect your Supabase postgres database to your Prisma project.' +--- + +This guide explains how to quickly connect the Postgres database provided by Supabase to a Prisma project. + +[Prisma](https://prisma.io) is an [open source](https://github.com/prisma/prisma) next-generation ORM. It consists of the following parts: + +- **Prisma Client**: Auto-generated and type-safe query builder for Node.js & TypeScript. +- **Prisma Migrate**: Migration system. +- **Prisma Studio**: GUI to view and edit data in your database. + +## Step 1: Get the connection string from Supabase project settings + +Go to the settings page from the sidebar and navigate to the **Database** tab. You’ll find the database’s connection string with a placeholder for the password you provided when you created the project. +![Getting the connection string](/img/guides/integrations/prisma/zntcsh3ic91gf1gy8j73.png) + +## Step 2: Testing the connection + +To make sure that everything works correctly, let’s try the connection string in a Prisma project. + +If you already have one, all you need to do is set the `DATABASE_URL` to the connection string (including the password) in your `.env` file, and you’re good to go. + +In case you don’t have a Prisma project or this is your first time working with Prisma, you’re going to use the repo from the [quickstart](https://www.prisma.io/docs/getting-started/quickstart) guide. + +### Cloning the starter project + +Navigate into a directory of your choice and run the following command in your terminal if you’re on a Windows machine: + +```bash +curl https://pris.ly/quickstart -L -o quickstart-main.tar.gz && tar -zxvf quickstart-main.tar.gz quickstart-main/typescript/starter && move quickstart-main\typescript\starter starter && rmdir /S /Q quickstart-main && del /Q quickstart-main.tar.gz +``` + +And if you’re using Mac OS or Linux, run the following command: + +```bash +curl -L https://pris.ly/quickstart | tar -xz --strip=2 quickstart-main/typescript/starter +``` + +You can now navigate into the directory and install the project’s dependencies: + +```bash +cd starter && npm install +``` + +### A look at the project’s structure + +This project comes with TypeScript configured and has the following structure. + +- A `prisma` directory which contains: + - A `dev.db` file: This is a SQLite database. + - A `schema.prisma` file: Where we define the different database models and relations between them. +- A `.env` file: Contains the `DATABASE_URL` variable, which Prisma will use. +- A `script.ts` file: where we will run some queries using Prisma Client. + This starter also comes with the following packages installed: +- [`@prisma/client`](https://www.npmjs.com/package/@prisma/client): An auto-generated and type-safe query builder that’s _tailored_ to your data. +- [`prisma`](https://www.npmjs.com/package/prisma): Prisma’s command-line interface (CLI). It allows you to initialize new project assets, generate Prisma Client, and analyze existing database structures through introspection to automatically create your application models. + > Note: Prisma works with both JavaScript and TypeScript. However, to get the best possible development experience, using TypeScript is highly recommended. + +### Configuring the project to use PostgreSQL + +Go ahead and delete the `prisma/dev.db` file because we will be switching to PostgreSQL. +Next, inside the `prisma/.env` file, update the value of the `DATABASE_URL` variable to the connection string you got in **step 3**. The URL might look as follows: + +```env +# prisma/.env +postgres://postgres:[YOUR-PASSWORD]@db.vdbnhqozmlzdsaejdxwr.supabase.co:5432/postgres +``` + +Finally, inside your `schema.prisma` file, change the `provider` from “sqlite” to `“postgresql”`. +This is what your `schema.prisma` file should look like: + +```go +datasource db { + provider = “postgresql” + url = env(“DATABASE_URL”) +} +generator client { + provider = “prisma-client-js” +} +model Post { + id Int @id @default(autoincrement()) + title String + content String? + published Boolean @default(false) + author User? @relation(fields: [authorId], references: [id]) + authorId Int? +} +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] +} +``` + +To test that everything works correctly, run the following command to create a migration: + +```bash +prisma migrate dev --name init +``` + +You can optionally give your migration a name, depending on the changes you made. Since this is the project’s first migration, you’re setting the `--name` flag to “init”. +If everything works correctly, you should get the following message in your terminal: + +```text +Your database is now in sync with your schema. +:heavy_check_mark: Generated Prisma Client (2.x.x) to ./node_modules/@prisma/client in 111ms +``` + +This will create a `prisma/migrations` folder inside your `prisma` directory and synchronize your Prisma schema with your database schema. + +> Note: if you want to skip the process of creating a migration history, you can use the [`db push`](https://www.prisma.io/docs/concepts/components/prisma-migrate/db-push) command instead of `migrate dev`. +> If you go to your Supabase project, in the table editor, you should see that two tables have been created, a `Post` and a `User` table. +> ![tables created in the UI](/img/guides/integrations/prisma/7y4qq4wwvfrheti6r09u.png) +> That’s it! You have now successfully connected a Prisma project to a PostgreSQL database hosted on Supabase and ran your first migration. + +## Connection pooling with Supabase + +If you’re working in a serverless environment (for example Node.js functions hosted on AWS Lambda, Vercel or Netlify Functions), you need to set up [connection pooling](https://www.prisma.io/docs/guides/performance-and-optimization/connection-management#serverless-environments-faas) using a tool like [PgBouncer](https://www.pgbouncer.org/). That’s because every function invocation may result in a [new connection to the database](https://www.prisma.io/docs/guides/performance-and-optimization/connection-management#the-serverless-challenge). Supabase [supports connection management using PgBouncer](https://supabase.io/blog/2021/04/02/supabase-pgbouncer#what-is-connection-pooling) and are enabled by default. +Go to the **Database** page from the sidebar in the Supabase dashboard and navigate to **connection pool** settings +![Connection pool settings](/img/guides/integrations/prisma/w0oowg8vq435ob5c3gf0.png) +When running migrations you need to use the non pooled connection URL (like the one we used in **step 4**). However, when deploying your app, you’ll use the pooled connection URL and add the `?pgbouncer=true` flag to the PostgreSQL connection URL. To minimize the number of concurrent connections, setting the `connection_limit` to `1` is also recommended. So the URL might look as follows: + +```env +# prisma/.env +postgres://postgres:[YOUR-PASSWORD]@db.vdbnhqozmlzdsaejdxwr.supabase.co:6543/postgres?pgbouncer=true&connection_limit=1 +``` + +Prisma Migrate uses database transactions to check out the current state of the database and the migrations table. However, the Migration Engine is designed to use a single connection to the database, and does not support connection pooling with PgBouncer. If you attempt to run Prisma Migrate commands in any environment that uses PgBouncer for connection pooling, you might see the following error: + +```bash +Error: undefined: Database error +Error querying the database: db error: ERROR: prepared statement “s0” already exists +``` + +This is a known issue and it is being worked on, you can follow the progress on this [GitHub issue](https://github.com/prisma/prisma/issues/6485). +If you want to learn more about Prisma, check out the [docs](https://www.prisma.io/docs). Also in case you have any questions or run into any issue, feel free to start a discussion in the repo’s [discussions section](https://github.com/prisma/prisma/discussions). + +## Troubleshooting + +If you run `prisma migrate dev --name init` multiple times, it sometimes asks if you want to recreate the whole schema. If you chose yes, it will delete the public schema and recreates it. The default grants are missing after this. If you run into this problem, add a helper SQL for fixing the grants: + +```sql +CREATE SCHEMA IF NOT EXISTS "auth"; +CREATE SCHEMA IF NOT EXISTS "extensions"; +create extension if not exists "uuid-ossp" with schema extensions; +create extension if not exists pgcrypto with schema extensions; +create extension if not exists pgjwt with schema extensions; + +grant usage on schema public to postgres, anon, authenticated, service_role; +grant usage on schema extensions to postgres, anon, authenticated, service_role; +alter user supabase_admin SET search_path TO public, extensions; -- don't include the "auth" schema + +grant all privileges on all tables in schema public to postgres, anon, authenticated, service_role, supabase_admin; +grant all privileges on all functions in schema public to postgres, anon, authenticated, service_role, supabase_admin; +grant all privileges on all sequences in schema public to postgres, anon, authenticated, service_role, supabase_admin; + +alter default privileges in schema public grant all on tables to postgres, anon, authenticated, service_role; +alter default privileges in schema public grant all on functions to postgres, anon, authenticated, service_role; +alter default privileges in schema public grant all on sequences to postgres, anon, authenticated, service_role; + +alter default privileges for user supabase_admin in schema public grant all on sequences to postgres, anon, authenticated, service_role; +alter default privileges for user supabase_admin in schema public grant all on tables to postgres, anon, authenticated, service_role; +alter default privileges for user supabase_admin in schema public grant all on functions to postgres, anon, authenticated, service_role; + +alter role anon set statement_timeout = '3s'; +alter role authenticated set statement_timeout = '8s'; +``` + +## Resources + +- [Prisma](https://prisma.io) official website. +- [Prisma GitHub](https://github.com/prisma/prisma). +- [Prisma](https://www.prisma.io/docs/) documentation. diff --git a/apps/reference/docs/guides/integrations/snaplet.mdx b/apps/reference/docs/guides/integrations/snaplet.mdx new file mode 100644 index 00000000000..9770c01aed2 --- /dev/null +++ b/apps/reference/docs/guides/integrations/snaplet.mdx @@ -0,0 +1,114 @@ +--- +id: snaplet +title: 'Snaplet' +description: 'Get started with Supabase and Snaplet, a developer tool for working with safe, versioned, up-to-date production-like data' +--- + +This step-by-step guide explains how to use Snaplet to clone your production Supabase project into another development database. + +[Snaplet](https://snaplet.dev/) is a developer tool that copies a Postgres database, transforming personal information, so that you can **safely code against actual data.** This functionality makes it possible to easily achieve environment parity in Supabase. + +Let's get started! + +Follow along in the video below as the founder of Snaplet, Peter Pistorius, takes you through the entire process. Otherwise, you can skip the video and dive into the step-by-step guide. + + + +## Step 1: Prerequisites + +1. **A production Supabase project's connection string:** These can be found in Supabase via `Organization > Project > Database > Connection Pooling > Connection string` +2. **A development Supabase project's connection string:** Same steps as above, but a different project/environment +3. **A read-only role** in Production (recommended): This can be done by running the following statements on Supabase via `Organization > SQL Editor > + New Query` + +> To create a read-only role across all schemas you can checkout the Snaplet [docs](https://docs.snaplet.dev/postgresql/create-read-only-role) + +4. **Superuser access** for the development project. This can be done in Supabase via `Organization > SQL Editor > + New Query` and running this statement: + `ALTER USER postgres WITH superuser;` + +## Step 2: Copying your production database + +### 2.1. Connect your data source + +Navigate to [https://www.snaplet.dev/](https://www.snaplet.dev/) and sign up for a new account (it’s free). Once you have successfully signed up for a new account, create a team, and start by connecting to your Supabase project. + +![connect-your-database](/img/guides/integrations/snaplet/connect-your-database.png) + +Enter the credentials of your production Supabase project. Find the "Connection string" in Supabase via `Organization > Project > Settings > Database > Connection string` (at the bottom of the page). + +The password is the same password you used when creating the Supabase project. + +![supabase-connection-db-info](/img/guides/integrations/snaplet/supabase-connection-db-info.png) + +You’ll have to confirm providing Snaplet access to your database. Snaplet will prompt you to only provide `read-only` access to your database. Snaplet has a guide in their documentation on how to do so [here](https://docs.snaplet.dev/postgresql/create-read-only-role). + +> Note that whatever connection string you provide here will be that of your Data Source – essentially the production database in a real-life scenario + +![checking-database-credentials](/img/guides/integrations/snaplet/checking-database-credentials.png) + +### 2.2. Transform your data + +![transform-your-data](/img/guides/integrations/snaplet/transform-your-data.png) + +The next step is to exclude any schemas that you do not require. You are able to exclude an entire schema by clicking on the drop-down at the top, selecting the schema you would like to exclude and clicking ‘Exclude schema’. Alternatively, you can select a given schema and exclude only specific tables from that particular schema. Exclude any non-required table data (such as logs) and extensions and view your columns. + +At this point, Snaplet will automatically detect any columns that have Personally Identifiable Information (PII) and mark them in purple. If there are any additional columns that hold data you would like to anonymise, you can click on the respective column name and provide a replacement value for the data in that column. To complete the onboarding, click on `Review and Save` and proceed to the dashboard. + +![create-your-first-snapshot](/img/guides/integrations/snaplet/create-your-first-snapshot.png) + +### 2.3. Create a Snapshot + +Create a snapshot of your production database. This is what you’re going to restore later into your data target (more on that later in the guide). + +## Step 3: Pasting into your development database + +### 3.1. Create a data target on Supabase + +Your data target is where you want Snaplet to restore the captured snapshot of your production project. This would most likely be either your staging or developer Supabase project. If you don’t already have a developer database setup on Supabase, create a new data target by setting up a new project on Supabase. To create a new project, follow the steps below: + +1. Go to [app.supabase.com](https://app.supabase.com/) +2. Click on “new project” +3. Enter your project details +4. Wait for the new database to launch + +> Remember the password you use when creating the project. You’ll need this password to connect your database to Snaplet later. + +### 3.2. Make your `postgres` user a superuser + +Snaplet requires the ability to drop the database schemas whilst restoring a snapshot. In order to do that, Snaplet requires `superuser` privileges. + +1. Navigate to the `SQL Editor` in your Supabase console +2. Click on `new query` +3. Paste `alter user postgres with superuser;` into the SQL editor +4. Run the query + +### 3.3. Install the Snaplet CLI + +1. Open your terminal and run `curl -sL https://app.snaplet.dev/get-cli/ | bash` +2. Run `snaplet auth` +3. Navigate to [https://app.snaplet.dev/access-token/cli](https://app.snaplet.dev/access-token/cli) to get your access token +4. Paste your access token in the terminal + +### 3.4. Restore to the data target + +You're now ready to restore your production snapshot into your Supabase development project. + +1. Navigate to your project directory +2. Run `snaplet setup` – you will be prompted to enter your database credentials. These are the database credentials of your **data target.** This could be your staging or development database + +Once completed, you will be presented with a list of databases that are connected to your Snaplet account. + +1. Select a data source from the list +2. Run `snaplet snapshot restore` + +## All done! + +As a Supabase user, you can see how this solves an issue developers all typically experience when attempting to create multiple development environments and populating each of those environments with data that can be worked with. Snaplet simplifies this process down to creating the respective Supabase projects, connecting the data source (The production database) to Snaplet and telling Snaplet where to restore that data (staging and development databases). + +If you want to learn more about Snaplet, you can explore the Snaplet [docs](https://docs.snaplet.dev/). If you have any questions, feel free to [reach out on Discord](https://discord.com/invite/6HUuajc866). diff --git a/apps/reference/docs/guides/integrations/stytch.mdx b/apps/reference/docs/guides/integrations/stytch.mdx new file mode 100644 index 00000000000..20a68ddb093 --- /dev/null +++ b/apps/reference/docs/guides/integrations/stytch.mdx @@ -0,0 +1,656 @@ +--- +id: stytch +title: 'Stytch' +description: "Build a Next.js application powered by password-less authentication from Stytch, and Supabase's Row Level Security (RLS)." +--- + +In this guide we will build a simple expense tracker web application using Stytch, Supabase, and Next.js. + +[Stytch](https://stytch.com?utm_source=supabase&utm_medium=guide) provides an all-in-one platform for passwordless auth. Stytch makes it easy for you to embed passwordless solutions into your websites and apps for better security, better conversion rates, and a better end user experience. Their easy-to-use SDKs and direct API access allows for maximum control and customization. In this example we will use [Email magic links](https://stytch.com/products/email-magic-links?utm_source=supabase&utm_medium=guide) to create and log in our users, and Session management. There is an additional, optional step to enable [Google One Tap](https://stytch.com/blog/improving-conversion-with-google-one-tap?utm_source=supabase&utm_medium=guide) which is an especially high-converting Google OAuth sign-up and login flow. + +We will leverage Supabase to store and authorize access to user data. Supabase makes it simple to set up Row Level Security (RLS) policies which ensure users can only read and write data that they are authorized to do so. If you do not already have a Supabase account, you will need to create one. + +This guide will use [Next.js](https://nextjs.org/) which is a web application framework built on top of React. Stytch provides a [Node.js library](https://github.com/stytchauth/stytch-node) and a [React library](https://github.com/stytchauth/stytch-react) which makes building Next.js apps super easy. + +> Note: You can find a completed version of this project on [Github](https://github.com/stytchauth/stytch-nextjs-supabase). + +## Step 0: Create a Stytch Account + +If you already have a Stytch account you may skip this step. + +Go to [Stytch](https://stytch.com?utm_source=supabase&utm_medium=guide), and create an account. Note that Stytch provides two ways to create an account, either via Google OAuth, or through Email magic links.  This is the same user experience we will be building in this guide! + +![Stytch redirect URL settings](/img/guides/integrations/stytch/01.png) + +## Step 1: Set up Stytch redirect URLs + +First we need to add the redirect URLs that will be used during the Email magic link flow. This step helps ensure bad actors cannot spoof your magic links and hijack redirects. + +Navigate to your [redirect URL settings](https://stytch.com/dashboard/redirect-urls?utm_source=supabase&utm_medium=guide) in the Stytch dashboard, and under **Test environment** create an entry where the **URL** is `http://localhost:3000/api/authenticate` and the **Type** is `All`. + +![Edit Stytch redirect URL settings](/img/guides/integrations/stytch/02.png) + +After pressing **Confirm**, the redirect URLs dashboard will update to show your new entry. We will use this URL later on. + +![Stytch redirect URL settings](/img/guides/integrations/stytch/03.png) + +## Step 2: Create a Supabase project + +From your [Supabase dashboard](https://app.supabase.com/), click **New project**. + +Enter a `Name` for your Supabase project. + +Enter a secure `Database Password`. + +Click **Create new project**. It may take a couple minutes for your project to be provisioned. + +![New Supabase project settings](/img/guides/integrations/stytch/04.png) + +## Step 3: Creating data in Supabase + +Once your Supabase project is provisioned, click Table editor, then New table. This tool is available from the sidebar menu in the [Supabase dashboard](https://app.supabase.com/). + +Enter `expenses` as the **Name** field. + +Select `Enable Row Level Security (RLS)`. + +Add three new columns: + +- `user_id` as `text` + +- `title` as `text` + +- `value` as `float8` + +Click **Save** to create the new table. + +![Creating a new table](/img/guides/integrations/stytch/05.png) + +From the Table editor view, select the expenses table and click **Insert row**. + +Fill out the title and value fields (leave user_id blank for now) and click **Save**. + +![Creating a new row](/img/guides/integrations/stytch/06.png) + +Use **Insert Row** to further populate the table with expenses. + +![Multiple rows](/img/guides/integrations/stytch/07.png) + +## Step 4: Building a Next.js app + +Using a terminal, create a new Next.js project: + +```bash +npx create-next-app stytch-supabase-example +``` + +Next, within `stytch-supabase-example` create a `.env.local` file and enter the following values: + +``` +STYTCH_PROJECT_ENV=test +STYTCH_PROJECT_ID=GET_FROM_STYTCH_DASHBOARD +STYTCH_PUBLIC_TOKEN=GET_FROM_STYTCH_DASHBOARD +STYTCH_SECRET=GET_FROM_STYTCH_DASHBOARD +NEXT_PUBLIC_SUPABASE_URL=GET_FROM_SUPABASE_DASHBOARD +NEXT_PUBLIC_SUPABASE_KEY=GET_FROM_SUPABASE_DASHBOARD +SUPABASE_SIGNING_SECRET=GET_FROM_SUPABASE_DASHBOARD +``` + +> Note: Stytch values can be found in the project [dashboard](https://stytch.com/dashboard/api-keys?utm_source=supabase&utm_medium=guide) under **API Keys**. + +![Stytch API keys](/img/guides/integrations/stytch/08.png) + +> Note: Supabase values can be found under **Settings** > **API** for your project. + +![Supabase API keys](/img/guides/integrations/stytch/09.png) + +Start your Next.js development server to read in the new values from `.env.local`. + +```bash +npm run dev +``` + +You should have a running Next.js application on `localhost:3000`. + +## Step 5: Build the Login Form + +Now we will replace the default Next.js home page with a login UI. We will use the Stytch React library. + +> Note: Stytch provides direct API access for those that want to build login UI themselves + +Install the `@stytch/stytch-react` library. + +```bash +npm install @stytch/stytch-react +``` + +In the root directory, create a new folder named `components` and file in that folder named `/StytchLogin.js`. Within this file, paste the snippet below. This will configure, and style the Stytch React component to use Email magic links. + +```jsx +// components/StytchLogin.js +import React from 'react' +import { Stytch } from '@stytch/stytch-react' + +const stytchConfig = { + loginOrSignupView: { + products: ['emailMagicLinks'], + emailMagicLinksOptions: { + loginRedirectURL: 'http://localhost:3000/api/authenticate', + loginExpirationMinutes: 30, + signupRedirectURL: 'http://localhost:3000/api/authenticate', + signupExpirationMinutes: 30, + createUserAsPending: true, + }, + }, + style: { + fontFamily: '"Helvetica New", Helvetica, sans-serif', + width: '321px', + primaryColor: '#0577CA', + }, +} + +const StytchLogin = ({ publicToken }) => { + return ( + + ) +} + +export default StytchLogin +``` + +Additionally, create a profile component by creating a file called `Profile.js` in `/components`. We will use this component to render our expenses stored in Supabase later on. + +```jsx +// components/Profile.js +import React from 'react' +import Link from 'next/link' + +export default function Profile({ user }) { + return ( +
+

Welcome {user.userId}

+

Your expenses

+ {user.expenses?.length > 0 ? ( + user.expenses.map((expense) => ( +

+ {expense.title}: ${expense.value} +

+ )) + ) : ( +

You have no expenses!

+ )} + + + + +
+ ) +} +``` + +Finally, replace the contents of the file `/pages/index.js` to render our new `StytchLogin` and `Profile` components. + +```jsx +// pages/index.js +import styles from '../styles/Home.module.css' +import Profile from '../components/Profile' +import StytchLogin from '../components/StytchLogin' + +const Index = ({ user, publicToken }) => { + let content + if (user) { + content = + } else { + content = + } + + return
{content}
+} + +export async function getServerSideProps({ req, res }) { + const user = null // Will update later + return { + props: { user, publicToken: process.env.STYTCH_PUBLIC_TOKEN }, + } +} + +export default Index +``` + +On `localhost:3000` there is now a login form prompting for your email address. + +![Email login step one](/img/guides/integrations/stytch/10.png) + +Enter your email address and press **Continue with email**. + +![Email login step two](/img/guides/integrations/stytch/11.png) + +In your inbox you will find a login request from your app. + +![Email login step three](/img/guides/integrations/stytch/12.png) + +However, if you click the link in the email you will get a 404. We need to build an API route to handle the email magic link authentication. + +## Step 6: Authenticate and start a session + +To make authentication easier we will use the Stytch Node.js library. Run + +```bash +npm install stytch +``` + +Additionally, we will need to store the authenticated session in a cookie. Run + +```bash +npm install cookies-next +``` + +Create a new folder named `utils` and inside a file named`stytchLogic.js` with the following contents + +```jsx +// utils/stytchLogic.js +import * as stytch from 'stytch' +import { getCookie, setCookies, removeCookies } from 'cookies-next' + +export const SESSION_COOKIE = 'stytch_cookie' + +let client +const loadStytch = () => { + if (!client) { + client = new stytch.Client({ + project_id: process.env.STYTCH_PROJECT_ID, + secret: process.env.STYTCH_SECRET, + env: process.env.STYTCH_PROJECT_ENV === 'live' ? stytch.envs.live : stytch.envs.test, + }) + } + + return client +} + +export const getAuthenticatedUserFromSession = async (req, res) => { + const sessionToken = getCookie(SESSION_COOKIE, { req, res }) + if (!sessionToken) { + return null + } + + try { + const stytchClient = loadStytch() + const resp = await stytchClient.sessions.authenticate({ + session_token: sessionToken, + }) + return resp.session.user_id + } catch (error) { + console.log(error) + return null + } +} + +export const revokeAndClearSession = async (req, res) => { + const sessionToken = getCookie(SESSION_COOKIE, { req, res }) + + if (sessionToken) { + try { + const stytchClient = loadStytch() + await stytchClient.sessions.revoke({ + session_token: sessionToken, + }) + } catch (error) { + console.log(error) + } + removeCookies(SESSION_COOKIE, { req, res }) + } + + return res.redirect('/') +} + +export const authenticateTokenStartSession = async (req, res) => { + const { token, type } = req.query + let sessionToken + try { + const stytchClient = loadStytch() + const resp = await stytchClient.magicLinks.authenticate(token, { + session_duration_minutes: 30, + }) + sessionToken = resp.session_token + } catch (error) { + console.log(error) + const errorString = JSON.stringify(error) + return res.status(400).json({ errorString }) + } + + setCookies(SESSION_COOKIE, sessionToken, { + req, + res, + maxAge: 60 * 60 * 24, + secure: true, + }) + + return res.redirect('/') +} +``` + +This logic is responsible for setting up the Stytch client we will use to call the API. It provides functions we will use to login, logout, and validate user sessions. + +In order to complete the email login flow, create a new file `pages/api/authenticate.js` with the contents: + +```jsx +// pages/api/authenticate.js +import { authenticateTokenStartSession } from '../../utils/stytchLogic' + +export default async function handler(req, res) { + return authenticateTokenStartSession(req, res) +} +``` + +We will also create a logout API endpoint with similar contents. In `pages/api/logout.js` include the following: + +```jsx +// pages/api/logout.js +import { revokeAndClearSession } from '../../utils/stytchLogic' + +export default async function handler(req, res) { + return revokeAndClearSession(req, res) +} +``` + +Finally, update `pages/index.js` by importing `getAuthenticatedUserFromSession`, and calling it to set the user variable in `getServerSideProps`. + +```jsx +// pages/index.js +import styles from '../styles/Home.module.css' + +import StytchLogin from '../components/StytchLogin' +import Profile from '../components/Profile' +import { getAuthenticatedUserFromSession } from '../utils/stytchLogic' + +const Index = ({ user, publicToken }) => { + let content + if (user) { + content = + } else { + content = + } + + return
{content}
+} + +export async function getServerSideProps({ req, res }) { + const userId = await getAuthenticatedUserFromSession(req, res) + if (userId) { + return { + props: { user: { userId }, publicToken: process.env.STYTCH_PUBLIC_TOKEN }, + } + } + return { + props: { publicToken: process.env.STYTCH_PUBLIC_TOKEN }, + } +} + +export default Index +``` + +Return to `localhost:3000`, and login again by sending yourself a new email. Upon clicking through in the email you should be presented with “Welcome $USER_ID”. If you refresh the page, you should remain in an authenticated state. If you press **Logout** then you should return to the login screen. + +![Profile page](/img/guides/integrations/stytch/13.png) + +Now that we have a working login flow with persistent authentication it is time to pull in our expense data from Supabase. + +## Step 7: Requesting user data from Supabase + +First, install the Supabase client: + +```bash +npm install @supabase/supabase-js +``` + +In order to pass an authenticated `user_id` to Supabase we will package it within a JWT. Install jsonwebtoken: + +```bash +npm install jsonwebtoken +``` + +Create a new file `utils/supabase.js` and add the following: + +```jsx +// utils/supabase.js +import { createClient } from '@supabase/supabase-js' +import jwt from 'jsonwebtoken' + +const getSupabase = (userId) => { + const supabase = createClient( + process.env.NEXT_PUBLIC_SUPABASE_URL, + process.env.NEXT_PUBLIC_SUPABASE_KEY + ) + + if (userId) { + const payload = { + userId, + exp: Math.floor(Date.now() / 1000) + 60 * 60, + } + + supabase.auth.session = () => ({ + access_token: jwt.sign(payload, process.env.SUPABASE_SIGNING_SECRET), + }) + } + + return supabase +} + +export { getSupabase } +``` + +Our payload for the JWT will contain our user's unique identifier from Stytch, their `user_id`. We are signing this JWT using Supabase's signing secret, so Supabase will be able to validate it is authentic and hasn't been tampered with in transit. + +Let's load our expenses from Supabase on the home page! Update `pages/index.js` a final time to make a request for expense data from Supabase. + +```jsx +import styles from '../styles/Home.module.css' + +import StytchLogin from '../components/StytchLogin' +import Profile from '../components/Profile' +import { getAuthenticatedUserFromSession } from '../utils/stytchLogic' +import { getSupabase } from '../utils/supabase' + +const Index = ({ user, publicToken }) => { + let content + if (user) { + content = + } else { + content = + } + + return
{content}
+} + +export async function getServerSideProps({ req, res }) { + const userId = await getAuthenticatedUserFromSession(req, res) + + if (userId) { + const supabase = getSupabase(userId) + const { data: expenses } = await supabase.from('expenses').select('*') + + return { + props: { + user: { userId, expenses }, + publicToken: process.env.STYTCH_PUBLIC_TOKEN, + }, + } + } else { + return { + props: { publicToken: process.env.STYTCH_PUBLIC_TOKEN }, + } + } +} + +export default Index +``` + +When we reload our application, we are still getting the empty state for expenses. + +This is because we enabled Row Level Security, which blocks all requests by default and lets you granularly control access to the data in your database. To enable our user to select their expenses we need to write a RLS policy. + +## Step 8: Write a policy to allow select + +Our policy will need to know who our currently logged in user is to determine whether or not they should have access. Let's create a PostgreSQL function to extract the current user from our new JWT. + +Navigate back to the Supabase dashboard, select SQL from the sidebar menu, and click **New query**. This will create a new query,, which will allow us to run any SQL against our Postgres database. + +Write the following and click **Run**. + +```sql +create or replace function auth.user_id() returns text as $$ + select nullif(current_setting('request.jwt.claims', true)::json->>'userId', '')::text; +$$ language sql stable; +``` + +You should see the output `Success, no rows returned`. This created a function called `auth.user_id()`, which will inspect the `userId` field of our JWT payload. + +> Note: To learn more about PostgreSQL functions, check out this [deep dive video](https://www.youtube.com/watch?v=MJZCCpCYEqk). + +Let's create a policy that checks whether this user is the owner of an expense. + +Select **Authentication** from the Supabase sidebar menu, click **Policies**, then **New Policy**. + +![Supabase authentication page](/img/guides/integrations/stytch/14.png) + +From the modal, select **For full customization create a policy from scratch** and add the following. + +![Supabase create policy page](/img/guides/integrations/stytch/15.png) + +This policy is calling the function we just created to get the currently logged in user's `user_id` `auth.user_id()` and checking whether this matches the `user_id` column for the current expense. If it does, then it will allow the user to select it, otherwise it will continue to deny. + +Click Review and then Save policy. After you've saved, click Enable RLS on the table to enable the policy we just created. + +> Note: To learn more about RLS and policies, check out this [video](https://www.youtube.com/watch?v=Ow_Uzedfohk). + +The last thing we need to do is update the `user_id` columns for our existing expenses. + +Head back to the Supabase dashboard, and select Table editor from the sidebar. You will notice each entry has `user_id` set to `NULL`. We need to update this value to the proper `user_id`. + +![Supabase null users in table](/img/guides/integrations/stytch/16.png) + +To get the `user_id` for our Stytch user, you can pull it from the welcome page in our example app (eg `user-test-61497d40-f957-45cd-a6c8-5408d22e93bc`). + +![Get user_id](/img/guides/integrations/stytch/17.png) + +Update each row in Supabase to this `user_id`. + +![Populate user_id](/img/guides/integrations/stytch/18.png) + +Return to `localhost:3000`, and you will see your expenses listed. + +![Listed expenses](/img/guides/integrations/stytch/19.png) + +We now have a basic expense tracker application powered by Stytch, Supabase, and Next.js. From here you could add additional features like adding, editing, and organizing your expenses further. + +> Note: You can find a completed version of this project on [Github](https://github.com/stytchauth/stytch-nextjs-supabase). + +## Optional: Add Google One Tap + +In this optional step, we will extend our application to allow users to login with Google One Tap in addition to Email magic links. + +You will need to follow the first four steps of [this guide](https://stytch.com/docs/one-tap-guide?utm_source=supabase&utm_medium=guide) to create a Google project, set up Google OAuth consent, and configure credentials and redirect URLs. + +First, we will make some adjustments to the `StytchLogin` component. We will update the configuration, so that it uses both Google OAuth, and Email magic links. + +```jsx +// components/StytchLogin.js +import React from 'react' +import { Stytch } from '@stytch/stytch-react' + +const stytchConfig = { + loginOrSignupView: { + products: ['oauth', 'emailMagicLinks'], + oauthOptions: { + providers: [ + { + type: 'google', + one_tap: true, + position: 'embedded', + }, + ], + loginRedirectURL: 'http://localhost:3000/api/authenticate?type=oauth', + signupRedirectURL: 'http://localhost:3000/api/authenticate?type=oauth', + }, + emailMagicLinksOptions: { + loginRedirectURL: 'http://localhost:3000/api/authenticate', + loginExpirationMinutes: 30, + signupRedirectURL: 'http://localhost:3000/api/authenticate', + signupExpirationMinutes: 30, + createUserAsPending: true, + }, + }, + style: { + fontFamily: '"Helvetica New", Helvetica, sans-serif', + width: '321px', + primaryColor: '#0577CA', + }, +} + +const StytchLogin = ({ publicToken }) => { + return ( + + ) +} + +export default StytchLogin +``` + +We also need to make an adjustment to the function `authenticateTokenStartSession` in `stytchLogic.js`. Stytch has separate authentication endpoints for Email magic links and OAuth, so we need to route our token correctly. + +```jsx +// utils/stytchLogic.js + +// leave the rest of the file contents as is +export const authenticateTokenStartSession = async (req, res) => { + const { token, type } = req.query + let sessionToken + try { + const stytchClient = loadStytch() + if (type == 'oauth') { + const resp = await stytchClient.oauth.authenticate(token, { + session_duration_minutes: 30, + session_management_type: 'stytch', + }) + sessionToken = resp.session.stytch_session.session_token + } else { + const resp = await stytchClient.magicLinks.authenticate(token, { + session_duration_minutes: 30, + }) + sessionToken = resp.session_token + } + } catch (error) { + console.log(error) + const errorString = JSON.stringify(error) + return res.status(400).json({ errorString }) + } + + setCookies(SESSION_COOKIE, sessionToken, { + req, + res, + maxAge: 60 * 60 * 24, + secure: true, + }) + + return res.redirect('/') +} +``` + +With these two changes you will now have a working Google One Tap authentication method along with email magic links. + +![Google One Tap](/img/guides/integrations/stytch/20.png) + +## Resources + +- [Stytch blog](https://stytch.com/blog?utm_source=supabase&utm_medium=guide) +- [Stytch documentation](https://stytch.com/docs?utm_source=supabase&utm_medium=guide) diff --git a/apps/reference/docs/guides/integrations/supertokens.mdx b/apps/reference/docs/guides/integrations/supertokens.mdx new file mode 100644 index 00000000000..61e34821798 --- /dev/null +++ b/apps/reference/docs/guides/integrations/supertokens.mdx @@ -0,0 +1,399 @@ +--- +id: supertokens +title: 'SuperTokens' +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. + +In this guide we will build a simple web application using SuperTokens, Supabase, and Next.js. You will be able to sign up using SuperTokens and your email and user ID will be stored in Supabase. Once authenticated the frontend will be able to query Supabase and retrieve the user's email. Our example app will be using the [Email-Password and Social Login](https://supertokens.com/docs/thirdpartyemailpassword/introduction) recipe for authentication and session management. + +We 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) + +## Step 1: Create a new Supabase project + +From your [Supabase dashboard](https://app.supabase.com/), 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. + +Click `Create new project`. + +![New Supabase project settings](/img/guides/integrations/supertokens/supabase_dashboard_create.png) + +## Step 2: Creating tables in Supabase + +From the sidebar menu in the [Supabase dashboard](https://app.supabase.com/), click `Table editor`, then `New table`. + +Enter `users` as the `Name` field. + +Select `Enable Row Level Security (RLS)`. + +Remove the default columns + +Create two new columns: + +- `user_id` as `varchar` as primary key +- `email` as `varchar` + +Click `Save` to create the new table. + +![Users table](/img/guides/integrations/supertokens/supabase_table_create.png) + +## 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 + +![SuperTokens Auth Screen](/img/guides/integrations/supertokens/supertokens_thirdpartyemailpassword_auth_screen.png) + +## Step 4: Creating a Supabase JWT to access Supabase + +In 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 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. + +```ts +// config/backendConfig.ts + +import ThirdPartyEmailPasswordNode from "supertokens-node/recipe/thirdpartyemailpassword"; +import SessionNode from "supertokens-node/recipe/session"; +import { TypeInput } from "supertokens-node/lib/build/types"; +import { appInfo } from "./appInfo"; +import jwt from "jsonwebtoken"; + +let backendConfig = (): TypeInput => { + return { + framework: "express", + supertokens: { + connectionURI: "https://try.supertokens.com", + }, + appInfo, + recipeList: [ + ThirdPartyEmailPasswordNode.init({...}), + SessionNode.init({ + override: { + functions: (originalImplementation) => { + return { + ...originalImplementation, + // We want to create a JWT which contains the users userId signed with Supabase's secret so + // it can be used by Supabase to validate the user when retrieving user data from their service. + // We store this token in the accessTokenPayload so it can be accessed on the frontend and on the backend. + createNewSession: async function (input) { + const payload = { + userId: input.userId, + exp: Math.floor(Date.now() / 1000) + 60 * 60, + }; + + const supabase_jwt_token = jwt.sign(payload, process.env.SUPABASE_SIGNING_SECRET); + + input.accessTokenPayload = { + ...input.accessTokenPayload, + supabase_token: supabase_jwt_token, + }; + + return await originalImplementation.createNewSession(input); + }, + }; + }, + }, + }), + ], + isInServerlessEnv: true, + }; +}; + +``` + +As seen above, we will be using the `jsonwebtoken` library to create a JWT signed with Supabase's signing secret whose payload contains the user's userId. + +We 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 + +Create a new file called `utils/supabase.ts` and add the following: + +```ts +// utils/supabase.ts + +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 + ) + + supabase.auth.session = () => ({ + access_token, + }) + + return supabase +} + +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. + +## Step 6: Inserting users into Supabase when they sign up: + +In our example app there are two ways for signing up a user. Email-Password and Social Login based authentication. We will need to override both these APIs such that when a user signs up, their email mapped to their userId is stored in Supabase. + +```ts +// config/backendConfig.ts + +import ThirdPartyEmailPasswordNode from "supertokens-node/recipe/thirdpartyemailpassword"; +import SessionNode from "supertokens-node/recipe/session"; +import { TypeInput } from "supertokens-node/lib/build/types"; +import { appInfo } from "./appInfo"; +import jwt from "jsonwebtoken"; +import { getSupabase } from "../utils/supabase"; + +let backendConfig = (): TypeInput => { + return { + framework: "express", + supertokens: { + connectionURI: "https://try.supertokens.com", + }, + appInfo, + recipeList: [ + ThirdPartyEmailPasswordNode.init({ + providers: [...], + override: { + apis: (originalImplementation) => { + return { + ...originalImplementation, + // the thirdPartySignInUpPost function handles sign up/in via Social login + thirdPartySignInUpPOST: async function (input) { + if (originalImplementation.thirdPartySignInUpPOST === undefined) { + throw Error("Should never come here"); + } + + // call the sign up/in api for social login + let response = await originalImplementation.thirdPartySignInUpPOST(input); + + // check that there is no issue with sign up and that a new user is created + if (response.status === "OK" && response.createdNewUser) { + + // retrieve the accessTokenPayload from the user's session + const accessTokenPayload = response.session.getAccessTokenPayload(); + + // create a supabase client with the supabase_token from the accessTokenPayload + const supabase = getSupabase(accessTokenPayload.supabase_token); + + // store the user's email mapped to their userId in Supabase + const { error } = await supabase + .from("users") + .insert({ email: response.user.email, user_id: response.user.id }); + + if (error !== null) { + + throw error; + } + } + + return response; + }, + // the emailPasswordSignUpPOST function handles sign up via Email-Password + emailPasswordSignUpPOST: async function (input) { + if (originalImplementation.emailPasswordSignUpPOST === undefined) { + throw Error("Should never come here"); + } + + let response = await originalImplementation.emailPasswordSignUpPOST(input); + + if (response.status === "OK") { + + // retrieve the accessTokenPayload from the user's session + const accessTokenPayload = response.session.getAccessTokenPayload(); + + // create a supabase client with the supabase_token from the accessTokenPayload + const supabase = getSupabase(accessTokenPayload.supabase_token); + + // store the user's email mapped to their userId in Supabase + const { error } = await supabase + .from("users") + .insert({ email: response.user.email, user_id: response.user.id }); + + if (error !== null) { + + throw error; + } + } + + return response; + }, + }; + }, + }, + }), + SessionNode.init({...}), + ], + isInServerlessEnv: true, + }; +}; + +``` + +As seen above, we will be overriding the `emailPasswordSignUpPOST` and `thirdPartySignInUpPOST` APIs such that if a user signs up, we retrieve the Supabase JWT (which we created in the `createNewSession` function) from the user's accessTokenPayload and send a request to Supabase to insert the email-userid mapping. + +## Step 7: Retrieving the user's email on the frontend + +Now that our backend is setup we can modify our frontend to retrieve the user's email from Supabase. + +```tsx +// pages/index.tsx + +import React, { useState, useEffect } from 'react' +import Head from 'next/head' +import styles from '../styles/Home.module.css' +import ThirdPartyEmailPassword, { + ThirdPartyEmailPasswordAuth, +} from "supertokens-auth-react/recipe/thirdpartyemailpassword"; +import dynamic from 'next/dynamic' +import { useSessionContext } from 'supertokens-auth-react/recipe/session' +import { getSupabase } from '../utils/supabase' + +export default function Home() { + return ( + // We will wrap the ProtectedPage component with ThirdPartyEmailPasswordAuth so only an + // authenticated user can access it. This will also allow us to access the users session information + // within the component. + + + + ) +} + +function ProtectedPage() { + // retrieve the authenticated user's accessTokenPayload and userId from the sessionContext + const { accessTokenPayload, userId } = useSessionContext() + + if (sessionContext.loading === true) { + return null; + } + + 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 ( +
+ + SuperTokens 💫 + + + +
+

+ You are authenticated with SuperTokens! (UserId: {userId}) +
+ Your email retrieved from Supabase: {userEmail} +

+
+
+ ) +} +``` + +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 requests + +To 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 + +To do this we will need a PostgreSQL function to extract the userId from the JWT. + +The payload in the JWT will have the following structure: + +``` +// JWT payload +{ + userId, + exp +} +``` + +To create the PostgreSQL function, lets navigate back to the Supabase dashboard, select `SQL` from the sidebar menu, and click `New query`. This will create a new query called `new sql snippet`, which will allow us to run any SQL against our Postgres database. + +Write the following and click `Run`. + +```sql +create or replace function auth.user_id() returns text as $$ + select nullif(current_setting('request.jwt.claims', true)::json->>'userId', '')::text; +$$ language sql stable; +``` + +This will create a function called `auth.user_id()`, which will inspect the `userId` field of our JWT payload. + +### SELECT query policy + +Our first policy will check whether the user is the owner of the email. + +Select `Authentication` from the Supabase sidebar menu, click `Policies`, and then `New Policy` on the `Users` table. + +![Create new policy](/img/guides/integrations/supertokens/create_policy.png) + +From the modal, select `Create a policy from scratch` and add the following. + +![Policy settings for SELECT](/img/guides/integrations/supertokens/policy_config_select.png) + +This policy is calling the PostgreSQL function we just created to get the currently logged in user's ID `auth.user_id()` and checking whether this matches the `user_id` column for the current `email`. If it does, then it will allow the user to select it, otherwise it will continue to deny. + +Click `Review` and then `Save policy`. + +### INSERT query policy + +Our second policy will check whether the `user_id` being inserted is the same as the `userId` in the JWT. + +Create another policy and add the following: + +![Policy settings for INSERT](/img/guides/integrations/supertokens/policy_config_insert.png) + +Similar to the previous policy we are calling the PostgreSQL function we created to get the currently logged in user's ID `auth.user_id()` and check whether this matches the `user_id` column for the row we are trying to insert. If it does, then it will allow the user to insert the row, otherwise it will continue to deny. + +Click `Review` and then `Save policy`. + +## Step 9: Test your changes + +You can now sign up and you should see the following screen: + +![SuperTokens App Authenticated](/img/guides/integrations/supertokens/supabase_app_authenticated_screen.png) + +If you navigate to your table you should see a new row with the user's `user_id` and `email`. + +![Supabase Users table](/img/guides/integrations/supertokens/table_with_user.png) + +## Resources + +- [SuperTokens](https://supertokens.com/) official website. +- [SuperTokens community](https://supertokens.com/discord). +- [SuperTokens documentation](https://supertokens.com/docs/guides). diff --git a/apps/reference/docs/guides/integrations/vercel.mdx b/apps/reference/docs/guides/integrations/vercel.mdx new file mode 100644 index 00000000000..65904c8ac61 --- /dev/null +++ b/apps/reference/docs/guides/integrations/vercel.mdx @@ -0,0 +1,241 @@ +--- +id: vercel +title: 'Vercel' +description: The fastest way to get up and running with an application that uses Supabase is with Vercel's Next.js starter and Supabase integration. +--- + +This guide steps through using Vercel's dashboard to create a Next.js project integrated with Supabase. To further streamline the process, we will be using the Next.js starter template, which can be automatically forked to a new GitHub repo, without leaving the dashboard! + +If you don’t have a Vercel account, create one [here](https://vercel.com/signup). + +## Step 1: Create a Supabase project + +This guide could use an existing Supabase project, but to create the `todo` demo from scratch, navigate to [Supabase](https://app.supabase.com/), click `Sign In` and authenticate with GitHub to login or register a new account. + +From the Supabase dashboard, click `New project` and select an organization. + +> Note: You may need to create an organization first. + +Give your project a `name`, `password`, select a `region` close to your potential users and click `Create new project`. + +![Create a Supabase project](/img/guides/integrations/vercel/create-supabase-project.png) + +Supabase will take a couple of minutes to configure the infrastructure. + +Once this is finished, navigate to `SQL Editor` from the sidebar menu and click `New query`. + +This will create a new SQL snippet called "New Query". Copy and paste the following and click `Run`. + +```sql +create table todos ( + id bigint generated by default as identity primary key, + title text, + is_complete boolean default false, + created_at timestamp with time zone default timezone('utc'::text, now()) not null +); + +alter table todos enable row level security; + +create policy "Anyone can view todos" on todos for + select using (true); + +create policy "Anyone can add new todos" on todos for + insert with check (true); + +insert into todos(title) +values + ('Create Supabase project'), + ('Create Vercel project'), + ('Install Supabase integration'); +``` + +This will create a new todos table, enable row level security, add policies for selecting and inserting data, and add some example rows. + +> Note: To simplify this example, we are allowing anyone to `select` and `insert` rows on the `todos` table. Usually, these actions would be locked down to only allow logged in users to perform them. Check out [this video](https://www.youtube.com/watch?v=Ow_Uzedfohk) to learn more about Row Level Security and policies. + +## Step 2: Create Vercel project + +From your [Vercel dashboard](https://vercel.com/dashboard), click `New Project`. + +![Create new Vercel project](/img/guides/integrations/vercel/create-vercel-project.png) + +Under the `Clone Template` menu, click `Next.js`. + +![Clone Next.js template](/img/guides/integrations/vercel/clone-next-js-template.png) + +In the `Create Git Repository` section, click `GitHub`, select your username under `GIT SCOPE`, enter a name for your project, choose whether you want your repo `private` or `public`, and click `Create`. + +![New GitHub repo settings](/img/guides/integrations/vercel/repo-settings.png) + +This will create a new GitHub repository, clone and commit the Next.js starter project, then build and deploy your new project to Vercel. + +Once you have been redirected to the `Congratulations` screen, click `Go to Dashboard`. + +Navigate to `Settings`, `Integrations`, then click `Browse Marketplace`. + +Search for `Supabase` and click the Supabase integration. + +![Supabase integration](/img/guides/integrations/vercel/supabase-integration.png) + +Click `Add Integration`. Select your account from the `Vercel Scope` dropdown, and click `CONTINUE`. + +![Choose scope](/img/guides/integrations/vercel/choose-scope.png) + +Choose `Specific Projects` and select your new Vercel project from the dropdown, and click `Add Integration`. + +![Choose project](/img/guides/integrations/vercel/choose-project.png) + +From the Supabase popup, select your new Vercel Project and Supabase project from the dropdowns. + +![Supabase integration](/img/guides/integrations/vercel/link-vercel-to-supabase.png) + +## Step 4: Clone GitHub repo + +The fastest way to get this project running locally is to clone the repo that Vercel created for us. + +Navigate back to the Vercel project `Overview` page, and click `View Git Repository`. + +![Vercel Project Dashboard](/img/guides/integrations/vercel/vercel-project-dashboard.png) + +This will open the GitHub repo. From here, click the arrow next to `Code` and copy the url from the dropdown. + +![GitHub repo url](/img/guides/integrations/vercel/github-project-url.png) + +Open a terminal window or CLI and run the following command to clone the GitHub repo. + +```bash +git clone your-repo-url.git +``` + +Open the project in your code editor of choice, and update the contents of `pages/index.js` to the following: + +```jsx +import styles from '../styles/Home.module.css' + +export default function Home() { + return
working
+} +``` + +Run a local development server. + +```bash +npm run dev +``` + +Navigate to `http://localhost:3000` to confirm the project is "working". + +## Step 4: Pull environment variables from Vercel + +First, we need to login to Vercel using their CLI tool. + +```bash +npx vercel login +``` + +This will ask if we are happy to install `vercel`. Type `y` and hit `Enter`. + +We will then need to authenticate Vercel by selecting `Continue with GitHub`. + +This will open a browser window where you need to authenticate with your GitHub account. + +Next, we need to link our Vercel project. + +```bash +npx vercel link +``` + +Step through the prompts to link the Vercel project. + +![Link project from Vercel](/img/guides/integrations/vercel/vercel-link.png) + +Copy the environment variables from our Vercel project. + +```bash +npx vercel env pull +``` + +This will create a `.env` file containing our Supabase environment variables. Rename this file to `.env.local` to automatically ignore it from git. + +## Step 5: Install Supabase.js + +Install the `supabase-js` library. + +```bash +npm i @supabase/supabase-js +``` + +Create a new file called `/utils/supabase.js` and add the following. + +```jsx +import { createClient } from '@supabase/supabase-js' + +export default createClient( + process.env.NEXT_PUBLIC_SUPABASE_URL, + process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY +) +``` + +Create a new file called `/components/NewTodo.js` and add the following. + +```jsx +import { useState } from 'react' +import supabase from '../utils/supabase' + +export default ({ reload }) => { + const [title, setTitle] = useState('') + + const addTodo = async (e) => { + e.preventDefault() + await supabase.from('todos').insert({ title }) + reload() + setTitle('') + } + + return ( +
+ setTitle(e.target.value)} /> +
+ ) +} +``` + +This component will be responsible for writing a new `todo` to Supabase. + +Let's import our new component in `pages/index.js` and display a list of todos. + +```jsx +import { useState, useEffect } from 'react' +import styles from '../styles/Home.module.css' +import supabase from '../utils/supabase' +import NewTodo from '../components/NewTodo' + +export default function Home() { + const [todos, setTodos] = useState([]) + + const fetchTodos = async () => { + const { data } = await supabase.from('todos').select('*') + setTodos(data) + } + + useEffect(() => { + fetchTodos() + }, []) + + return ( +
+ + {todos.map((todo) => ( +

{todo.title}

+ ))} +
+ ) +} +``` + +## Resources + +- [Vercel official website](https://vercel.com). +- [Vercel blog](https://vercel.com/blog). +- [Vercel docs](https://vercel.com/docs). +- [Vercel Integration docs](https://vercel.com/docs/integrations) diff --git a/apps/reference/docs/guides/local-development.mdx b/apps/reference/docs/guides/local-development.mdx new file mode 100644 index 00000000000..114c5f8cfcf --- /dev/null +++ b/apps/reference/docs/guides/local-development.mdx @@ -0,0 +1,258 @@ +--- +id: local-development +title: Local Development +description: How to use Supabase on your local development machine. +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +Supabase provides a CLI so that you can develop your application locally, with the ability to deploy your application to the Supabase platform. + +## Prerequisites + +### Dependencies + +Before we begin, make sure you have these installed on your local machine: + +- Git. [Docs](https://github.com/git-guides/install-git) +- Docker (make sure this is running). [Docs](https://docs.docker.com/engine/install/) +- Supabase CLI. [Docs](/docs/reference/cli/installing-and-updating) + +### Supabase CLI login + +After installing the Supabase CLI you can [log in](/docs/reference/cli/supabase-login) using your Supabase account (sign up at [app.supabase.com](https://app.supabase.com)). + +```bash +supabase login +``` + +This is a one-time operation. After you have logged in the CLI will have permissions to manage your Supabase projects. + +## Getting started + +### Initialize your project + +Let's create a new folder on your local machine: + +```bash +# create your project folder +mkdir your-project + +# move into the new folder +cd your-project + +# start a new git repository +git init +``` + +These commands will create an empty folder for your project and start a new git repository. + +### Initialize Supabase + +Let's [initialize](/docs/reference/cli/supabase-init) Supabase inside the folder that you created: + +```bash +supabase init +``` + +This command will create a `supabase` folder which holds all the configuration for developing your project locally. + +## Developing Locally + +### Start Supabase + +```bash +supabase start +``` + +The [start](/docs/reference/cli/supabase-start) command uses Docker to start the open source [services](/docs/#how-it-works) of Supabase. +This command may take a while to run if this is the first time using the CLI. + +Once all of the Supabase services are running, you'll see an output that contains your local Supabase credentials. + +You can use the [stop](/docs/reference/cli/supabase-stop) command at any time to stop all services. + +### Accessing Services Directly + + + + +```sh +# Default URL: +postgresql://postgres:postgres@localhost:54322/postgres +``` + +The local Postgres instance can be accessed through [`psql`](https://www.postgresql.org/docs/current/app-psql.html) +or any other Postgres client, such as [pgadmin](https://www.pgadmin.org/). + +For example: + +```bash +psql 'postgresql://postgres:postgres@localhost:54322/postgres' +``` + + + + +```sh +# Default URL: +http://localhost:54321 +``` + +All of the services are accessible through the API Gateway [Kong](https://github.com/Kong/kong)). +If you are accessing these services without the client libraries, you may need to pass the client keys as an `Authorization` header. +You can learn more about these JWT headers in our [Resources](/docs/learn/auth-deep-dive/auth-deep-dive-jwts). + +```sh +curl 'http://localhost:54321/rest/v1/' \ + -H "apikey: " \ + -H "Authorization: Bearer " + +http://localhost:54321/rest/v1/ # REST (PostgREST) +http://localhost:54321/realtime/v1/ # Realtime +http://localhost:54321/storage/v1/ # Storage +http://localhost:54321/auth/v1/ # Auth (GoTrue) +``` + + + + + +### Database Migrations + +Database changes are managed through "migrations". Database migrations are a common way of tracking changes to your database over time. + + +#### Making database changes + +For this guide, let's create a table called `employees`, using the "Supabase Studio" link provided. + +:::note + +If you're familiar with databases, you can also execute any SQL using the `DB URL` shown by `supabase start`. + +::: + +Open the Studio, navigate to the "SQL Editor" section, and run the following SQL command: + +```sql +create table employees ( + id integer primary key generated always as identity, + name text +); +``` + +Now we have the `employees` table in the local database, but how do we incorporate this into migrations? The CLI automatically detects changes by running the [commit](/docs/reference/cli/supabase-db-commit) command: + +```sh +supabase db commit create_employees +``` + +This creates a new migration named `supabase/migrations/_create_employees.sql`, representing any changes we've made to the local database since `supabase start`. + +#### Adding sample data + +Let's add some sample data into the table. We can use the seed script in `supabase/seed.sql` (which gets created when you run `supabase init`). + +```sql +-- in supabase/seed.sql +insert into public.employees (name) +values + ('Erlich Backman'), + ('Richard Hendricks'), + ('Monica Hall'); +``` + +Now run the following to rerun the migration scripts and the seed script: + +```bash +supabase db reset +``` + +If you look again within Studio, you should now see the contents of `employees`. + +#### Resetting database changes + +If you run any SQL on the local database that you want to revert, you can use the `reset` command. + +```sql +-- run on local database to make a change +alter table employees + add department text default 'Hooli'; +``` + +To revert this change we can run: + +```sh +supabase db reset +``` + +And the local database will be reset. + +## Deploying + +Now that you've developed an application locally, head over to [app.supabase.com](https://app.supabase.com) and create a project where we can deploy the changes. + +### Linking your project + +:::note + +There are a few commands required to link your project. We are in the process of consolidating these commands into a single command. Bear with us! + +::: + +Let's associate your project with your remote project using [supabase link](/docs/guides/local-development) and [db remote set](/docs/reference/cli/supabase-db-remote-set) + + +```bash + +supabase link +# Use "supabase link --project-ref your-project-ref" to link your project in one step. + +supabase db remote set 'postgresql://postgres:@db..supabase.co:5432/postgres' +# Use the connection string from your Supabase project here. + +supabase db remote commit +# capture any changes that you have made to your database before setting up the CLI +``` + +You'll notice that `supabase/migrations` is now populated with a migration in `..._remote_commit.sql`. +This migration captures any changes required for your local database to match the schema of your remote Supabase project. + + +### Deploying Database changes + +You can deploy any local database migrations using [`db push`](/docs/reference/cli/supabase-db-push): + +```sh +supabase db push +``` + +### Deploying Edge Functions + +You can deploy any Edge Functions using [`functions deploy`](/docs/reference/cli/supabase-functions-deploy): + +```sh +supabase functions deploy +``` + +## Limitations + +The local development environment is not as feature-complete as the Platform. Here are some of the differences: + +- The Storage interface is coming soon. +- The Functions interface is coming soon. +- Logs are not supported through the interface (however you can accesss them via the docker containers). +- You cannot update your project settings via the Dashboard - this can be done using the CLI instead. + +## Next steps + +- Got a question? [Ask in our Discussions](https://github.com/supabase/supabase/discussions). +- CLI repository: [GitHub](https://github.com/supabase/cli). +- Sign in: [app.supabase.com](https://app.supabase.com) diff --git a/apps/reference/docs/guides/platform/logs.mdx b/apps/reference/docs/guides/platform/logs.mdx new file mode 100644 index 00000000000..5fcf33ff1b1 --- /dev/null +++ b/apps/reference/docs/guides/platform/logs.mdx @@ -0,0 +1,84 @@ +--- +id: logs +title: Logging +description: Getting started with Supabase Platform Log Browser +--- + +The Supabase Platform provides a log explorer that allows log tracing and debugging. Currently, PostgreSQL and Cloudflare edge logs are available. + +:::note + +The features discussed in this article are only available through the Supabase Platform and are not available on self-hosted. + +::: + +## Product Logs + +As well as a Log Explorer, Supabase provides a logging interface specific to each product. + +### API Logs + +![API Logs](/img/guides/platform/logs/logs-api.png) + +The API Logs can be found under `Database > API Logs`. These show all network requests for the REST and GraphQL [API](/docs/guides/api). + +### Postgres Logs + +![Postgres Logs](/img/guides/platform/logs/logs-database.png) + +The Postgres Logs can be found under `Database > Postgres Logs`. These show all queries and activity for your [Database](/docs/guides/database). + + +## Log Explorer + +![Sidebar navigation steps](/img/guides/platform/logs/sidebar-navigation.png) + +The log browser can be accessed in the sidebar under **Logs Explorer**. The **Logs Explorer** is for querying and aggregating project logs across products using SQL `SELECT` queries. + + +### Example +For example, you may enter the following into the SQL editor to query for each user's IP address: + +```sql +SELECT timestamp, h.x_real_ip +FROM edge_logs + LEFT JOIN UNNEST(metadata) as m ON TRUE + LEFT JOIN UNNEST(m.request) AS r ON TRUE + LEFT JOIN UNNEST(r.headers) AS h ON TRUE +WHERE h.x_real_ip IS NOT NULL +``` + +![SELECT query example](/img/guides/platform/logs/select-query.png) + + +The list of supported product sources can be found under the **Sources** dropdown. + +### Unnesting Arrays + +To query the metadata in the above example, you can unnest the field and "join" the unnested data. Clicking on the log row shows that log metadata is stored as an array of objects. + +In order to query any value that is an array, we would need to `UNNEST()` that field and add it to the query as a join, thereby allowing us to reference the nested fields within the array. + +:::caution + +Large projects may run into a `Resources Exceeded` memory limit error when selecting large objects with many nested keys. To avoid this error, select individual keys separately or reduce the queried date range. +::: + +### Functions + +You may have also noticed from the above examples that we are able to use certain SQL functions within our queries. The querying engine currently supported is BigQuery, hence you may use [any valid BigQuery function](https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-and-operators) within your query. + + +#### Timestamp Behavior + +Each log entry is stored with a `timestamp`. In order to utilize the `timestamp` field in a query, you can use the appropriate [timestamp functions](https://cloud.google.com/bigquery/docs/reference/standard-sql/timestamp_functions#timestamp). + +:::note + +In the Log Explorer, timestamps are rendered as unix microsecond timestamps. SQL queries, however, should always use the `TIMESTAMP` data type. If you are using a unix timestamp value in a query, cast the value to a `TIMESTAMP` data type. + +::: + +## Templates + +Templates are available to help craft you log queries. Templates are available under the **Templates** tab, or under the **Templates** Dropdown in the **Query** tab. \ No newline at end of file diff --git a/apps/reference/docs/guides/platform/metrics.mdx b/apps/reference/docs/guides/platform/metrics.mdx new file mode 100644 index 00000000000..8fba89eace9 --- /dev/null +++ b/apps/reference/docs/guides/platform/metrics.mdx @@ -0,0 +1,31 @@ +--- +id: metrics +title: Metrics +description: Observability for your Supabase project +--- + +In addition to the reports and charts built in to the Supabase dashboard, each project hosted on the Supabase platform comes with a [Prometheus](https://prometheus.io/)-compatible metrics endpoint, which can be used to gather insight into the health and status of your project. + +You can use this endpoint to ingest data into your own monitoring and alerting infrastructure, as long as it is capable of scraping Prometheus-compatible endpoints, in order to set up custom rules beyond those supported by the Supabase dashboard. + +:::note + +The endpoint discussed in this article is in beta, and the metrics returned by it might evolve or be changed in the future to increase its utility. + +::: + +:::note + +The endpoint discussed in this article is not available on self-hosted. + +::: + +## Accessing the metrics endpoint + +Your project's metrics endpoint is accessible at `https://.supabase.co/customer/v1/privileged/metrics`. Access to the endpoint is secured via HTTP Basic Auth; the username is `service_role`, while the password is the service role JWT available through the Supabase dashboard. + +```shell +> curl https://.supabase.co/customer/v1/privileged/metrics --user 'service_role:' +``` + +Additionally, we [maintain a guide](https://github.com/supabase/grafana-agent-fly-example/) on quickly setting up a scraping agent to work with Grafana Cloud. diff --git a/apps/reference/docs/guides/platform/performance.mdx b/apps/reference/docs/guides/platform/performance.mdx new file mode 100644 index 00000000000..3194054dff8 --- /dev/null +++ b/apps/reference/docs/guides/platform/performance.mdx @@ -0,0 +1,78 @@ +--- +id: performance +title: Performance Tuning +description: Getting the best results out of your Supabase project +--- + +The Supabase platform automatically optimizes your Postgres database to take advantage of the compute resources of the tier your project is on. However, these optimizations are based on assumptions about the type of workflow the project is being utilized for, and it is likely that better results can be obtained by tuning the database for your particular workflow. + +## Optimizing the number of connections + +By default, the number of connections allowed to Postgres and PgBouncer is configured based on the resources available to the database. + +| Compute Add-on | Postgresql connections | PGBouncer connections | +|----------------|------------------------|-----------------------| +| None | 60 | 200 | +| Small | 90 | 200 | +| Medium | 120 | 200 | +| Large | 160 | 300 | +| XL | 240 | 700 | +| 2XL | 380 | 1500 | +| 4XL | 480 | 3000 | +| 8XL | 490 | 6000 | +| 12XL | 500 | 9000 | +| 16XL | 500 | 12000 | + +If the number of connections is insufficient, you will receive the following error upon connecting to the DB: + +```shell +$ psql -U postgres -h ... +FATAL: remaining connection slots are reserved for non-replication superuser connections +``` + +In such a scenario, you can consider either upgrading to a larger compute add-on, or alternatively, by manually configuring the database for a higher number of connections. + +You can configure Postgres by executing the following statement, followed by a server restart: + +```sql +alter system set max_connections = ''; +``` + +Note that [the default configuration used by the Supabase platform](https://github.com/supabase/supabase-admin-api/blob/master/optimizations/postgres.go) optimizes the database to maximize resource utilization, and as a result, you might also need to configure other options (e.g. `work_mem`, `shared_buffers`, `maintenance_work_mem`) in order to tune them towards your use-case, and to avoid causing instability in your database. + +Once overridden, the Supabase platform will continue to respect your manually configured value (even if the add-on size is changed), unless the override is removed with the following statement, followed by a server restart: + +```sql +alter system reset max_connections; +alter system reset ; +... +``` + +Configuring the number of PgBouncer connections is not supported at this time. + +## Examining Query Performance + +Every Supabase project has [the pg_stat_statements extension](https://www.postgresql.org/docs/14/pgstatstatements.html) enabled by default. This extension records query execution performance details and is the best way to find queries that take the most time to execute. This information can be combined with the Postgres query plan analyzer to develop more efficient queries. + +Obtaining information from pg_stat_statements: +```sql +select mean_exec_time + stddev_exec_time, * from pg_stat_statements order by 1 desc; +``` + +Using the query plan analyzer on your expensive queries: + +```sql +explain analyze ; +``` + +Be careful using `explain analyze` with `insert`/`update`/`delete` queries, because the query will actually run, and could have unintended side-effects. + +Using the query plan analyzer to optimize your queries is a large topic, with a number of online resources available: + +- [Official docs.](https://www.postgresql.org/docs/current/using-explain.html) +- [The Art of PostgreSQL.](https://theartofpostgresql.com/explain-plan-visualizer/) +- [Postgres Wiki.](https://wiki.postgresql.org/wiki/Using_EXPLAIN) +- [Enterprise DB.](https://www.enterprisedb.com/blog/postgresql-query-optimization-performance-tuning-with-explain-analyze) + + +You can pair the information available from `pg_stat_statements` with the detailed system metrics available [via your metrics endpoint](/docs/guides/platform/metrics) to better understand the behavior of your DB and the queries you're executing against it. diff --git a/apps/reference/docs/guides/platform/permissions.mdx b/apps/reference/docs/guides/platform/permissions.mdx new file mode 100644 index 00000000000..c3fbf719d23 --- /dev/null +++ b/apps/reference/docs/guides/platform/permissions.mdx @@ -0,0 +1,14 @@ +--- +id: permissions +title: Permissions +description: Permissions requirements for the Supabase Cloud hosting environment +--- + +The Supabase platform offers additional services (e.g. Storage) on top of the Postgres database that comes with each project. These services default to storing their operational data within your database, to ensure that you retain complete control over it. + +However, these services assume a base level of access to their data, in order to e.g. be able to run migrations over it. Breaking these assumptions runs the risk of rendering these services inoperational for your project: + +- all entitites under the `storage` schema are owned by `supabase_storage_admin` +- all entitites under the `auth` schema are owned by `supabase_auth_admin` + +It is possible for violations of these assumptions to not cause an immediate outage, but take effect at a later time when a newer migration becomes available. diff --git a/apps/reference/docs/guides/storage.mdx b/apps/reference/docs/guides/storage.mdx new file mode 100644 index 00000000000..8caca04659a --- /dev/null +++ b/apps/reference/docs/guides/storage.mdx @@ -0,0 +1,379 @@ +--- +id: storage +title: Storage +description: Use Supabase to store and serve files. +sidebar_label: Overview +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +## Overview + +Supabase Storage makes it simple to store and serve large files. + +### Files + +Files can be any sort of media file. This includes images, GIFs, and videos. It is best practice to store files outside of your database because of their sizes. + +### Folders + +Folders are a way to organize your files (just like on your computer). +There is no right or wrong way to +organize your files. You can store them in whichever folder structure suits your project. + +### Buckets + +Buckets are distinct containers for files and folders. You can think of them like "super folders". +Generally you would create distinct buckets for different Security and Access Rules. For example, you might +keep all public files in a "public" bucket, and other files that require logged-in access in a "restricted" bucket. + +## Getting started + +This is a quick guide that shows the basic functionality of Supabase Storage. Find a full +[example application in GitHub](https://github.com/supabase/supabase/tree/master/examples/user-management/nextjs-ts-user-management), +which you can deploy yourself. + +**Note before begin** : File, Folder, and Bucket names **must follow** [AWS Safe Characters naming guideline](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-keys.html) and avoid use of any other characters + +[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https%3A%2F%2Fgithub.com%2Fsupabase%2Fsupabase%2Ftree%2Fmaster%2Fexamples%2Fnextjs-ts-user-management&project-name=supabase-user-management&repository-name=supabase-user-management&demo-title=Supabase%20User%20Management&demo-description=An%20example%20web%20app%20using%20Supabase%20and%20Next.js&demo-url=https%3A%2F%2Fsupabase-nextjs-ts-user-management.vercel.app&demo-image=https%3A%2F%2Fi.imgur.com%2FZ3HkQqe.png&integration-ids=oac_jUduyjQgOyzev1fjrW83NYOv&external-id=nextjs-user-management) + +### Create a bucket + +You can create a bucket using the Supabase Dashboard. +Since the storage is interoperable with your Postgres database, you can also use SQL or our +client libraries. Here we create a bucket called "avatars": + + + + +1. Go to the [Storage](https://app.supabase.com/project/_/storage/buckets) page in the Dashboard. +2. Click **New Bucket** and enter a name for the bucket. +3. Click **Create Bucket**. + + + + + + +```sql +-- Use Postgres to create a bucket. + +insert into storage.buckets (id, name) +values ('avatars', 'avatars'); +``` + + + + +```js +// Use the JS library to create a bucket. + +const { data, error } = await supabase.storage.createBucket('avatars') +``` + +[Reference.](/docs/reference/javascript/storage-createbucket) + + + + +```dart +void main() async { + final client = SupabaseClient('supabaseUrl', 'supabaseKey'); + + final storageResponse = await client + .storage + .createBucket('avatars'); +} +``` + +[Reference.](https://pub.dev/documentation/storage_client/latest/storage_client/SupabaseStorageClient/createBucket.html) + + + + +### Upload a file + +You can upload a file from the Dashboard, or within a browser using our JS libraries. + + + + +1. Go to the [Storage](https://app.supabase.com/project/_/storage/buckets) page in the Dashboard. +2. Select the bucket you want to upload the file to. +3. Click **Upload File**. +4. Select the file you want to upload. + + + + + + +```js +const avatarFile = event.target.files[0] +const { data, error } = await supabase.storage + .from('avatars') + .upload('public/avatar1.png', avatarFile) +``` + +[Reference.](/docs/reference/javascript/storage-from-upload) + + + + +```dart +void main() async { + final client = SupabaseClient('supabaseUrl', 'supabaseKey'); + + // Create file `example.txt` and upload it in `public` bucket + final file = File('example.txt'); + file.writeAsStringSync('File content'); + final storageResponse = await client + .storage + .from('public') + .upload('example.txt', file); +} +``` + + + + +### Download a file + +You can download a file from the Dashboard, or within a browser using our JS libraries. + + + + +1. Go to the [Storage](https://app.supabase.com/project/_/storage/buckets) page in the Dashboard. +2. Select the bucket that contains the file. +3. Select the file that you want to download. +4. Click **Download**. + + + + + + +```js +// Use the JS library to create a bucket. + +const { data, error } = await supabase.storage.from('avatars').download('public/avatar1.png') +``` + +[Reference.](/docs/reference/javascript/storage-from-download) + + + + +```dart +void main() async { + final client = SupabaseClient('supabaseUrl', 'supabaseKey'); + + final storageResponse = await client + .storage + .from('public') + .download('example.txt'); +} +``` + + + + +### Add security rules + +To restrict access to your files you can use either the Dashboard or SQL. + + + + +1. Go to the [Storage](https://app.supabase.com/project/_/storage/buckets) page in the Dashboard. +2. Click **Policies** in the sidebar. +3. Click **Add Policies** in the `OBJECTS` table to add policies for Files. You can also create policies for Buckets. +4. Choose whether you want the policy to apply to downloads (SELECT), uploads (INSERT), updates (UPDATE), or deletes (DELETE). +5. Give your policy a unique name. +6. Write the policy using SQL. + + + + + + +```sql +-- Use SQL to create a policy. + +create policy "Public Access" + on storage.objects for select + using ( bucket_id = 'public' ); +``` + + + + +## Helpers + +Supabase Storage is configured with database SQL helper functions which you can use in your database queries and +policies. + +--- + +#### `storage.filename()` + +Returns the name of a file. + +```sql +select storage.filename(name) +from storage.objects; +``` + +For example, if your file is stored in `public/subfolder/avatar.png` it would return: + +`'avatar.png'` + +--- + +#### `storage.foldername()` + +Returns an array path, with all of the subfolders that a file belongs to. + +```sql +select storage.foldername(name) +from storage.objects; +``` + +For example, if your file is stored in `public/subfolder/avatar.png` it would return: + +`[ 'public', 'subfolder' ]` + +--- + +#### `storage.extension()` + +Returns the extension of a file. + +```sql +select storage.extension(name) +from storage.objects; +``` + +For example, if your file is stored in `public/subfolder/avatar.png` it would return: + +`'png'` + +--- + +## Accessing objects + + +For private buckets, you can access objects via the [download](/docs/reference/javascript/storage-from-download) method. This corresponds to `/object/auth/` API endpoint. +Alternatively, you can create a publicly shareable URL with an expiry date using the [createSignedUrl](/docs/reference/javascript/storage-from-createsignedurl) method +which calls the `/object/sign/` API. + +For public buckets, you can access the assets directly without a token or an Authorisation header. The [getPublicUrl](/docs/reference/javascript/storage-from-getpublicurl) +helper method returns the full public URL for an asset. This calls the `/object/public/` API endpoint internally. + + +
+Advanced: reverse proxy +The URLs returned are proxied through the API Proxy. They are prefixed by /storage/v1. + +For example, on the hosted Platform they will be + +https://[project_ref].supabase.co/storage/v1/object/public/[id] + +You can access the storage API directly with the same endpoint. See the API docs for a full list of operations available. + +
+ + +--- + +## Security + +Supabase Storage is integrated with your [Postgres Database](/docs/guides/database). +This means that you can use the same [Policy](/docs/guides/auth#policies) engine +for managing access to your files. + +## Policy Examples + +Here are some examples to show you the power of PostgreSQL's Row Level Security. Each policy is attached to a table, and the policy is executed +every time a table is accessed. + +### Allow public access to a bucket + +```sql +-- 1. Allow public access to any files in the "public" bucket +create policy "Public Access" +on storage.objects for select +using ( bucket_id = 'public' ); +``` + +### Allow logged-in access to a bucket + +```sql +-- 1. Allow logged-in access to any files in the "restricted" bucket +create policy "Restricted Access" +on storage.objects for select +using ( + bucket_id = 'restricted' + and auth.role() = 'authenticated' +); +``` + +### Allow individual access to a file + +```sql +-- 1. Allow a user to access their own files +create policy "Individual user Access" +on storage.objects for select +using ( auth.uid() = owner ); +``` + +## Resources + +- Find the API server on GitHub: [github.com/supabase/storage-api](https://github.com/supabase/storage-api) +- Find the Swagger API Docs online: [supabase.github.io/storage-api](https://supabase.github.io/storage-api) +- Official client libraries documentation: [JavaScript](/docs/reference/javascript/storage-createbucket) and [Dart](/docs/reference/dart/storage-createbucket). +- Community libraries: [github.com/supabase-community](https://github.com/supabase-community) + +## Next steps + +- Got a question? [Ask here](https://github.com/supabase/supabase/discussions). +- Read more about storage in our [blog post](https://supabase.com/blog/2021/03/30/supabase-storage). +- Sign in: [app.supabase.com](https://app.supabase.com) diff --git a/apps/reference/docs/guides/storage/storage-sample.mdx b/apps/reference/docs/guides/storage/storage-sample.mdx new file mode 100644 index 00000000000..cd9ec88a3b4 --- /dev/null +++ b/apps/reference/docs/guides/storage/storage-sample.mdx @@ -0,0 +1,12 @@ +--- +id: storage-sample +title: "Storage Sample Doc" +description: Storage Sample Doc +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +## Description + +Sample... \ No newline at end of file diff --git a/apps/reference/docs/guides/with-angular.mdx b/apps/reference/docs/guides/with-angular.mdx new file mode 100644 index 00000000000..58b7444c70c --- /dev/null +++ b/apps/reference/docs/guides/with-angular.mdx @@ -0,0 +1,571 @@ +--- +id: with-angular +title: "Quickstart: Angular" +description: Learn how to use Supabase in your Angular App. +sidebar_label: Angular +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +## Intro + +This example provides the steps to build a simple user management app (from scratch!) using Supabase and Angular. It includes: + +- Supabase [Database](/docs/guides/database): a Postgres database for storing your user data. +- Supabase [Auth](/docs/guides/auth): users can sign in with magic links (no passwords, only email). +- Supabase [Storage](/docs/guides/storage): users can upload a photo. +- [Row Level Security](/docs/guides/auth#row-level-security): data is protected so that individuals can only access their own data. +- Instant [APIs](/docs/guides/api): APIs will be automatically generated when you create your database tables. + +By the end of this guide you'll have an app which allows users to login and update some basic profile details: + +![Supabase User Management example](/img/user-management-demo.png) + +Clicking this button the application will: + +- Launch and prepare the Postgres database in Supabase. +- Launch the app in Vercel. +- Fork the example into your own GitHub account. +- Prepare the deployed application with all the necessary environment variables. + +If you want to do it yourself, let's get started! + +### GitHub + +Whenever you get stuck at any point, take a look at [this repo](https://github.com/angular-supa/supabase-angular-user-management). + +## Project set up + +Before we start building we're going to set up our Database and API. This is as simple as starting a new Project in Supabase +and then creating a "schema" inside the database. + +### Create a project + +1. Go to [app.supabase.com](https://app.supabase.com). +1. Click on "New Project". +1. Enter your project details. +1. Wait for the new database to launch. + + +### Set up the database schema + +Now we are going to set up the database schema. We can use the "User Management Starter" quickstart in the SQL Editor, +or you can just copy/paste the SQL from below and run it yourself. + + + + +1. Go to the [SQL Editor](https://app.supabase.com/project/_/sql) page in the Dashboard. +2. Click **User Management Starter**. +3. Click **Run**. + + + + + + +```sql +-- Create a table for public "profiles" +create table profiles ( + id uuid references auth.users not null, + updated_at timestamp with time zone, + username text unique, + avatar_url text, + website text, + + primary key (id), + unique(username), + constraint username_length check (char_length(username) >= 3) +); + +alter table profiles enable row level security; + +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 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; + +-- Set up Storage! +insert into storage.buckets (id, name) +values ('avatars', 'avatars'); + +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' ); +``` + + + + + +### Get the API Keys + +Now that you've created some database tables, you are ready to insert data using the auto-generated API. +We just need to get the URL and `anon` key from the API settings. + +1. Go to the [Settings](https://app.supabase.com/project/_/settings) page in the Dashboard. +2. Click **API** in the sidebar. +3. Find your API `URL`, `anon`, and `service_role` keys on this page. + + + +## Building the App + +Let's start building the Angular app from scratch. + +### Initialize an Angular app + +We can use the [Angular CLI](https://angular.io/cli) to initialize +an app called `supabase-angular`: + +```bash +npx ng new supabase-angular --routing false --style css +cd supabase-angular +``` + +Then let's install the only additional dependency: [supabase-js](https://github.com/supabase/supabase-js) + +```bash +npm install @supabase/supabase-js +``` + +And finally we want to save the environment variables in the `environment.ts` file. +All we need are the API URL and the `anon` key that you copied [earlier](#get-the-api-keys). +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. + + +```ts title="environment.ts" +export const environment = { + production: false, + supabaseUrl: "YOUR_SUPABASE_URL", + supabaseKey: "YOUR_SUPABASE_KEY" +}; +``` + +Now that we have the API credentials in place, let's create a **SupabaseService** with `ng g s supabase` to initialize the Supabase client and implement functions to communicate with the Supabase API. + +```ts title="src/app/supabase.service.ts" +import { Injectable } from '@angular/core'; +import {AuthChangeEvent, createClient, Session, SupabaseClient} from '@supabase/supabase-js'; +import {environment} from "../environments/environment"; + +export interface Profile { + username: string; + website: string; + avatar_url: string; +} + +@Injectable({ + providedIn: 'root' +}) +export class SupabaseService { + private supabase: SupabaseClient; + + constructor() { + this.supabase = createClient(environment.supabaseUrl, environment.supabaseKey); + } + + get user() { + return this.supabase.auth.user(); + } + + get session() { + return this.supabase.auth.session(); + } + + get profile() { + return this.supabase + .from('profiles') + .select(`username, website, avatar_url`) + .eq('id', this.user?.id) + .single(); + } + + authChanges(callback: (event: AuthChangeEvent, session: Session | null) => void) { + return this.supabase.auth.onAuthStateChange(callback); + } + + signIn(email: string) { + return this.supabase.auth.signIn({email}); + } + + signOut() { + return this.supabase.auth.signOut(); + } + + updateProfile(profile: Profile) { + const update = { + ...profile, + id: this.user?.id, + updated_at: new Date() + } + + return this.supabase.from('profiles').upsert(update, { + returning: 'minimal', // Don't return the value after inserting + }); + } + + downLoadImage(path: string) { + return this.supabase.storage.from('avatars').download(path); + } + + uploadAvatar(filePath: string, file: File) { + return this.supabase.storage + .from('avatars') + .upload(filePath, file); + } +} + +``` + +And one optional step is to update the CSS file `src/index.css` to make the app look nice. +You can find the full contents of this file [here](https://raw.githubusercontent.com/angular-supa/supabase-angular-user-management/main/src/styles.css). + +### Set up a Login component + +Let's set up an Angular component to manage logins and sign ups. We'll use Magic Links, so users can sign in with their email without using passwords. +Create an **AuthComponent** with `ng g c auth` Angular CLI command. + +```ts title="src/app/auth.component.ts" +import { Component } from '@angular/core'; +import {SupabaseService} from "./supabase.service"; + +@Component({ + selector: 'app-auth', + template: ` +
+
+

Supabase + Angular

+

Sign in via magic link with your email below

+
+ +
+
+ +
+
+
+ `, +}) +export class AuthComponent { + loading = false; + + constructor(private readonly supabase: SupabaseService) { } + + async handleLogin(input: string) { + try { + this.loading = true; + await this.supabase.signIn(input); + alert('Check your email for the login link!'); + } catch (error) { + alert(error.error_description || error.message) + } finally { + this.loading = false; + } + } +} +``` + +### Account page + +After a user is signed in we can allow them to edit their profile details and manage their account. +Create an **AccountComponent** with `ng g c account` Angular CLI command. + +```ts title="src/app/account.component.ts" +import {Component, Input, OnInit} from '@angular/core'; +import {Profile, SupabaseService} from "./supabase.service"; +import {Session} from "@supabase/supabase-js"; + +@Component({ + selector: 'app-account', + template: ` +
+
+ + +
+
+ + +
+
+ + +
+ +
+ +
+ +
+ +
+
+ ` +}) +export class AccountComponent implements OnInit { + loading = false; + profile: Profile | undefined; + + @Input() session: Session | undefined; + + constructor(private readonly supabase: SupabaseService) { } + + ngOnInit() { + this.getProfile(); + } + + async getProfile() { + try { + this.loading = true; + let {data: profile, error, status} = await this.supabase.profile; + + if (error && status !== 406) { + throw error; + } + + if (profile) { + this.profile = profile; + } + } catch (error) { + alert(error.message) + } finally { + this.loading = false; + } + } + + async updateProfile(username: string, website: string, avatar_url: string = '') { + try { + this.loading = true; + await this.supabase.updateProfile({username, website, avatar_url}); + } catch (error) { + alert(error.message); + } finally { + this.loading = false; + } + } + + async signOut() { + await this.supabase.signOut(); + } +} +``` + + + +### Launch! + +Now that we have all the components in place, let's update **AppComponent**: + +```ts title="src/app/app.component.ts" +import {Component, OnInit} from '@angular/core'; +import {SupabaseService} from "./supabase.service"; + +@Component({ + selector: 'app-root', + template: ` +
+ + + + +
+ ` +}) +export class AppComponent implements OnInit { + session = this.supabase.session; + + constructor(private readonly supabase: SupabaseService) { } + + ngOnInit() { + this.supabase.authChanges((_, session) => this.session = session); + } +} +``` + +Once that's done, run this in a terminal window: + +```bash +npm run start +``` + +And then open the browser to [localhost:4200](http://localhost:4200) and you should see the completed app. + + +![Supabase Angular](/img/supabase-angular-demo.png) + +## Bonus: Profile photos + +Every Supabase project is configured with [Storage](/docs/guides/storage) for managing large files like photos and videos. + +### Create an upload widget + +Let's create an avatar for the user so that they can upload a profile photo. +Create an **AvatarComponent** with `ng g c avatar` Angular CLI command. + +```ts title="src/app/avatar.component.ts" +import {Component, EventEmitter, Input, Output} from '@angular/core'; +import {SupabaseService} from "./supabase.service"; +import {DomSanitizer, SafeResourceUrl} from "@angular/platform-browser"; + +@Component({ + selector: 'app-avatar', + template: ` +
+ Avatar
+
+
+ + +
+ `, +}) +export class AvatarComponent { + _avatarUrl: SafeResourceUrl | undefined; + uploading = false; + + @Input() + set avatarUrl(url: string | undefined) { + if (url) { + this.downloadImage(url); + } + }; + + @Output() upload = new EventEmitter(); + + constructor( + private readonly supabase: SupabaseService, + private readonly dom: DomSanitizer + ) { } + + async downloadImage(path: string) { + try { + const {data} = await this.supabase.downLoadImage(path); + if (data instanceof Blob) { + this._avatarUrl = this.dom.bypassSecurityTrustResourceUrl( + URL.createObjectURL(data) + ); + } + } catch (error) { + console.error('Error downloading image: ', error.message); + } + } + + async uploadAvatar(event: any) { + try { + this.uploading = 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 = `${Math.random()}.${fileExt}`; + const filePath = `${fileName}`; + + await this.supabase.uploadAvatar(filePath, file); + this.upload.emit(filePath); + } catch (error) { + alert(error.message); + } finally { + this.uploading = false; + } + } +} +``` + + +### Add the new widget + +And then we can add the widget on top of the **AccountComponent** html template: + +```ts title="src/app/account.component.ts" +template: ` + + + + +` +``` + +## Next steps + +At this stage you have a fully functional application! + +- Got a question? [Ask here](https://github.com/supabase/supabase/discussions). +- Sign in: [app.supabase.com](https://app.supabase.com) diff --git a/apps/reference/docs/guides/with-expo.mdx b/apps/reference/docs/guides/with-expo.mdx new file mode 100644 index 00000000000..2406ed70c74 --- /dev/null +++ b/apps/reference/docs/guides/with-expo.mdx @@ -0,0 +1,524 @@ +--- +id: with-expo +title: 'Quickstart: Expo' +description: Learn how to use Supabase in your React Native App. +sidebar_label: Expo +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +## Intro + +This example provides the steps to build a simple user management app (from scratch!) using Supabase and React Native. It includes: + +- Supabase [Database](/docs/guides/database): a Postgres database for storing your user data. +- Supabase [Auth](/docs/guides/auth): users can sign in with magic links (no passwords, only email). +- Supabase [Storage](/docs/guides/storage): users can upload a photo. +- [Row Level Security](/docs/guides/auth#row-level-security): data is protected so that individuals can only access their own data. +- Instant [APIs](/docs/guides/api): APIs will be automatically generated when you create your database tables. + +By the end of this guide you'll have an app which allows users to login and update some basic profile details: + +## Project set up + +Before we start building we're going to set up our Database and API. This is as simple as starting a new Project in Supabase +and then creating a "schema" inside the database. + +### Create a project + +1. Go to [app.supabase.com](https://app.supabase.com). +1. Click on "New Project". +1. Enter your project details. +1. Wait for the new database to launch. + +### Set up the database schema + +Now we are going to set up the database schema. We can use the "User Management Starter" quickstart in the SQL Editor, +or you can just copy/paste the SQL from below and run it yourself. + + + + +1. Go to the [SQL Editor](https://app.supabase.com/project/_/sql) page in the Dashboard. +2. Click **User Management Starter**. +3. Click **Run**. + + + + + + +```sql +-- Create a table for public "profiles" +create table profiles ( + id uuid references auth.users not null, + updated_at timestamp with time zone, + username text unique, + avatar_url text, + website text, + + primary key (id), + unique(username), + constraint username_length check (char_length(username) >= 3) +); + +alter table profiles enable row level security; + +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 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; + +-- Set up Storage! +insert into storage.buckets (id, name) +values ('avatars', 'avatars'); + +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' ); + +``` + + + + +### Get the API Keys + +Now that you've created some database tables, you are ready to insert data using the auto-generated API. +We just need to get the URL and `anon` key from the API settings. + +1. Go to the [Settings](https://app.supabase.com/project/_/settings) page in the Dashboard. +2. Click **API** in the sidebar. +3. Find your API `URL`, `anon`, and `service_role` keys on this page. + + + +## Building the App + +Let's start building the React Native app from scratch. + +### Initialize a React Native app + +We can use [`expo`](https://docs.expo.dev/get-started/create-a-new-app/) to initialize +an app called `supabaseReactNative`: + +```bash +#select the "Blank (TypeScript)" template when prompted +expo init supabaseReactNative + +cd supabaseReactNative +``` + +Then let's install the additional dependencies: [supabase-js](https://github.com/supabase/supabase-js) + +```bash +yarn add @supabase/supabase-js +yarn add react-native-elements +yarn add react-native-safe-area-context +yarn add @react-native-async-storage/async-storage +yarn add react-native-url-polyfill +``` + +Now let's create a helper file to initialize the Supabase client. +We need the API URL and the `anon` key that you copied [earlier](#get-the-api-keys). +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="lib/supabase.ts" +import AsyncStorage from '@react-native-async-storage/async-storage'; +import { createClient } from '@supabase/supabase-js' + +const supabaseUrl = YOUR_REACT_NATIVE_SUPABASE_URL +const supabaseAnonKey = YOUR_REACT_NATIVE_SUPABASE_ANON_KEY + +export const supabase = createClient(supabaseUrl, supabaseAnonKey, { + localStorage: AsyncStorage as any, + autoRefreshToken: true, + persistSession: true, + detectSessionInUrl: false, +}); +``` + +### Set up a Login component + +Let's set up a React Native component to manage logins and sign ups. +Users would be able to sign in with their email and password. + +```jsx title="components/Auth.tsx" +import React, { useState } from 'react' +import { Alert, StyleSheet, View } from 'react-native' +import { supabase } from '../lib/supabase' +import { Button, Input } from 'react-native-elements' + +export default function Auth() { + const [email, setEmail] = useState('') + const [password, setPassword] = useState('') + const [loading, setLoading] = useState(false) + + async function signInWithEmail() { + setLoading(true) + const { user, error } = await supabase.auth.signIn({ + email: email, + password: password, + }) + + if (error) Alert.alert(error.message) + setLoading(false) + } + + async function signUpWithEmail() { + setLoading(true) + const { user, error } = await supabase.auth.signUp({ + email: email, + password: password, + }) + + if (error) Alert.alert(error.message) + setLoading(false) + } + + return ( + + + setEmail(text)} + value={email} + placeholder="email@address.com" + autoCapitalize={'none'} + /> + + + setPassword(text)} + value={password} + secureTextEntry={true} + placeholder="Password" + autoCapitalize={'none'} + /> + + + + + + + ) +} +``` + +### 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`. + +```jsx title="components/Account.js" +import { useState, useEffect } from 'react' +import { supabase } from '../utils/supabaseClient' + +export default function Account({ session }) { + const [loading, setLoading] = useState(true) + const [username, setUsername] = useState(null) + const [website, setWebsite] = useState(null) + const [avatar_url, setAvatarUrl] = useState(null) + + useEffect(() => { + getProfile() + }, [session]) + + async function getProfile() { + try { + setLoading(true) + const user = supabase.auth.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.message) + } finally { + setLoading(false) + } + } + + async function updateProfile({ username, website, avatar_url }) { + try { + setLoading(true) + const user = supabase.auth.user() + + const updates = { + id: user.id, + username, + website, + avatar_url, + 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 { + setLoading(false) + } + } + + return ( +
+
+ + +
+
+ + setUsername(e.target.value)} + /> +
+
+ + setWebsite(e.target.value)} + /> +
+ +
+ +
+ +
+ +
+
+ ) +} + +``` + + + +### 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 Account from '../components/Account' + +export default function Home() { + const [session, setSession] = useState(null) + + useEffect(() => { + setSession(supabase.auth.session()) + + supabase.auth.onAuthStateChange((_event, session) => { + setSession(session) + }) + }, []) + + return ( +
+ {!session ? : } +
+ ) +} +``` + +Once that's done, run this in a terminal window: + +```bash +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 +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: + +```jsx title="components/Avatar.js" +import { useEffect, useState } from 'react' +import { supabase } from '../utils/supabaseClient' + +export default function Avatar({ url, size, onUpload }) { + const [avatarUrl, setAvatarUrl] = useState(null) + const [uploading, setUploading] = useState(false) + + useEffect(() => { + if (url) downloadImage(url) + }, [url]) + + async function downloadImage(path) { + 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.message) + } + } + + + async function uploadAvatar(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 = `${Math.random()}.${fileExt}` + const filePath = `${fileName}` + + let { error: uploadError } = await supabase.storage + .from('avatars') + .upload(filePath, file) + + if (uploadError) { + throw uploadError + } + + onUpload(filePath) + } catch (error) { + alert(error.message) + } finally { + setUploading(false) + } + } + + return ( +
+ {avatarUrl ? ( + Avatar + ) : ( +
+ )} +
+ + +
+
+ ) +} +``` + + +### Add the new widget + +And then we can add the widget to the Account page: + + +```jsx title="components/Account.js" +// Import the new component +import Avatar from './Avatar' + +// ... + +return ( +
+ {/* Add to the body */} + { + setAvatarUrl(url) + updateProfile({ username, website, avatar_url: url }) + }} + /> + {/* ... */} +
+) + +``` + +## Next steps + +At this stage you have a fully functional application! + +- Got a question? [Ask here](https://github.com/supabase/supabase/discussions). +- Sign in: [app.supabase.com](https://app.supabase.com) diff --git a/apps/reference/docs/guides/with-nuxt-3.mdx b/apps/reference/docs/guides/with-nuxt-3.mdx new file mode 100644 index 00000000000..529b3c41bfb --- /dev/null +++ b/apps/reference/docs/guides/with-nuxt-3.mdx @@ -0,0 +1,544 @@ +--- +id: with-nuxt-3 +title: 'Quickstart: Nuxt 3' +description: Learn how to use Supabase in your Nuxt 3 App. +sidebar_label: Nuxt 3 +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +## Intro + +This example provides the steps to build a simple user management app (from scratch!) using Supabase and Nuxt 3. It includes: + +- Supabase [Database](/docs/guides/database): a Postgres database for storing your user data. +- Supabase [Auth](/docs/guides/auth): users can sign in with magic links (no passwords, only email). +- Supabase [Storage](/docs/guides/storage): users can upload a photo. +- [Row Level Security](/docs/guides/auth#row-level-security): data is protected so that individuals can only access their own data. +- Instant [APIs](/docs/guides/api): APIs will be automatically generated when you create your database tables. + +By the end of this guide you'll have an app which allows users to login and update some basic profile details: + +![Supabase User Management example](/img/user-management-demo.png) + +### Github + +Whenever you get stuck at any point, take a look at [this repo](https://github.com/supabase-community/nuxt3-quickstarter). + +## Project set up + +Before we start building we're going to set up our Database and API. This is as simple as starting a new Project in Supabase +and then creating a "schema" inside the database. + +### Create a project + +1. Go to [app.supabase.com](https://app.supabase.com). +1. Click on "New Project". +1. Enter your project details. +1. Wait for the new database to launch. + +### Set up the database schema + +Now we are going to set up the database schema. We can use the "User Management Starter" quickstart in the SQL Editor, +or you can just copy/paste the SQL from below and run it yourself. + + + + +1. Go to the [SQL Editor](https://app.supabase.com/project/_/sql) page in the Dashboard. +2. Click **User Management Starter**. +3. Click **Run**. + + + + + + +```sql +-- Create a table for public "profiles" +create table profiles ( + id uuid references auth.users not null, + updated_at timestamp with time zone, + username text unique, + avatar_url text, + website text, + + primary key (id), + unique(username), + constraint username_length check (char_length(username) >= 3) +); + +alter table profiles enable row level security; + +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 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; + +-- Set up Storage! +insert into storage.buckets (id, name) +values ('avatars', 'avatars'); + +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' ); + +``` + + + + +### Get the API Keys + +Now that you've created some database tables, you are ready to insert data using the auto-generated API. +We just need to get the URL and `anon` key from the API settings. + +1. Go to the [Settings](https://app.supabase.com/project/_/settings) page in the Dashboard. +2. Click **API** in the sidebar. +3. Find your API `URL`, `anon`, and `service_role` keys on this page. + + + +## Building the App + +Let's start building the Vue 3 app from scratch. + +### Initialize a Nuxt 3 app + +We can use [`nuxi init`](https://v3.nuxtjs.org/getting-started/quick-start/) to create an app called `nuxt-user-management`: + +```bash +npx nuxi init nuxt-user-management + +cd nuxt-user-management +``` + +Then let's install the only additional dependency: [NuxtSupabase](https://supabase.nuxtjs.org/). We only need to import NuxtSupabase as a dev dependency. + +```bash +npm install @nuxtjs/supabase --save-dev +``` + +And finally we want to save the environment variables in a `.env`. +All we need are the API URL and the `anon` key that you copied [earlier](#get-the-api-keys). + +```bash title=".env" +SUPABASE_URL="YOUR_SUPABASE_URL" +SUPABASE_KEY="YOUR_SUPABASE_ANON_KEY" +``` + +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. +Amazing thing about [NuxtSupabase](https://supabase.nuxtjs.org/) is that setting environment variables is all we need to do in order to start using Supabase. +No need to initialize Supabase. The library will take care of it automatically. + +And one optional step is to update the CSS file `assets/main.css` to make the app look nice. +You can find the full contents of this file [here](https://github.com/supabase-community/nuxt3-quickstarter/blob/main/assets/main.css). + +```typescript title="nuxt.config.ts" +import { defineNuxtConfig } from 'nuxt' + +// https://v3.nuxtjs.org/api/configuration/nuxt.config +export default defineNuxtConfig({ + modules: ['@nuxtjs/supabase'], + css: ['@/assets/main.css'], +}) +``` + +### Set up Auth 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="/components/Auth.vue" + + + +``` + +### User state + +To access the user information in other places, will create a user state. Create a new file called `states.ts` and utilize `useState` method of Nuxt 3. + +```typescript title="composables/states.ts" +export const useUser = () => useState('user', () => null) +``` + +### Account component + +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.vue`. + +```html title="components/Account.vue" + + + +``` + +### Launch! + +Now that we have all the components in place, let's update `app.vue`: + +```html title="app.vue" + +``` + +We now need to create an index page called `pages/index.vue`: + +```html title="pages/index.vue" + + + +``` + +Once that's done, run this in a terminal window: + +```bash +npm run dev +``` + +And then open the browser to [localhost:3000](http://localhost:3000) and you should see the completed app. + +![Supabase Nuxt 3](/img/supabase-vue-3-demo.png) + +## Bonus: Profile photos + +Every Supabase project is configured with [Storage](/docs/guides/storage) for managing large files like photos and videos. + +### Create an upload widget + +Let's create an avatar for the user so that they can upload a profile photo. We can start by creating a new component: + +```html title="components/Avatar.vue" + + + +``` + +### Add the new widget + +And then we can add the widget to the Account page: + +```html title="components/Account.vue" + + + +``` + +That is it! You should now be able to upload a profile photo to Supabase Storage. + +## Next steps + +At this stage you have a fully functional application! + +- Got a question? [Ask here](https://github.com/supabase/supabase/discussions). +- Sign in: [app.supabase.com](https://app.supabase.com) diff --git a/apps/reference/docs/guides/with-react.mdx b/apps/reference/docs/guides/with-react.mdx new file mode 100644 index 00000000000..db22e129800 --- /dev/null +++ b/apps/reference/docs/guides/with-react.mdx @@ -0,0 +1,529 @@ +--- +id: with-react +title: 'Quickstart: React' +description: Learn how to use Supabase in your React App. +sidebar_label: React +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +## Intro + +This example provides the steps to build a simple user management app (from scratch!) using Supabase and React. It includes: + +- Supabase [Database](/docs/guides/database): a Postgres database for storing your user data. +- Supabase [Auth](/docs/guides/auth): users can sign in with magic links (no passwords, only email). +- Supabase [Storage](/docs/guides/storage): users can upload a photo. +- [Row Level Security](/docs/guides/auth#row-level-security): data is protected so that individuals can only access their own data. +- Instant [APIs](/docs/guides/api): APIs will be automatically generated when you create your database tables. + +By the end of this guide you'll have an app which allows users to login and update some basic profile details: + +![Supabase User Management example](/img/user-management-demo.png) + + + +## Project set up + +Before we start building we're going to set up our Database and API. This is as simple as starting a new Project in Supabase +and then creating a "schema" inside the database. + +### Create a project + +1. Go to [app.supabase.com](https://app.supabase.com). +1. Click on "New Project". +1. Enter your project details. +1. Wait for the new database to launch. + +### Set up the database schema + +Now we are going to set up the database schema. We can use the "User Management Starter" quickstart in the SQL Editor, +or you can just copy/paste the SQL from below and run it yourself. + + + + +1. Go to the [SQL Editor](https://app.supabase.com/project/_/sql) page in the Dashboard. +2. Click **User Management Starter**. +3. Click **Run**. + + + + + + +```sql +-- Create a table for public "profiles" +create table profiles ( + id uuid references auth.users not null, + updated_at timestamp with time zone, + username text unique, + avatar_url text, + website text, + + primary key (id), + unique(username), + constraint username_length check (char_length(username) >= 3) +); + +alter table profiles enable row level security; + +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 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; + +-- Set up Storage! +insert into storage.buckets (id, name) +values ('avatars', 'avatars'); + +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' ); + +``` + + + + +### Get the API Keys + +Now that you've created some database tables, you are ready to insert data using the auto-generated API. +We just need to get the URL and `anon` key from the API settings. + +1. Go to the [Settings](https://app.supabase.com/project/_/settings) page in the Dashboard. +2. Click **API** in the sidebar. +3. Find your API `URL`, `anon`, and `service_role` keys on this page. + + + +## Building the App + +Let's start building the React app from scratch. + +### Initialize a React app + +We can use [Create React App](https://create-react-app.dev/docs/getting-started/) to initialize +an app called `supabase-react`: + +```bash +npx create-react-app supabase-react +cd supabase-react +``` + +Then let's install the only additional dependency: [supabase-js](https://github.com/supabase/supabase-js) + +```bash +npm install @supabase/supabase-js +``` + +And finally we want to save the environment variables in a `.env`. +All we need are the API URL and the `anon` key that you copied [earlier](#get-the-api-keys). + +```bash title=".env" +REACT_APP_SUPABASE_URL=YOUR_SUPABASE_URL +REACT_APP_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="src/supabaseClient.js" +import { createClient } from '@supabase/supabase-js' + +const supabaseUrl = process.env.REACT_APP_SUPABASE_URL +const supabaseAnonKey = process.env.REACT_APP_SUPABASE_ANON_KEY + +export const supabase = createClient(supabaseUrl, supabaseAnonKey) +``` + +And one optional step is to update the CSS file `src/index.css` to make the app look nice. +You can find the full contents of this file [here](https://raw.githubusercontent.com/supabase/supabase/master/examples/user-management/react-user-management/src/index.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. + +```jsx title="/src/Auth.js" +import { useState } from 'react' +import { supabase } from './supabaseClient' + +export default function Auth() { + const [loading, setLoading] = useState(false) + const [email, setEmail] = useState('') + + const handleLogin = async (e) => { + e.preventDefault() + + try { + setLoading(true) + const { error } = await supabase.auth.signIn({ email }) + if (error) throw error + alert('Check your email for the login link!') + } catch (error) { + alert(error.error_description || error.message) + } finally { + setLoading(false) + } + } + + return ( +
+
+

Supabase + React

+

Sign in via magic link with your email below

+ {loading ? ( + 'Sending magic link...' + ) : ( +
+ + setEmail(e.target.value)} + /> + +
+ )} +
+
+ ) +} +``` + +### 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`. + +```jsx title="src/Account.js" +import { useState, useEffect } from 'react' +import { supabase } from './supabaseClient' + +const Account = ({ session }) => { + const [loading, setLoading] = useState(true) + const [username, setUsername] = useState(null) + const [website, setWebsite] = useState(null) + const [avatar_url, setAvatarUrl] = useState(null) + + useEffect(() => { + getProfile() + }, [session]) + + const getProfile = async () => { + try { + setLoading(true) + const user = supabase.auth.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.message) + } finally { + setLoading(false) + } + } + + const updateProfile = async (e) => { + e.preventDefault() + + try { + setLoading(true) + const user = supabase.auth.user() + + const updates = { + id: user.id, + username, + website, + avatar_url, + 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 { + setLoading(false) + } + } + + return ( +
+ {loading ? ( + 'Saving ...' + ) : ( +
+
Email: {session.user.email}
+
+ + setUsername(e.target.value)} + /> +
+
+ + setWebsite(e.target.value)} + /> +
+
+ +
+
+ )} + +
+ ) +} + +export default Account +``` + +### Launch! + +Now that we have all the components in place, let's update `App.js`: + +```jsx title="src/App.js" +import './index.css' +import { useState, useEffect } from 'react' +import { supabase } from './supabaseClient' +import Auth from './Auth' +import Account from './Account' + +export default function App() { + const [session, setSession] = useState(null) + + useEffect(() => { + setSession(supabase.auth.session()) + + supabase.auth.onAuthStateChange((_event, session) => { + setSession(session) + }) + }, []) + + return ( +
+ {!session ? : } +
+ ) +} +``` + +Once that's done, run this in a terminal window: + +```bash +npm start +``` + +And then open the browser to [localhost:3000](http://localhost:3000) and you should see the completed app. + +![Supabase React](/img/supabase-react-demo.png) + +## Bonus: Profile photos + +Every Supabase project is configured with [Storage](/docs/guides/storage) for managing large files like photos and videos. + +### Add @reach/visually-hidden + +The upload widget uses one additional npm library. You can install it like so: `npm install @reach/visually-hidden`. + +### 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: + +```jsx title="src/Avatar.js" +import { useEffect, useState } from 'react' +import { supabase } from './supabaseClient' +import VisuallyHidden from '@reach/visually-hidden' + +export default function Avatar({ url, size, onUpload }) { + const [avatarUrl, setAvatarUrl] = useState(null) + const [uploading, setUploading] = useState(false) + + useEffect(() => { + if (url) downloadImage(url) + }, [url]) + + const downloadImage = async (path) => { + 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.message) + } + } + + const uploadAvatar = 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 = `${Math.random()}.${fileExt}` + const filePath = `${fileName}` + + let { error: uploadError } = await supabase.storage.from('avatars').upload(filePath, file) + + if (uploadError) { + throw uploadError + } + + onUpload(filePath) + } catch (error) { + alert(error.message) + } finally { + setUploading(false) + } + } + + return ( +
+ {avatarUrl + {uploading ? "Uploading..." : ( + <> + + + + + + )} +
+ ) +} +``` + +### Add the new widget + +And then we can add the widget to the Account page: + +```jsx title="src/Account.js" +// Import the new component +import Avatar from './Avatar' + +// ... + +return ( +
+ {/* Add to the body */} + { + setAvatarUrl(url) + updateProfile({ username, website, avatar_url: url }) + }} + /> + {/* ... */} +
+) +``` + +## Next steps + +At this stage you have a fully functional application! + +- Got a question? [Ask here](https://github.com/supabase/supabase/discussions). +- Sign in: [app.supabase.com](https://app.supabase.com) diff --git a/apps/reference/docs/guides/with-redwoodjs.mdx b/apps/reference/docs/guides/with-redwoodjs.mdx new file mode 100644 index 00000000000..7a46bb920db --- /dev/null +++ b/apps/reference/docs/guides/with-redwoodjs.mdx @@ -0,0 +1,764 @@ +--- +id: with-redwoodjs +title: 'Quickstart: RedwoodJS' +description: Learn how to use Supabase in your RedwoodJS App. +sidebar_label: RedwoodJS +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +## Intro + +For the sake of consistency with the other framework Quickstart examples, we'll build a RedwoodJS a little differently than normal. + +We **_won't use_** Prisma to connect to the Supabase Postgres database or [Prisma migrations](https://redwoodjs.com/docs/cli-commands#prisma-migrate) as one typically might in a Redwood app. +Instead, we'll rely on the Supabase client to do some of the work on the **web** side and use the client again on the **API** side to do data fetching as well. + +That means you will want to refrain from running any `yarn rw prisma migrate` commands and also double check your build commands on deployment to ensure Prisma won't reset your database. + +:::note +TLDR; Prisma currently doesn't support cross-schema foreign keys, so introspecting the schema fails due to how your Supabase `public` schema references the `auth.users`. +::: + +This example provides the steps to build a simple user management app (from scratch!) using Supabase and [RedwoodJS](https://redwoodjs.com/docs/introduction). It includes: + +- Supabase [Database](/docs/guides/database): a Postgres database for storing your user data. +- Supabase [Auth](/docs/guides/auth): users can sign in with magic links (no passwords, only email). +- Supabase [Storage](/docs/guides/storage): users can upload a photo. +- Instant [APIs](/docs/guides/api): APIs will be automatically generated when you create your database tables. +- [Row Level Security](/docs/guides/auth#row-level-security): data is protected so that individuals can only access their own data. + +By the end of this guide you'll have an app which allows users to login and update some basic profile details: + +![Supabase User Management example](/img/user-management-demo.png) + +:::note +Note: For RedwoodJS apps, port will be 8910 +::: + +### GitHub + +If you get stuck at any point, take a look at [this repo](https://github.com/redwoodjs/redwoodjs-supabase-quickstart). + + + +## About RedwoodJS + +A Redwood application is split into two parts: a frontend and a backend. This is represented as two node projects within a single monorepo. + +The frontend project is called **`web`** and the backend project is called **`api`**. For clarity, we will refer to these in prose as **"sides"**, i.e. the "web side" and the "api side". +They are separate projects because code on the `web side` will end up running in the user's browser while code on the `api side` will run on a server somewhere. + +:::note +Important: When this guide refers to "API", that means the Supabase API and when it refers to "api side", that means the RedwoodJS `api side`. +::: + +The **`api side`** is an implementation of a GraphQL API. The business logic is organized into "services" that represent their own internal API and can be called both from external GraphQL requests and other internal services. + +The **`web side`** is built with React. Redwood's router makes it simple to map URL paths to React "Page" components (and automatically code-split your app on each route). +Pages may contain a "Layout" component to wrap content. They also contain "Cells" and regular React components. +Cells allow you to declaratively manage the lifecycle of a component that fetches and displays data. + +:::note +For the sake of consistency with the other framework Quickstart examples, we'll build a RedwoodJS a little differently than normal. +We **_won't use_** Prisma to connect to the Supabase Postgres database or [Prisma migrations](https://redwoodjs.com/docs/cli-commands#prisma-migrate) as one typically might in a Redwood app. +Instead, we'll rely on the Supabase client to do some of the work on the **`web`** side and use the client again on the **`api`** side to do data fetching as well. +::: + +## Project set up + +Before we start building we're going to set up our Database and API. This is as simple as starting a new Project in Supabase +and then creating a "schema" inside the database. + +:::note +When setting up Supabase, you'll interact with your project dashboard. However, most of the RedwoodJS setup steps will interact with the [Redwood CLI](https://redwoodjs.com/docs/cli-commands) to generate routes, pages, components, and more. +So be sure to have a terminal at the ready and in your project directory. +::: + +### Create a project + +1. Go to [app.supabase.com](https://app.supabase.com). +1. Click on "New Project". +1. Enter your project details. +1. Wait for the new database to launch. + +### Set up the database schema + +Now we are going to set up the database schema. We can use the "User Management Starter" quickstart in the SQL Editor, +or you can just copy/paste the SQL from below and run it yourself. + + + + +1. Go to the [SQL Editor](https://app.supabase.com/project/_/sql) page in the Dashboard. +2. Click **User Management Starter**. +3. Click **Run**. + + + + + + +```sql +-- Create a table for public "profiles" +create table profiles ( + id uuid references auth.users not null, + updated_at timestamp with time zone, + username text unique, + avatar_url text, + website text, + + primary key (id), + unique(username), + constraint username_length check (char_length(username) >= 3) +); + +alter table profiles enable row level security; + +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 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; + +-- Set up Storage! +insert into storage.buckets (id, name) +values ('avatars', 'avatars'); + +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' ); + +``` + + + + +#### Important Note about Prisma and Migrations + +:::note +Because this Quick Start does not use Prisma to manage the database schema, seed it, or run migrations, you **need** to take extra care when running some of the typical Redwood CLI commands. +::: + +### Get the API Keys + +Now that you've created some database tables, you are ready to insert data using the auto-generated API. +We just need to get the URL as well as the `anon`, `service_role` and `JWT_SECRET` keys from the API settings. + +1. Go to the [Settings](https://app.supabase.com/project/_/settings) page in the Dashboard. +2. Click **API** in the sidebar. +3. Find your API `URL`, `anon`, and `service_role` keys on this page. + + + +## Building the App + +Let's start building the RedwoodJS app from scratch. + +:::note +RedwoodJS requires Node.js (>=14.x <=16.x) and Yarn (>=1.15). +::: + +Make sure you have installed yarn since RedwoodJS relies on it to [manage its packages in workspaces](https://classic.yarnpkg.com/lang/en/docs/workspaces/) for its `web` and `api` "sides". + +### Initialize a RedwoodJS app + +We can use [Create Redwood App](https://redwoodjs.com/docs/quick-start) command to initialize +an app called `supabase-redwoodjs`: + +```bash +yarn create redwood-app supabase-redwoodjs +cd supabase-redwoodjs +``` + +While the app is installing, you should see: + +```bash +✔ Creating Redwood app + ✔ Checking node and yarn compatibility + ✔ Creating directory 'supabase-redwoodjs' +✔ Installing packages + ✔ Running 'yarn install'... (This could take a while) +✔ Convert TypeScript files to JavaScript +✔ Generating types + +Thanks for trying out Redwood! +``` + +Then let's install the only additional dependency [supabase-js](https://github.com/supabase/supabase-js) by running the `setup auth` command: + +```bash +yarn redwood setup auth supabase +``` + +When prompted: + +Overwrite existing /api/src/lib/auth.[jt]s? +::: + +Say, **yes** and it will setup the Supabase client in your app and also provide hooks used with Supabase authentication. + +```bash +✔ Generating auth lib... + ✔ Successfully wrote file `./api/src/lib/auth.js` + ✔ Adding auth config to web... + ✔ Adding auth config to GraphQL API... + ✔ Adding required web packages... + ✔ Installing packages... + ✔ One more thing... + + You will need to add your Supabase URL (SUPABASE_URL), public API KEY, + and JWT SECRET (SUPABASE_KEY, and SUPABASE_JWT_SECRET) to your .env file. +``` + +Next, we want to save the environment variables in a `.env`. +We need the `API URL` as well as the `anon` and `jwt_secret` keys that you copied [earlier](#get-the-api-keys). + +```bash title=".env" +SUPABASE_URL=YOUR_SUPABASE_URL +SUPABASE_KEY=YOUR_SUPABASE_ANON_KEY +SUPABASE_JWT_SECRET=YOUR_SUPABASE_JWT_SECRET +``` + +And finally, you will also need to save **just** the `web side` environment variables to the `redwood.toml`. + +```bash title="redwood.toml" +[web] + title = "Supabase Redwood Quickstart" + port = 8910 + apiProxyPath = "/.redwood/functions" + includeEnvironmentVariables = ["SUPABASE_URL", "SUPABASE_KEY"] +[api] + port = 8911 +[browser] + open = true +``` + +These variables will be exposed on the browser, and that's completely fine. +They allow your web app to initialize the Supabase client with your public anon key +since we have [Row Level Security](/docs/guides/auth#row-level-security) enabled on our Database. + +You'll see these being used to configure your Supabase client in `web/src/App.js`: + +```js title="web/src/App.js" +// ... Redwood imports +import { AuthProvider } from '@redwoodjs/auth' +import { createClient } from '@supabase/supabase-js' + +// ... + +const supabaseClient = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_KEY) + +const App = () => ( + + + + + + + + + +) + +export default App +``` + +And one optional step is to update the CSS file `web/src/index.css` to make the app look nice. +You can find the full contents of this file [here](https://raw.githubusercontent.com/supabase/supabase/master/examples/user-management/react-user-management/src/index.css). + +### Start RedwoodJS and your first Page + +Let's test our setup at the moment by starting up the app: + +```bash +yarn rw dev +``` + +:::note +Note: You can also use the alias `rw` for `redwood`, as in `yarn rw` to run Redwood CLI commands +::: + +You should see a "Welcome to RedwoodJS" page and a message about not having any pages yet. + +So, let's create a "home" page: + +```bash +yarn rw generate page home / + +✔ Generating page files... + ✔ Successfully wrote file `./web/src/pages/HomePage/HomePage.stories.js` + ✔ Successfully wrote file `./web/src/pages/HomePage/HomePage.test.js` + ✔ Successfully wrote file `./web/src/pages/HomePage/HomePage.js` +✔ Updating routes file... +✔ Generating types ... +``` + +:::note +Note: the slash `/` is important here as it creates a root level route. +::: + +You can stop the `dev` server if you want; to see your changes, just be sure to run `yarn rw dev` again. + +You should see the `Home` page route in `web/src/Routes.js`: + +```bash title="web/src/Routes.js" +import { Router, Route } from '@redwoodjs/router' + +const Routes = () => { + return ( + + + + + ) +} + +export default Routes +``` + +### Set up a Login component + +Let's set up a Redwood component to manage logins and sign ups. We'll use Magic Links, so users can sign in with their email without using passwords. + +```bash +yarn rw g component auth + + ✔ Generating component files... + ✔ Successfully wrote file `./web/src/components/Auth/Auth.test.js` + ✔ Successfully wrote file `./web/src/components/Auth/Auth.stories.js` + ✔ Successfully wrote file `./web/src/components/Auth/Auth.js` + +``` + +Now, update the `Auth.js` component to contain: + +```jsx title="/web/src/components/Auth/Auth.js" +import { useState } from 'react' +import { useAuth } from '@redwoodjs/auth' + +const Auth = () => { + const { logIn } = useAuth() + const [loading, setLoading] = useState(false) + const [email, setEmail] = useState('') + + const handleLogin = async (email) => { + try { + setLoading(true) + const { error } = await logIn({ email }) + if (error) throw error + alert('Check your email for the login link!') + } catch (error) { + alert(error.error_description || error.message) + } finally { + setLoading(false) + } + } + + return ( +
+
+

Supabase + RedwoodJS

+

Sign in via magic link with your email below

+
+ setEmail(e.target.value)} + /> +
+
+ +
+
+
+ ) +} + +export default Auth +``` + +### Set up an Account component + +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`. + +```bash +yarn rw g component account + + ✔ Generating component files... + ✔ Successfully wrote file `./web/src/components/Account/Account.test.js` + ✔ Successfully wrote file `./web/src/components/Account/Account.stories.js` + ✔ Successfully wrote file `./web/src/components/Account/Account.js` +``` + +And then update the file to contain: + +```jsx title="web/src/components/Account/Account.js" +import { useState, useEffect } from 'react' +import { useAuth } from '@redwoodjs/auth' + +const Account = () => { + const { client: supabase, currentUser, logOut } = useAuth() + const [loading, setLoading] = useState(true) + const [username, setUsername] = useState(null) + const [website, setWebsite] = useState(null) + const [avatar_url, setAvatarUrl] = useState(null) + + useEffect(() => { + getProfile() + }, [supabase.auth.session]) + + async function getProfile() { + try { + setLoading(true) + const user = supabase.auth.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.message) + } finally { + setLoading(false) + } + } + + async function updateProfile({ username, website, avatar_url }) { + try { + setLoading(true) + const user = supabase.auth.user() + + const updates = { + id: user.id, + username, + website, + avatar_url, + 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 + } + + alert('Updated profile!') + } catch (error) { + alert(error.message) + } finally { + setLoading(false) + } + } + + return ( +
+
+

Supabase + RedwoodJS

+

Your profile

+
+
+ + +
+
+ + setUsername(e.target.value)} + /> +
+
+ + setWebsite(e.target.value)} + /> +
+ +
+ +
+ +
+ +
+
+
+
+ ) +} + +export default Account +``` + +:::note +Note: You'll see the use of `useAuth()` several times in the quickstart. Redwood's `useAuth` hook provides convenient ways to access +logIn, logOut, currentUser, and access the `supabase` authenticate client. We'll use it to get an instance +of the supabase client to interact with your API. +::: + +### Update Home Page + +Now that we have all the components in place, let's update your `HomePage` page to use them: + +```jsx title="web/src/pages/HomePage/HomePage.js" +import { useAuth } from '@redwoodjs/auth' +import { MetaTags } from '@redwoodjs/web' + +import Account from 'src/components/Account' +import Auth from 'src/components/Auth' + +const HomePage = () => { + const { isAuthenticated } = useAuth() + + return ( + <> + + {!isAuthenticated ? : } + + ) +} + +export default HomePage +``` + +> What we're doing here is showing the sign in form if you aren't logged in and your account profile if you are. + +### Launch! + +Once that's done, run this in a terminal window to launch the `dev` server: + +```bash +yarn rw dev +``` + +And then open the browser to [localhost:8910](http://localhost:8910) and you should see the completed app. + +![Supabase RedwoodJS](/img/supabase-redwoodjs-demo.png) + +## Bonus: Profile photos + +Every Supabase project is configured with [Storage](/docs/guides/storage) for managing large files like photos and videos. + +### Create an upload widget + +Let's create an avatar for the user so that they can upload a profile photo. We can start by creating a new component: + +```bash +yarn rw g component avatar + ✔ Generating component files... + ✔ Successfully wrote file `./web/src/components/Avatar/Avatar.test.js` + ✔ Successfully wrote file `./web/src/components/Avatar/Avatar.stories.js` + ✔ Successfully wrote file `./web/src/components/Avatar/Avatar.js` +``` + +Now, update your Avatar component to contain the following widget: + +```jsx title="web/src/components/Avatar/Avatar.js" +import { useEffect, useState } from 'react' +import { useAuth } from '@redwoodjs/auth' + +const Avatar = ({ url, size, onUpload }) => { + const { client: supabase } = useAuth() + + const [avatarUrl, setAvatarUrl] = useState(null) + const [uploading, setUploading] = useState(false) + + useEffect(() => { + if (url) downloadImage(url) + }, [url]) + + async function downloadImage(path) { + 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.message) + } + } + + async function uploadAvatar(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 = `${Math.random()}.${fileExt}` + const filePath = `${fileName}` + + let { error: uploadError } = await supabase.storage.from('avatars').upload(filePath, file) + + if (uploadError) { + throw uploadError + } + + onUpload(filePath) + } catch (error) { + alert(error.message) + } finally { + setUploading(false) + } + } + + return ( +
+ {avatarUrl ? ( + Avatar + ) : ( +
+ )} +
+ + +
+
+ ) +} + +export default Avatar +``` + +### Add the new widget + +And then we can add the widget to the Account component: + +```jsx title="web/src/components/Account/Account.js" +// Import the new component +import Avatar from 'src/components/Avatar' + +// ... + +return ( +
+ {/* Add to the body */} + { + setAvatarUrl(url) + updateProfile({ username, website, avatar_url: url }) + }} + /> + {/* ... */} +
+) +``` + +## Next steps + +At this stage you have a fully functional application! + +- Got a question? [Ask here](https://github.com/supabase/supabase/discussions). +- Sign in: [app.supabase.com](https://app.supabase.com) +- Learn more about [RedwoodJS](https://redwoodjs.com) +- Visit the [RedwoodJS Discourse Community](https://community.redwoodjs.com) diff --git a/apps/reference/docs/guides/with-solidjs.mdx b/apps/reference/docs/guides/with-solidjs.mdx new file mode 100644 index 00000000000..953c44500e9 --- /dev/null +++ b/apps/reference/docs/guides/with-solidjs.mdx @@ -0,0 +1,526 @@ +--- +id: with-solidjs +title: 'Quickstart: SolidJS' +description: Learn how to use Supabase in your SolidJS App. +sidebar_label: SolidJS +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +## Intro + +This example provides the steps to build a simple user management app (from scratch!) using Supabase and Solid JS. It includes: + +- Supabase [Database](/docs/guides/database): a Postgres database for storing your user data. +- Supabase [Auth](/docs/guides/auth): users can sign in with magic links (no passwords, only email). +- Supabase [Storage](/docs/guides/storage): users can upload a photo. +- [Row Level Security](/docs/guides/auth#row-level-security): data is protected so that individuals can only access their own data. +- Instant [APIs](/docs/guides/api): APIs will be automatically generated when you create your database tables. + +By the end of this guide you'll have an app which allows users to login and update some basic profile details: + +![Supabase User Management example](/img/user-management-demo.png) + + + +## Project set up + +Before we start building we're going to set up our Database and API. This is as simple as starting a new Project in Supabase +and then creating a "schema" inside the database. + +### Create a project + +1. Go to [app.supabase.com](https://app.supabase.com). +1. Click on "New Project". +1. Enter your project details. +1. Wait for the new database to launch. + +### Set up the database schema + +Now we are going to set up the database schema. We can use the "User Management Starter" quickstart in the SQL Editor, +or you can just copy/paste the SQL from below and run it yourself. + + + + +1. Go to the [SQL Editor](https://app.supabase.com/project/_/sql) page in the Dashboard. +2. Click **User Management Starter**. +3. Click **Run**. + + + + + + +```sql +-- Create a table for public "profiles" +create table profiles ( + id uuid references auth.users not null, + updated_at timestamp with time zone, + username text unique, + avatar_url text, + website text, + + primary key (id), + unique(username), + constraint username_length check (char_length(username) >= 3) +); + +alter table profiles enable row level security; + +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 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; + +-- Set up Storage! +insert into storage.buckets (id, name) +values ('avatars', 'avatars'); + +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' ); + +``` + + + + +### Get the API Keys + +Now that you've created some database tables, you are ready to insert data using the auto-generated API. +We just need to get the URL and `anon` key from the API settings. + +1. Go to the [Settings](https://app.supabase.com/project/_/settings) page in the Dashboard. +2. Click **API** in the sidebar. +3. Find your API `URL`, `anon`, and `service_role` keys on this page. + + + +## Building the App + +Let's start building the SolidJS app from scratch. + +### Initialize a SolidJS app + +We can use [Degit](https://github.com/Rich-Harris/degit) to initialize an app called `supabase-solid`: + +```bash +npx degit solidjs/templates/js supabase-solid +cd supabase-solid +``` + +Then let's install the only additional dependency: [supabase-js](https://github.com/supabase/supabase-js) + +```bash +npm install @supabase/supabase-js +``` + +And finally we want to save the environment variables in a `.env`. +All we need are the API URL and the `anon` key that you copied [earlier](#get-the-api-keys). + +```bash title=".env" +VITE_SUPABASE_URL=YOUR_SUPABASE_URL +VITE_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="src/supabaseClient.jsx" +import { createClient } from '@supabase/supabase-js' + +const supabaseUrl = import.meta.env.VITE_SUPABASE_URL +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/index.css` to make the app look nice. +You can find the full contents of this file [here](https://raw.githubusercontent.com/supabase/supabase/master/examples/user-management/react-user-management/src/index.css). + +### Set up a Login component + +Let's set up a SolidJS component to manage logins and sign ups. We'll use Magic Links, so users can sign in with their email without using passwords. + +```jsx title="/src/Auth.jsx" +import { createSignal } from 'solid-js' +import { supabase } from './supabaseClient' + +export default function Auth() { + const [loading, setLoading] = createSignal(false) + const [email, setEmail] = createSignal('') + + const handleLogin = async (e) => { + e.preventDefault() + + try { + setLoading(true) + const { error } = await supabase.auth.signIn({ email: email() }) + if (error) throw error + alert('Check your email for the login link!') + } catch (error) { + alert(error.error_description || error.message) + } finally { + setLoading(false) + } + } + + return ( +
+
+

Supabase + SolidJS

+

Sign in via magic link with your email below

+ {loading() ? ( + 'Sending magic link...' + ) : ( +
+ + setEmail(e.target.value)} + /> + +
+ )} +
+
+ ) +} +``` + +### 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`. + +```jsx title="src/Account.jsx" +import { createSignal, createEffect } from 'solid-js' +import { supabase } from './supabaseClient' + +const Account = (props) => { + const [loading, setLoading] = createSignal(true) + const [username, setUsername] = createSignal(null) + const [website, setWebsite] = createSignal(null) + const [avatar_url, setAvatarUrl] = createSignal(null) + + createEffect(() => { + props.session + getProfile() + }) + + const getProfile = async () => { + try { + setLoading(true) + const user = supabase.auth.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.message) + } finally { + setLoading(false) + } + } + + const updateProfile = async (e) => { + e.preventDefault() + + try { + setLoading(true) + const user = supabase.auth.user() + + const updates = { + id: user.id, + username: username(), + website: website(), + avatar_url: avatar_url(), + 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 { + setLoading(false) + } + } + + return ( +
+ {loading() ? ( + 'Saving ...' + ) : ( +
+
Email: {props.session.user.email}
+
+ + setUsername(e.target.value)} + /> +
+
+ + setWebsite(e.target.value)} + /> +
+
+ +
+
+ )} + +
+ ) +} + +export default Account +``` + +### Launch! + +Now that we have all the components in place, let's update `App.js`: + +```jsx title="src/App.jsx" +import './index.css' +import { createSignal, createEffect } from 'solid-js' +import { supabase } from './supabaseClient' +import Auth from './Auth' +import Account from './Account' + +export default () => { + const [session, setSession] = createSignal(null) + + createEffect(() => { + setSession(supabase.auth.session()) + + supabase.auth.onAuthStateChange((_event, session) => { + setSession(session) + }) + }) + + return ( +
+ {!session() ? : } +
+ ) +} +``` + +Once that's done, run this in a terminal window: + +```bash +npm start +``` + +And then open the browser to [localhost:3000](http://localhost:3000) and you should see the completed app. + +![Supabase SolidJS](/img/supabase-solidjs-demo.png) + +## Bonus: Profile photos + +Every Supabase project is configured with [Storage](/docs/guides/storage) for managing large files like photos and videos. + +### Create an upload widget + +Let's create an avatar for the user so that they can upload a profile photo. We can start by creating a new component: + +```jsx title="src/Avatar.jsx" +import { createEffect, createSignal } from 'solid-js' +import { supabase } from './supabaseClient' + +export default (props) => { + const [avatarUrl, setAvatarUrl] = createSignal(null) + const [uploading, setUploading] = createSignal(false) + + createEffect(() => { + if (props.url()) downloadImage(props.url()) + }) + + const downloadImage = async (path) => { + 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.message) + } + } + + const uploadAvatar = 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 = `${Math.random()}.${fileExt}` + const filePath = `${fileName}` + + let { error: uploadError } = await supabase.storage.from('avatars').upload(filePath, file) + + if (uploadError) { + throw uploadError + } + + props.onUpload(event, filePath) + } catch (error) { + alert(error.message) + } finally { + setUploading(false) + } + } + + return ( +
+ {avatarUrl() + {uploading() ? ( + 'Uploading...' + ) : ( + <> + + + + + + )} +
+ ) +} +``` + +### Add the new widget + +And then we can add the widget to the Account page: + +```jsx title="src/Account.jsx" +// Import the new component +import Avatar from './Avatar' + +// ... + +return ( +
+ {/* Add to the body */} + { + setAvatarUrl(url) + updateProfile(e) + }} + /> + {/* ... */} +
+) +``` + +## Next steps + +At this stage you have a fully functional application! + +- Got a question? [Ask here](https://github.com/supabase/supabase/discussions). +- Sign in: [app.supabase.com](https://app.supabase.com) diff --git a/apps/reference/docs/guides/with-svelte.mdx b/apps/reference/docs/guides/with-svelte.mdx new file mode 100644 index 00000000000..b1f5c3463ec --- /dev/null +++ b/apps/reference/docs/guides/with-svelte.mdx @@ -0,0 +1,537 @@ +--- +id: with-svelte +title: "Quickstart: Svelte" +description: Learn how to use Supabase in your Svelte App. +sidebar_label: Svelte +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +## Intro + +This example provides the steps to build a simple user management app (from scratch!) using Supabase and Svelte. It includes: + +- Supabase [Database](/docs/guides/database): a Postgres database for storing your user data. +- Supabase [Auth](/docs/guides/auth): users can sign in with magic links (no passwords, only email). +- Supabase [Storage](/docs/guides/storage): users can upload a photo. +- [Row Level Security](/docs/guides/auth#row-level-security): data is protected so that individuals can only access their own data. +- Instant [APIs](/docs/guides/api): APIs will be automatically generated when you create your database tables. + +By the end of this guide you'll have an app which allows users to login and update some basic profile details: + +![Supabase User Management example](/img/user-management-demo.png) + +### GitHub +Whenever you get stuck at any point, take a look at [this repo](https://github.com/yustarandomname/svelte-supabase-quickstart). + +## Project set up + +Before we start building we're going to set up our Database and API. This is as simple as starting a new Project in Supabase +and then creating a "schema" inside the database. + +### Create a project + +1. Go to [app.supabase.com](https://app.supabase.com). +1. Click on "New Project". +1. Enter your project details. +1. Wait for the new database to launch. + + +### Set up the database schema + +Now we are going to set up the database schema. We can use the "User Management Starter" quickstart in the SQL Editor, +or you can just copy/paste the SQL from below and run it yourself. + + + + +1. Go to the [SQL Editor](https://app.supabase.com/project/_/sql) page in the Dashboard. +2. Click **User Management Starter**. +3. Click **Run**. + + + + + + +```sql +-- Create a table for public "profiles" +create table profiles ( + id uuid references auth.users not null, + updated_at timestamp with time zone, + username text unique, + avatar_url text, + website text, + + primary key (id), + unique(username), + constraint username_length check (char_length(username) >= 3) +); + +alter table profiles enable row level security; + +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 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; + +-- Set up Storage! +insert into storage.buckets (id, name) +values ('avatars', 'avatars'); + +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' ); + +``` + + + + + +### Get the API Keys + + +Now that you've created some database tables, you are ready to insert data using the auto-generated API. +We just need to get the URL and `anon` key from the API settings. + +1. Go to the [Settings](https://app.supabase.com/project/_/settings) page in the Dashboard. +2. Click **API** in the sidebar. +3. Find your API `URL`, `anon`, and `service_role` keys on this page. + + + +## Building the App + +Let's start building the Svelte app from scratch. + +### Initialize a Svelte app + +We can use the [Quickstart Svelte Template](https://svelte.dev/blog/the-easiest-way-to-get-started) to initialize +an app called `supabase-svelte`: + +```bash +npx degit sveltejs/template supabase-svelte +cd supabase-svelte +``` + +Then let's install the only additional dependency: [supabase-js](https://github.com/supabase/supabase-js) + +```bash +npm install @supabase/supabase-js +``` + +And finally we want to save the environment variables in a `.env`. +All we need are the API URL and the `anon` key that you copied [earlier](#get-the-api-keys). + +```bash title=".env" +SVELTE_APP_SUPABASE_URL=YOUR_SUPABASE_URL +SVELTE_APP_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY +``` + +Our app is almost functional, to make svelte work with supabase and .env files we first need to change the `rollup.config.js` file a bit. +Supabase imports `json` files, to convert .json files to ES6 modules we need the `@rollup/plugin-json` install it by running: + +```bash + npm install --save-dev @rollup/plugin-json +``` + +Furthermore, to use the .env with svelte we need another rollup plugin. Install: + +```bash + npm install --save-dev dotenv @rollup/plugin-replace +``` + +and add these plugins to the `rollup.config.js` file. + +```js title="rollup.config.js" + import { config } from 'dotenv'; + import replace from '@rollup/plugin-replace'; + import json from '@rollup/plugin-json' + + export default { + plugins: [ + replace({ + __api: JSON.stringify({ + env: { + isProd: production, + ...config().parsed // attached the .env config + } + }), + delimiters: ['', ''] + }), + json(), + // ... + ], + // ... + } +``` + +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="src/supabaseClient.js" +import { createClient } from '@supabase/supabase-js' + +const supabaseUrl = __api.env.SVELTE_APP_SUPABASE_URL +const supabaseAnonKey = __api.env.SVELTE_APP_SUPABASE_ANON_KEY + +export const supabase = createClient(supabaseUrl, supabaseAnonKey) +``` + +And one optional step is to update the CSS file `public/global.css` to make the app look nice. +You can find the full contents of this file [here](https://raw.githubusercontent.com/supabase/supabase/master/examples/user-management/react-user-management/src/index.css). + +### Set up a Login component + +Let's set up a Svelte 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/Auth.svelte" + + +
+
+

Supabase + Svelte

+

Sign in via magic link with your email below

+
+ +
+
+ +
+
+
+``` + +### User store +To access the user information in other places, we use a writable store. Create a new file called `sessionStore.js` +```javascript title="src/sessionStore.js" +import { writable } from 'svelte/store'; + +export const user = writable(false); +``` + + +### 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.svelte`. + +```html title="src/Profile.svelte" + + +
+
+ + +
+
+ + +
+
+ + +
+ +
+ +
+ +
+ +
+
+``` + + + +### Launch! + +Now that we have all the components in place, let's update `App.svelte`: + +```html title="src/App.svelte" + + +
+ {#if $user} + + {:else} + + {/if} +
+``` + +Once that's done, run this in a terminal window: + +```bash +npm run dev +``` + +And then open the browser to [localhost:5000](http://localhost:5000) and you should see the completed app. + +> ⚠️ WARNING: Svelte uses by default `port 5000`, Supabase uses `port 3000`. To change the redirection port for supabase go to: `Authentication > Settings` and change the `Site Url` to `localhost:5000` + +![Supabase Svelte](/img/supabase-svelte-demo.png) + +## Bonus: Profile photos + +Every Supabase project is configured with [Storage](/docs/guides/storage) for managing large files like photos and videos. + +### Create an upload widget + +Let's create an avatar for the user so that they can upload a profile photo. We can start by creating a new component: + +```html title="src/Avatar.svelte" + + +
+ {#if path} + Avatar + {:else} +
+ {/if} + +
+ + +
+
+``` + + +### Add the new widget + +And then we can add the widget to the Account page: + + +```html title="src/Profile.svelte" + + +
+ + + + + + +``` + +## Next steps + +At this stage you have a fully functional application! + +- Got a question? [Ask here](https://github.com/supabase/supabase/discussions). +- Sign in: [app.supabase.com](https://app.supabase.com) diff --git a/apps/reference/docs/guides/with-sveltekit.mdx b/apps/reference/docs/guides/with-sveltekit.mdx new file mode 100644 index 00000000000..ddf83b7f853 --- /dev/null +++ b/apps/reference/docs/guides/with-sveltekit.mdx @@ -0,0 +1,500 @@ +--- +id: with-sveltekit +title: "Quickstart: SvelteKit" +description: Learn how to use Supabase in your SvelteKit App. +sidebar_label: SvelteKit +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +## Intro + +This example provides the steps to build a simple user management app (from scratch!) using Supabase and Svelte. It includes: + +- Supabase [Database](/docs/guides/database): a Postgres database for storing your user data. +- Supabase [Auth](/docs/guides/auth): users can sign in with magic links (no passwords, only email). +- Supabase [Storage](/docs/guides/storage): users can upload a photo. +- [Row Level Security](/docs/guides/auth#row-level-security): data is protected so that individuals can only access their own data. +- Instant [APIs](/docs/guides/api): APIs will be automatically generated when you create your database tables. + +By the end of this guide you'll have an app which allows users to login and update some basic profile details: + +![Supabase User Management example](/img/user-management-demo.png) + +### Github +Whenever you get stuck at any point, take a look at [this repo](https://github.com/yustarandomname/svelte-supabase-quickstart). + +## Project set up + +Before we start building we're going to set up our Database and API. This is as simple as starting a new Project in Supabase +and then creating a "schema" inside the database. + +### Create a project + +1. Go to [app.supabase.com](https://app.supabase.com). +1. Click on "New Project". +1. Enter your project details. +1. Wait for the new project to launch. + + +### Set up the database schema + +Now we are going to set up the database schema. We can use the "User Management Starter" quickstart in the SQL Editor, +or you can just copy/paste the SQL from below and run it yourself. + + + + +1. Go to the [SQL Editor](https://app.supabase.com/project/_/sql) page in the Dashboard. +2. Click **User Management Starter**. +3. Click **Run**. + + + + + + +```sql +-- Create a table for public "profiles" +create table profiles ( + id uuid references auth.users not null, + updated_at timestamp with time zone, + username text unique, + avatar_url text, + website text, + + primary key (id), + unique(username), + constraint username_length check (char_length(username) >= 3) +); + +alter table profiles enable row level security; + +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 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; + +-- Set up Storage! +insert into storage.buckets (id, name) +values ('avatars', 'avatars'); + +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' ); + +``` + + + + + +### Get the API Keys + + +Now that you've created some database tables, you are ready to insert data using the auto-generated API. +We just need to get the URL and `anon` key from the API settings. + +1. Go to the [Settings](https://app.supabase.com/project/_/settings) page in the Dashboard. +2. Click **API** in the sidebar. +3. Find your API `URL`, `anon`, and `service_role` keys on this page. + + + +## Building the App + +Let's start building the Svelte app from scratch. + +### Initialize a Svelte app + +We can use the [SvelteKit Skeleton Project](https://kit.svelte.dev/docs) to initialize +an app called `supabase-sveltekit` (for this tutorial you do not need TypeScript, ESLint, Prettier, or Playwright): + +```bash +npm create svelte supabase-sveltekit +cd supabase-sveltekit +npm install +``` + +Then let's install the only additional dependency: [supabase-js](https://github.com/supabase/supabase-js) + +```bash +npm install @supabase/supabase-js +``` + +And finally we want to save the environment variables in a `.env`. +All we need are the `SUPABASE_URL` and the `SUPABASE_KEY` key that you copied [earlier](#get-the-api-keys). + +```bash title=".env" +VITE_SUPABASE_URL="YOUR_SUPABASE_URL" +VITE_SUPABASE_ANON_KEY="YOUR_SUPABASE_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="lib/supabaseClient.js" +import { createClient } from '@supabase/supabase-js' + +const supabaseUrl = import.meta.env.VITE_SUPABASE_URL +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 `public/global.css` to make the app look nice. +You can find the full contents of this file [here](https://raw.githubusercontent.com/supabase/supabase/master/examples/user-management/react-user-management/src/index.css). + +### Set up a Login component + +Let's set up a Svelte 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="lib/Auth.svelte" + + +
+
+

Supabase + Svelte

+

Sign in via magic link with your email below

+
+ +
+
+ +
+
+
+``` + +### User store +To access the user information in other places, we use a writable store. Create a new file called `sessionStore.js` +```javascript title="lib/sessionStore.js" +import { writable } from 'svelte/store' + +export const user = writable(false) +``` + + +### 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.svelte`. + +```html title="lib/Profile.svelte" + + +
+
+ + +
+
+ + +
+
+ + +
+ +
+ +
+ +
+ +
+
+``` + + + +### Launch! + +Now that we have all the components in place, let's update `src/routes/index.svelte`: + +```html title="src/routes/index.svelte" + + +
+ {#if $user} + + {:else} + + {/if} +
+``` + +Once that's done, run this in a terminal window: + +```bash +npm run dev +``` + +And then open the browser to [localhost:3000](http://localhost:3000) and you should see the completed app. + +![Supabase Svelte](/img/supabase-svelte-demo.png) + +## Bonus: Profile photos + +Every Supabase project is configured with [Storage](/docs/guides/storage) for managing large files like photos and videos. + +### Create an upload widget + +Let's create an avatar for the user so that they can upload a profile photo. We can start by creating a new component: + +```html title="lib/Avatar.svelte" + + +
+ {#if path} + Avatar + {:else} +
+ {/if} + +
+ + +
+
+``` + + +### Add the new widget + +And then we can add the widget to the Account page: + + +```html title="$lib/Profile.svelte" + + +
+ + + + + + +``` + +## Next steps + +At this stage you have a fully functional application! + +- Got a question? [Ask here](https://github.com/supabase/supabase/discussions). +- Sign in: [app.supabase.com](https://app.supabase.com) diff --git a/apps/reference/docs/guides/with-vue-3.mdx b/apps/reference/docs/guides/with-vue-3.mdx new file mode 100644 index 00000000000..c954e23927f --- /dev/null +++ b/apps/reference/docs/guides/with-vue-3.mdx @@ -0,0 +1,590 @@ +--- +id: with-vue-3 +title: "Quickstart: Vue 3" +description: Learn how to use Supabase in your Vue 3 App. +sidebar_label: "Vue 3" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +## Intro + +This example provides the steps to build a simple user management app (from scratch!) using Supabase and Vue 3. It includes: + +- Supabase [Database](/docs/guides/database): a Postgres database for storing your user data. +- Supabase [Auth](/docs/guides/auth): users can sign in with magic links (no passwords, only email). +- Supabase [Storage](/docs/guides/storage): users can upload a photo. +- [Row Level Security](/docs/guides/auth#row-level-security): data is protected so that individuals can only access their own data. +- Instant [APIs](/docs/guides/api): APIs will be automatically generated when you create your database tables. + +By the end of this guide you'll have an app which allows users to login and update some basic profile details: + +![Supabase User Management example](/img/user-management-demo.png) + +### GitHub +Whenever you get stuck at any point, take a look at [this repo](https://github.com/zernonia/supabase-vue-3). + +## Project set up + +Before we start building we're going to set up our Database and API. This is as simple as starting a new Project in Supabase +and then creating a "schema" inside the database. + +### Create a project + +1. Go to [app.supabase.com](https://app.supabase.com). +1. Click on "New Project". +1. Enter your project details. +1. Wait for the new database to launch. + + +### Set up the database schema + +Now we are going to set up the database schema. We can use the "User Management Starter" quickstart in the SQL Editor, +or you can just copy/paste the SQL from below and run it yourself. + + + + +1. Go to the [SQL Editor](https://app.supabase.com/project/_/sql) page in the Dashboard. +2. Click **User Management Starter**. +3. Click **Run**. + + + + + + +```sql +-- Create a table for public "profiles" +create table profiles ( + id uuid references auth.users not null, + updated_at timestamp with time zone, + username text unique, + avatar_url text, + website text, + + primary key (id), + unique(username), + constraint username_length check (char_length(username) >= 3) +); + +alter table profiles enable row level security; + +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 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; + +-- Set up Storage! +insert into storage.buckets (id, name) +values ('avatars', 'avatars'); + +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' ); + +``` + + + + + +### Get the API Keys + + +Now that you've created some database tables, you are ready to insert data using the auto-generated API. +We just need to get the URL and `anon` key from the API settings. + +1. Go to the [Settings](https://app.supabase.com/project/_/settings) page in the Dashboard. +2. Click **API** in the sidebar. +3. Find your API `URL`, `anon`, and `service_role` keys on this page. + + + +## Building the App + +Let's start building the Vue 3 app from scratch. + +### Initialize a Vue 3 app + +We can quickly use [Vite with Vue 3 Template](https://vitejs.dev/guide/#scaffolding-your-first-vite-project) to initialize +an app called `supabase-vue-3`: + +```bash +# npm 6.x +npm init @vitejs/app supabase-vue-3 --template vue + +# npm 7+, extra double-dash is needed: +npm init @vitejs/app supabase-vue-3 -- --template vue + +cd supabase-vue-3 +``` + +Then let's install the only additional dependency: [supabase-js](https://github.com/supabase/supabase-js) + +```bash +npm install @supabase/supabase-js +``` + +And finally we want to save the environment variables in a `.env`. +All we need are the API URL and the `anon` key that you copied [earlier](#get-the-api-keys). + +```bash title=".env" +VITE_SUPABASE_URL=YOUR_SUPABASE_URL +VITE_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="src/supabase.js" +import { createClient } from '@supabase/supabase-js' + +const supabaseUrl = import.meta.env.VITE_SUPABASE_URL +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/supabase/master/examples/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") +``` + + + +### 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" + + + +``` + +### 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`. + +```html title="src/components/Profile.vue" + + + + +``` + + + +### Launch! + +Now that we have all the components in place, let's update `App.vue`: + +```html title="src/App.vue" + + + + +``` + +Once that's done, run this in a terminal window: + +```bash +npm run dev +``` + +And then open the browser to [localhost:3000](http://localhost:3000) and you should see the completed app. + +![Supabase Vue 3](/img/supabase-vue-3-demo.png) + +## Bonus: Profile photos + +Every Supabase project is configured with [Storage](/docs/guides/storage) for managing large files like photos and videos. + +### Create an upload widget + +Let's create an avatar for the user so that they can upload a profile photo. We can start by creating a new component: + +```html title="src/components/Avatar.vue" + + + +``` + + +### Add the new widget + +And then we can add the widget to the Account page: + + +```html title="src/Profile.vue" + + + +``` + +## Next steps + +At this stage you have a fully functional application! + +- Got a question? [Ask here](https://github.com/supabase/supabase/discussions). +- Sign in: [app.supabase.com](https://app.supabase.com) diff --git a/apps/reference/docs/handbook/contributing.mdx b/apps/reference/docs/handbook/contributing.mdx new file mode 100644 index 00000000000..e6ad5dfa399 --- /dev/null +++ b/apps/reference/docs/handbook/contributing.mdx @@ -0,0 +1,32 @@ +--- +id: contributing +title: Contributing +description: Want to help? +--- + +import Sponsors from '@site/src/components/Sponsors' + +## How to contribute + +Supabase has many [open source repos](https://github.com/orgs/supabase/repositories). Some of the more popular ones are: + - [Supabase](https://github.com/supabase/supabase) - Our Dashboard, Websites, and example apps + - [Supabase-js](https://github.com/supabase/supabase-js) - A clientside library written in Typescript + - [Gotrue](https://github.com/supabase/gotrue) - Our auth server, written in Go + - [Realtime](https://github.com/supabase/realtime) - A server for streaming changes from Postgres, written in Elixir + - [browse all](https://github.com/orgs/supabase/repositories) + +Want to contribute? Why not jump into our GitHub repo and: + +- [Sponsor Supabase](https://github.com/sponsors/supabase). +- [Answer Discussions](https://github.com/supabase/supabase/discussions). +- Submit an issue to one of our [repos](https://github.com/orgs/supabase/repositories) +- Report a performance issue or a part of the documentation that you find confusing. +- Create a pull request in one of our [repos](https://github.com/orgs/supabase/repositories) +- [Translate our Readme](https://github.com/supabase/supabase/issues/1341). +- Try our products and give feedback. +- Spread the word if you like what we are doing. + + +## Sponsors + + \ No newline at end of file diff --git a/apps/reference/docs/handbook/introduction.mdx b/apps/reference/docs/handbook/introduction.mdx new file mode 100644 index 00000000000..69d9bb2bcae --- /dev/null +++ b/apps/reference/docs/handbook/introduction.mdx @@ -0,0 +1,15 @@ +--- +id: introduction +title: Supabase Handbook +description: 'The Supabase public handbook and manifesto' +--- + +Supabase is thinking in public. Everything is online, no matter how raw the current state of things. + +This is our public handbook and manifesto. We are completely opensource and this means that you, our users, are also our team members. + +--- + +## Opensource + +Wherever we can we will support existing opensource tools and libraries. diff --git a/apps/reference/docs/handbook/supasquad.mdx b/apps/reference/docs/handbook/supasquad.mdx new file mode 100644 index 00000000000..90d66f74820 --- /dev/null +++ b/apps/reference/docs/handbook/supasquad.mdx @@ -0,0 +1,83 @@ +--- +id: supasquad +title: SupaSquad +description: Supabase Advocate program +--- + +The SupaSquad is an official Supabase advocate program where community members help build and manage the Supabase community. + +- Official recognition in the Supabase community. +- Direct connection to the Supabase team. +- Help steer the Supabase community. + +![Supabase SupaSquad](/img/supabase-squad.png) + +## Requirements + +As a member of the Squad, you choose the approach where you'll provide the most value. +You can help in one of five ways: + +### Maintainer + +Help maintain Supabase repositories. This includes building client libraries, managing issues, and fixing bugs. + +### Expert + +Answer user questions on GitHub [Discussions](https://github.com/supabase/supabase/discussions), [Discord](https://discord.supabase.com), and various other social platforms. + +### Advocate + +Spread the word on social channels and help to answer Supabase-related questions in the broader community and social channels. + +### Builder + +Build Supabase examples, blog about them, and them add to the [SupaSquad GitHub Org](https://github.com/supasquad). + +### Author + +Write guest blog posts, create documentation, and help Supabase global expansion through translation. + +### Moderator + +Help us maintain the community guidelines in our GitHub and Community-led communities such as [Discord](https://discord.supabase.com), [Reddit](https://reddit.com/r/Supabase/), +[StackOverflow](https://stackoverflow.com/questions/tagged/supabase), etc. + +## Benefits for SupaSquad members + +- Access to a Supabase Discord channel providing direct communication with the team, Discord badges, and elevated privileges. +- Special AMA sessions with members of the Supabase team. +- Monthly DevRel committee call with industry-leading Developer Advocates (many of whom are [angel investors](https://supabase.com/blog/2021/03/25/angels-of-supabase)), where you can learn from the best. +- We'll help you build your audience by promoting content via the Supabase social channels. +- Featured profile on Supabase website. +- Early access to new features (and the opportunity to provide feedback to the team!). +- Free credits that you can use for Squad efforts. +- Direct access to members of the Supabase team for questions, suggestions, etc. +- Help shape the future of the program. +- Invited to the [SupaSquad GitHub Org](https://github.com/supasquad) to collaborate with the other squad members. +- Exclusive Supabase Team swag drops are usually exclusively reserved for the Supabase core team. + +## How to join + + +1. Apply to join the program using [this form](https://airtable.com/shr0FtLqLfhpuEya8). +2. We will start taking interviewing members from `1 September 2021`. +3. Entry is capped to 20 founding members so we can grow the community at a healthy pace and provide a great experience to all new users. +4. Membership is valid for one year, and can be renewed every year. + + +## FAQs + +
+ Why are you only admitting 20 new members? + The entire Supabase team is only 20 people, so as you can imagine adding another 20 people sounds like a lot to us! We wish we could admit everyone who wanted to join. + But we also want to make sure everyone who joins the Squad has an awesome experience. In the future we will probably expand the intake to include a monthly quota. +
+
+ What is expected? + Mostly just enthusiasm. If you are interested in Open Source and want to get involved, the SupaSquad program is a great channel. You'll be given opportunities to contribute + to the community in whatever ways match your skillset. +
+
+ What if I become too busy to contribute? + No worries! The program isn't a job. It's just an opportunity to build your skillset and audience within the Supabase ecosystem. +
\ No newline at end of file diff --git a/apps/reference/docs/learn/auth-deep-dive/google-oauth.md b/apps/reference/docs/learn/auth-deep-dive/google-oauth.md new file mode 100644 index 00000000000..cb6915f3e84 --- /dev/null +++ b/apps/reference/docs/learn/auth-deep-dive/google-oauth.md @@ -0,0 +1,90 @@ +--- +id: auth-google-oauth +title: 'Part Five: Google Oauth' +description: 'Supabase Deep Dive Part 5: Google OAuth Provider' +--- + +### About + +How to add Google OAuth Logins to your Supabase Application. + +### Watch + + + +### Logging in with external OAuth providers + +Connecting social logins such as Google, GitHub, or Facebook couldn't be easier. In this guide we'll walk you through the process of connecting Google, but the process is basically the same for all of the providers which includes: azure, bitbucket, github, gitlab, facebook, and google. + +First you'll need to create a google project inside their [cloud console](https://console.cloud.google.com/home/dashboard), in other providers they may refer to this as an "app" and is usually available on the company's developer portal. + +![Create a new Google Project inside cloud console](/img/auth-5-1.png) + +Once you have a project, type "OAuth" into the search bar and open up "OAuth Consent Screen" + +![Open the OAuth consent screen](/img/auth-5-2.png) + +Select 'External' and proceed to fill out the rest of the form fields + +![Select External on the OAuth form](/img/auth-5-3.png) + +Next open up Credentials page on the left + +![Open up Credentials page](/img/auth-5-4.png) + +And click to create a new set of credentials, select OAuth client ID as the option + +![Create new oauth client id credentials](/img/auth-5-5.png) + +Now choose Web Application (assuming you're creating a web app) and in the Authorized redirect URI section you need to add: `https://.supabase.co/auth/v1/callback`. You can find your Supabase URL in Settings > API inside the Supabase dashboard. + +![Add your redirect URI](/img/auth-5-6.png) + +Now you can grab the client ID and secret from the popup, and insert them into the google section inside the Supabase dashboard in Auth > Settings: + +![take client id and secret](/img/auth-5-7.png) + +![insert client id and secret into supabase dashboard in auth > auth](/img/auth-5-8.png) + +Hit save. Now you should be able to navigate in the browser to: + +``` +https://.supabase.co/auth/v1/authorize?provider=google +``` + +And log in to your service using any google or gmail account. + +You can additionally add a query parameter `redirect_to=` to the end of the URL for example: + +``` +https://.supabase.co/auth/v1/authorize?provider=google&redirect_to=http://localhost:3000/welcome +``` + +But make sure any URL you enter here is on the same host as the site url that you have entered on the Auth > Settings page on the Supabase dashboard. (There is additional functionality coming soon, where you'll be able to add additional URLs to the allow list). + +If you want to redirect the user to a specific page in your website or app after a successful authentication. + +You also have the option of requesting additional scopes from the oauth provider. Let's say for example you want the ability to send emails on behalf of the user's gmail account. You can do this by adding the query parameter `scopes`, like: + +``` +https://.supabase.co/auth/v1/authorize?provider=google&https://www.googleapis.com/auth/gmail.send +``` + +Note however that your app will usually have to be verified by Google before you can request advanced scopes such as this. + +The only thing left to implement is the UI, but if you prefer to use something pre-built, we have a handy [Auth Widget](https://github.com/supabase/ui/#using-supabase-ui-auth), where you can enable/disable whichever auth providers you want to support. + +For any support please get in touch at beta at [supabase.com](https://supabase.com) or for feature requests open an issue in the [backend](https://github.com/supabase/gotrue) or [frontend](https://github.com/supabase/gotrue-js) repos. + +### Resources + +- [JWT debugger](https://jwt.io) + +### Next steps + +- Watch [Part One: JWTs](/docs/learn/auth-deep-dive/auth-deep-dive-jwts) +- Watch [Part Two: Row Level Security](/docs/learn/auth-deep-dive/auth-row-level-security) +- Watch [Part Three: Policies](/docs/learn/auth-deep-dive/auth-policies) +- Watch [Part Four: GoTrue](/docs/learn/auth-deep-dive/auth-gotrue) + +- Sign up for Supabase: [app.supabase.com](https://app.supabase.com) diff --git a/apps/reference/docs/learn/auth-deep-dive/gotrue.md b/apps/reference/docs/learn/auth-deep-dive/gotrue.md new file mode 100644 index 00000000000..da56e1e3559 --- /dev/null +++ b/apps/reference/docs/learn/auth-deep-dive/gotrue.md @@ -0,0 +1,72 @@ +--- +id: auth-gotrue +title: 'Part Four: GoTrue' +description: 'Supabase Deep Dive Part 4: Gotrue Overview' +--- + +### About + +How to restrict table access to authenticated users, row level policies, and email domain based access. + +### Watch + + + +### Gotrue Server + +Gotrue is an auth API server written in Go by the Netlify team, find the Supabase fork here: https://github.com/supabase/gotrue. The list of available API endpoints is available [here](https://github.com/supabase/gotrue#endpoints). + +When you deploy a new Supabase project, we deploy a new instance of this server alongside your database, and also inject your database with the required `auth` schema. + +It makes it super easy to, for example, send magic link emails which your users can use to login: + +```bash +# replace with your own project reference +# and SUPABASE_KEY with your anon api key +curl -X POST 'https://.supabase.co/auth/v1/magiclink' \ +-H "apikey: SUPABASE_KEY" \ +-H "Content-Type: application/json" \ +-d '{ + "email": "someone@email.com" +}' +``` + +Gotrue is responsible for issuing access tokens for your users, sends confirmation, magic-link, and password recovery emails (by default we send these from a Supabase SMTP server, but you can easily plug in your own inside the dashboard at Auth > Settings) and also transacting with third party OAuth providers to get basic user data. + +The community even recently built in the functionality to request custom OAuth scopes, if your users need to interact more closely with the provider. See the scopes parameter here: [https://github.com/supabase/gotrue#get-authorize](https://github.com/supabase/gotrue#get-authorize). + +So let's say you want to send emails on behalf of a user via gmail, you might request the gmail.send scope by directing them to: + +``` +https://sjvwsaokcugktsdaxxze.supabase.co/auth/v1/authorize?provider=google&https://www.googleapis.com/auth/gmail.send +``` + +You'll have to make sure your google app is verified of course in order to request these advanced scopes. + +[Gotrue-js](https://github.com/supabase/gotrue-js) (and also [gotrue-csharp](https://github.com/supabase/gotrue-csharp), [gotrue-py](https://github.com/j0/gotrue-py), [gotrue-kt](https://github.com/supabase/gotrue-kt), and [gotrue-dart](https://github.com/supabase/gotrue-dart)) are all wrappers around the gotrue API endpoints, and make for easier session management inside your client. + +But all the functionality of gotrue-js is also available in supabase-js, which uses gotrue-js internally when you do things like: + +```jsx +const { user, session, error } = await supabase.auth.signIn({ + email: 'example@email.com', + password: 'example-password', +}) +``` + +If you want to request a feature, or contribute to the project directly, just head to https://github.com/supabase/gotrue and open some issues/PRs, we're always open to help. + +In the next guide we'll be looking at how to setup external OAuth providers: Watch [Part Five: Google Oauth](/docs/learn/auth-deep-dive/auth-google-oauth) + +### Resources + +- JWT debugger: https://jwt.io​ + +### Next steps + +- Watch [Part One: JWTs](/docs/learn/auth-deep-dive/auth-deep-dive-jwts) +- Watch [Part Two: Row Level Security](/docs/learn/auth-deep-dive/auth-row-level-security) +- Watch [Part Three: Policies](/docs/learn/auth-deep-dive/auth-policies) + +- Watch [Part Five: Google Oauth](/docs/learn/auth-deep-dive/auth-google-oauth) +- Sign up for Supabase: [app.supabase.com](https://app.supabase.com) diff --git a/apps/reference/docs/learn/auth-deep-dive/jwts.md b/apps/reference/docs/learn/auth-deep-dive/jwts.md new file mode 100644 index 00000000000..67c79c572a0 --- /dev/null +++ b/apps/reference/docs/learn/auth-deep-dive/jwts.md @@ -0,0 +1,184 @@ +--- +id: auth-deep-dive-jwts +title: 'Part One: JWTs' +description: Supabase Auth Deep Dive Part 1 - JWTs +--- + +### About + +An introduction to JWTs and how they are used in Supabase Auth + +### Watch + + + +### What are JSON Web Tokens (JWTs)? + +JWTs are JSON objects that are encoded and signed and sent around as a string. They are distributed to users of a service or website, who can later show the JWT to the website or service as proof that they have the right to access certain content. + +What exactly do we mean when we say "encoded" and "signed"? + +Well, the JSON object starts out looking something like this: + +```js +{ + "sub": "0001", + "name": "Sam Vimes", + "iat": 1516239022, + "exp": 1518239022 +} +``` + +`sub` is the "subject", which is usually the UUID of the user. `name` is self-explanatory, and `iat` is the Unix timestamp at which the token was created. Many JWTs will also have an `exp`, which is the date at which the token is set to expire and can no longer be used. These are some of the standard fields you may find in a JWT, but you can pretty much store whatever you want in there, for example: + +```js +{ + "sub": "0002", + "name": "Věra Hrabánková", + "iat": 1516239022, + "exp": 1518239022, + "theme": { + "primary" : "#D80C14", + "secondary" : "#FFFFFF" + } +} +``` + +Just note that the more data you store in your token, the longer the encoded string will be. + +When we want to send the JWT to the user, we first encode the data using an algorithm such as `HS256`. There are many libraries (and several different algorithms) that can be used to do this encoding/decoding, such as [jsonwebtoken](https://www.npmjs.com/package/jsonwebtoken). I made a repl [here](https://replit.com/@awalias/jsonwebtokens#index.js) so you can try it for yourself. The signing is as simple as: + +```js +// from https://replit.com/@awalias/jsonwebtokens#index.js +let token = jwt.sign({ name: 'Sam Vimes' }, 'some-secret') +``` + +And the resulting string will look like this: + +```js +eyJhbGciOiJIUzI1NiJ9 + .eyJzdWIiOiIwMDAxIiwibmFtZSI6IlNhbSBWaW1lcyIsImlhdCI6MTUxNjIzOTAyMiwiZXhwIjoxNTE4MjM5MDIyfQ + .zMcHjKlkGhuVsiPIkyAkB2rjXzyzJsMMgpvEGvGtjvA +``` + +You will notice that the string is actually made up of three components, which we'll address one by one: + +The first segment `eyJhbGciOiJIUzI1NiJ9` is known as the "header", and when decoded just tells us which algorithm was used to do the encoding: + +```js +{ + "alg": "HS256" +} +``` + +The second segment `eyJzdWIiOiIwMDAxIiwibmFtZSI6IlNhbSBWaW1lcyIsImlhdCI6MTUxNjIzOTAyMiwiZXhwIjoxNTE4MjM5MDIyfQ` contains our original payload: + +```js +{ + "sub": "0001", + "name": "Sam Vimes", + "iat": 1516239022, + "exp": 1518239022 +} +``` + +The last segment `zMcHjKlkGhuVsiPIkyAkB2rjXzyzJsMMgpvEGvGtjvA` is the signature itself, which is the part used by the website or service provider to verify that a token sent by some user is legitimate. It is produced in the first instance by running the cryptographic function HS256 on the following input: + +```js +HMACSHA256( + base64UrlEncode(header) + "." + + base64UrlEncode(payload) + +) +``` + +You can test out minting your own tokens on [https://jwt.io](https://jwt.io). + +It is important to note that anyone who possesses the `jwt_secret` here can create new tokens, and also verify existing ones. More advanced JWT algorithms use two secrets: one for the creation of tokens, and a separate one to verify the validity of signed tokens. + +You might wonder why JWTs are so popular all of a sudden. The answer is that with the mass adoption of microservice architecture, we were in a situation where several distinct microservices (APIs, websites, servers, etc.) want to easily validate that a user is who they say they are, or are in other words a "logged-in" user. Traditional session tokens are no use here, since they would require each microservice to either maintain a record of currently valid session tokens or to query a central database each time a user wants to access a resource in order to check the validity of the session token – very inefficient indeed. JWT-based auth in this sense is decentralized, since anyone with the `jwt_secret` can verify a token without needing access to a centralized database. + +Note: One downside of JWTs is that they are not easily voidable, like session tokens. If a JWT is leaked to a malicious actor, they will be able to redeem it anywhere until the expiry date is reached – unless of course the system owner updates the `jwt_secret` (which will of course invalidate _everyone's_ existing tokens). + +### JWTs in Supabase + +In Supabase we issue JWTs for three different purposes: + +1. `anon key`: This key is used to bypass the Supabase API gateway and can be used in your client-side code. +2. `service role key`: This key has super admin rights and can bypass your Row Level Security. Do not put it in your client-side code. Keep it private. +3. `user specific jwts`: These are tokens we issue to users who log into your project/service/website. It's the modern equivalent of a session token, and can be used by a user to access content or permissions specific to them. + +The first token here, the `anon key` token, is for developers to send along with their API requests whenever they want to interact with their Supabase database. + +Let's say you want to read the names of all the rows in a table `colors`. We would make a request like: + +```bash +curl 'https://xscduanzzfseqszwzhcy.supabase.co/rest/v1/colors?select=name' \ +-H "apikey: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiIsImlhdCI6MTYxNDIwNTE3NCwiZXhwIjoxOTI5NzgxMTc0fQ.-NBR1WnZyQGpRLdXJfgfpszoZ0EeE6KHatJsDPLIX8c" +``` + +If we put this token into https://jwt.io, we see it decodes to: + +```js +{ + "role": "anon", + "iss": "supabase", + "iat": 1614205174, + "exp": 1929781174 +} +``` + +This JWT is signed by a `jwt_secret` specific to the developer's Supabase token (you can find this secret alongside this encoded "anon key" on your Dashboard under Settings > API page) and is required to get past the Supabase API gateway and access the developer's project. + +The idea with this particular key is that it's safe to put into your client, meaning it's okay if your end users see this key – but _only_ if you first enable Row Level Security, which is the topic of [Part Two](/docs/learn/auth-deep-dive/auth-row-level-security) in this series. + +The second key, `service role key`, should only ever be used on one of your own servers or environments, and should never be shared with end users. You might use this token to do things like make batch inserts of data. + +The `user access token` is the JWT issued when you call for example: + +```js +supabase.auth.signIn({ + email: 'lao.gimmie@gov.sg', + password: 'They_Live_1988!', +}) +``` + +This token should be passed in addition to the `apikey` header as an `Authorization Bearer` header like: + +```bash +curl 'https://xscduanzzfseqszwzhcy.supabase.co/rest/v1/colors?select=name' \ +-H "apikey: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiIsImlhdCI6MTYxNDIwNTE3NCwiZXhwIjoxOTI5NzgxMTc0fQ.-NBR1WnZyQGpRLdXJfgfpszoZ0EeE6KHatJsDPLIX8c" \ +-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhdXRoZW50aWNhdGVkIiwiZXhwIjoxNjE1ODI0Mzg4LCJzdWIiOiIwMzM0NzQ0YS1mMmEyLTRhYmEtOGM4YS02ZTc0OGY2MmExNzIiLCJlbWFpbCI6InNvbWVvbmVAZW1haWwuY29tIiwiYXBwX21ldGFkYXRhIjp7InByb3ZpZGVyIjoiZW1haWwifSwidXNlcl9tZXRhZGF0YSI6bnVsbCwicm9sZSI6ImF1dGhlbnRpY2F0ZWQifQ.I-_oSsJamtinGxniPETBf-ezAUwDW2sY9bJIThvdX9s" +``` + +You'll notice that this token is quite a bit longer, since it contains information specific to the user such as: + +```js +{ + "aud": "authenticated", + "exp": 1615824388, + "sub": "0334744a-f2a2-4aba-8c8a-6e748f62a172", + "email": "d.l.solove@gmail.com", + "app_metadata": { + "provider": "email" + }, + "user_metadata": null, + "role": "authenticated" +} +``` + +Now that you understand what JWTs are and where they're used in Supabase, you can explore how to use them in combination with Row Level Security to start restricting access to certain tables, rows, and columns in your Postgres database: [Part Two: Row Level Security](/docs/learn/auth-deep-dive/auth-row-level-security) + +### Resources + +- JWT debugger: https://jwt.io/ + +### Next steps + + + +- [Part Two: Row Level Security](/docs/learn/auth-deep-dive/auth-row-level-security) +- [Part Three: Policies](/docs/learn/auth-deep-dive/auth-policies) +- [Part Four: GoTrue](/docs/learn/auth-deep-dive/auth-gotrue) +- [Part Five: Google Oauth](/docs/learn/auth-deep-dive/auth-google-oauth) +- Sign up for Supabase: [app.supabase.com](https://app.supabase.com) diff --git a/apps/reference/docs/learn/auth-deep-dive/policies.md b/apps/reference/docs/learn/auth-deep-dive/policies.md new file mode 100644 index 00000000000..e965fae6835 --- /dev/null +++ b/apps/reference/docs/learn/auth-deep-dive/policies.md @@ -0,0 +1,169 @@ +--- +id: auth-policies +title: 'Part Three: Policies' +description: 'Supabase Auth Deep Dive Part 3: User Based Access Policies' +--- + +### About + +How to restrict table access to authenticated users, row level policies, and email domain based access. + +### Watch + + + +### User based row level policies + +Now that we know how to restrict access to tables based on JWT roles, we can combine this with user management to give us much more control over what data your users can read to and write from your database. + +We'll start with how user sessions work in Supabase, and later move on to writing user-centric policies. + +Let's say we're signing a user up to our service for the first time. The typical way to do this is by invoking the following method in supabase-js: + +```jsx +// see full api reference here: /docs/reference/javascript/auth-signup +supabase.auth.signUp({ email, password }) +``` + +By default this will send a confirmation email to the user. When the user clicks the link in the email, they will be redirected to your site (you need to provide your site url in Auth > Settings on the dashboard. By default this is http://localhost:3000) and the full URL including query params will look something like this: + +``` +http://localhost:3000/#access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhdXRoZW50aWNhdGVkIiwiZXhwIjoxNjE2NDI5MDY0LCJzdWIiOiI1YTQzNjVlNy03YzdkLTRlYWYtYThlZS05ZWM5NDMyOTE3Y2EiLCJlbWFpbCI6ImFudEBzdXBhYmFzZS5pbyIsImFwcF9tZXRhZGF0YSI6eyJwcm92aWRlciI6ImVtYWlsIn0sInVzZXJfbWV0YWRhdGEiOnt9LCJyb2xlIjoiYXV0aGVudGljYXRlZCJ9.4IFzn4eymqUNYYo2AHLxNRL8m08G93Qcg3_fblGqDjo&expires_in=3600&refresh_token=RuioJv2eLV05lgH5AlJwTw&token_type=bearer&type=signup +``` + +Let's break this up so that it's easier to read: + +```jsx +// the base url - whatever you set in the Auth Settings in app.supabase.com dashboard +http://localhost:3000/ + +// note we use the '#' (fragment) instead of '?' query param +// the access token is a JWT issued to the user +#access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhdXRoZW50aWNhdGVkIiwiZXhwIjoxNjE2NDI5MDY0LCJzdWIiOiI1YTQzNjVlNy03YzdkLTRlYWYtYThlZS05ZWM5NDMyOTE3Y2EiLCJlbWFpbCI6ImFudEBzdXBhYmFzZS5pbyIsImFwcF9tZXRhZGF0YSI6eyJwcm92aWRlciI6ImVtYWlsIn0sInVzZXJfbWV0YWRhdGEiOnt9LCJyb2xlIjoiYXV0aGVudGljYXRlZCJ9.4IFzn4eymqUNYYo2AHLxNRL8m08G93Qcg3_fblGqDjo + +// valid for 60 minutes by default +&expires_in=3600 + +// use to get a new access_token before 60 minutes expires +&refresh_token=RuioJv2eLV05lgH5AlJwTw + +// can use as the Authorization: Bearer header in requests to your API +&token_type=bearer + +// why was this token issued? was it a signup, login, password reset, or magic link? +&type=signup +``` + +If we put the access_token into [https://jwt.io](https://jwt.io) we'll see it decodes to: + +```jsx +{ + "aud": "authenticated", + "exp": 1616429064, + "sub": "5a4365e7-7c7d-4eaf-a8ee-9ec9432917ca", + "email": "ant@supabase.io", + "app_metadata": { + "provider": "email" + }, + "user_metadata": {}, + "role": "authenticated" +} +``` + +The `authenticated` role is special in Supabase, it tells the API that this is an authenticated user and will know to compare the JWT against any policies you've added to the requested resource (table or row). + +The `sub` claim is usually what we use to match the JWT to rows in your database, since by default it is the unique identifier of the user in the `auth.users` table (as a side note - it's generally not recommended to alter the `auth` schema in any way in your Supabase database since the Auth API relies on it to function correctly). + +For the curious, try heading to the SQL editor and querying: + +```sql +select * from auth.users; +``` + +If supabase-js is loaded on your site (in this case http://localhost:3000) then it will automatically pluck the access_token out of the URL and initiate a session. You can check the [session()](/docs/reference/javascript/auth-session) method to see if there is a valid session: + +```jsx +console.log(supabase.auth.session()) +``` + +Now that we can use methods like `supabase.auth.signIn({ email, password})` to issue JWTs to users we want to start fetching resources specific to that user. So let's make some. Go to the SQL editor and run: + +```sql +create table my_scores ( + name text, + score int, + user_id uuid not null +); + +ALTER TABLE my_scores ENABLE ROW LEVEL SECURITY; + +insert into my_scores(name, score, user_id) +values + ('Paul', 100, '5a4365e7-7c7d-4eaf-a8ee-9ec9432917ca'), + ('Paul', 200, '5a4365e7-7c7d-4eaf-a8ee-9ec9432917ca'), + ('Leto', 50, '9ec94326-2e2d-2ea2-22e3-3a535a4365e7'); + +-- use UUIDs from the auth.users table if you want to try it +-- for yourself +``` + +Now we'll write our policy, again in SQL, but note it's also possible to add via the dashboard in Auth > Policies: + +```sql +CREATE POLICY user_update_own_scores ON my_scores + FOR ALL + USING (auth.uid() = user_id); +``` + +Now, assuming you have an active session in your javascript/supabase-js environment you can do: + +```jsx +supabase.from('my_scores').select('*').then(console.log) +``` + +and you should only receive scores belonging to the current logged in user. Alternatively you can use Bash like: + +```bash +curl 'https://sjvwsaokcugktsdaxxze.supabase.co/rest/v1/my_scores?select=*' \ +-H "apikey: " \ +-H "Authorization: Bearer " +``` + +Note that the `anon key` (or `service role key`) is always needed to get past the API gateway. This can be passed in the `apikey` header or in a query param named `apikey`. It is passed automatically in supabase-js as long as you used it to instantiate the client. + +There are some more notes here on how to structure your schema to best integrate with the `auth.users` table. + +Once you get the hang of policies you can start to get a little bit fancy. Let's say I work at Blizzard and I only want Blizzard staff members to be able to update people's high scores, I can write something like: + +```sql +create or replace function auth.email() returns text as $$ + select nullif(current_setting('request.jwt.claims', true)::json->>'email', '')::text; +$$ language sql; + +create policy "Only Blizzard staff can update leaderboard" + on my_scores + for update using ( + right(auth.email(), 13) = '@blizzard.com' + ); +``` + +Supabase comes with three built-in helper functions: `auth.email()`, `auth.uid()` and `auth.role()`. + +See the full PostgreSQL policy docs here: [https://www.postgresql.org/docs/12/sql-createpolicy.html](https://www.postgresql.org/docs/12/sql-createpolicy.html) + +You can get as creative as you like with these policies. + +### Resources + +- JWT debugger: https://jwt.io​ +- PostgeSQL Policies: https://www.postgresql.org/docs/12/sql-createpolicy.html +- PostgREST Row Level Security: https://postgrest.org/en/v7.0.0/auth.html + +### Next steps + +- Watch [Part One: JWTs](/docs/learn/auth-deep-dive/auth-deep-dive-jwts) +- Watch [Part Two: Row Level Security](/docs/learn/auth-deep-dive/auth-row-level-security) + +- Watch [Part Four: GoTrue](/docs/learn/auth-deep-dive/auth-gotrue) +- Watch [Part Five: Google Oauth](/docs/learn/auth-deep-dive/auth-google-oauth) +- Sign up for Supabase: [app.supabase.com](https://app.supabase.com) diff --git a/apps/reference/docs/learn/auth-deep-dive/row-level-security.md b/apps/reference/docs/learn/auth-deep-dive/row-level-security.md new file mode 100644 index 00000000000..01e9ffa4f57 --- /dev/null +++ b/apps/reference/docs/learn/auth-deep-dive/row-level-security.md @@ -0,0 +1,119 @@ +--- +id: auth-row-level-security +title: 'Part Two: Row Level Security' +description: Supabase Auth Deep Dive Part Two - Row Level Security +--- + +### About + +Learn how to restrict access to your database tables by enabling Row Level Security and writing Postgres Policies in the Supabase Dashboard. + +### Watch + + + +### Securing Your Tables + +In Supabase, you can access your data directly from the client (often the web browser), you do this by passing your Supabase URL and Anon key to supabase-js like so: + +```js +const supabase = createClient( + 'https://qwertyuiop.supabase.co', + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c' +) +``` + +This raises an interesting question however: "if my anon key is in the client, then can't someone read my javascript and steal my key?", the answer is yes. And this is where Postgres policies come in. + +Using Postgres's "Row-Level-Security" policies, we can set rules on what data the anon key is allowed or not allowed to access by default. + +We can say for example that the anon key should only be able to read from a particular table, but not write, update, nor delete. + +And these rules can be as complex as we want. We could say that the anon key can only delete rows which were inserted on a Thursday afternoon between 4 and 6pm, and where the id column is an even number. Pretty strange, but it shows the power of policies. + +Let's say we create a leaderboard table. We want people on our website to be able to read the leaderboard, but not write, update, or delete from it. We start by defining our table in SQL and adding some dummy data: + +```sql +create table leaderboard ( + name text, + score int +); + +insert into leaderboard(name, score) +values ('Paul', 100), ('Leto', 50), ('Chani', 200); +``` + +Now let's set up a client to read the data, I've created a repl here to show a living example: [https://replit.com/@awalias/supabase-leaderboard-demo#index.js](https://replit.com/@awalias/supabase-leaderboard-demo#index.js). If you copy the snippet you can plug in your own Supabase URL and anon key. + +You can see that it's possible to freely read from and write to the table by using: + +```js +// Writing +let { data, error } = await supabase + .from('leaderboard') + .insert({ name: 'Bob', score: 99999 }) + +// Reading +let { data, error } = await supabase + .from('leaderboard') + .select('name, score') + .order('score', { ascending: false }) +``` + +Now let's restrict access. We'll start by fully restricting the table. We can do this in the SQL editor by making a query: + +```sql +ALTER TABLE leaderboard ENABLE ROW LEVEL SECURITY; +``` + +or via the Supabase Dashboard, by navigating to Auth > Policies, and clicking the red padlock on the leaderboard table, so that it turns white. + +![Enable row level security in Supabase](/img/auth-deep-dive-2.png) + +You'll notice that both reading and writing now fail with an error like: + +```jsx +{ + hint: null, + details: null, + code: '42501', + message: 'new row violates row-level security policy for table "leaderboard"' +} +``` + +Now we need to add a policy to enable reading of the table, for everyone who sends the anon key (JWT) in the `Authorization: Bearer` header. + +In SQL this can be done with: + +```sql +CREATE POLICY anon_read_leaderboard ON leaderboard + FOR SELECT + TO 'anon' + USING (true); +``` + +`anon_read_leaderboard` here is just a name that you choose for your policy. `leaderboard` is the table name. `FOR SELECT` says that we only want this policy to apply for reads (or rather "selects" in SQL). `TO` means that this policy will only apply to the `anon` Postgres role. And finally the rule itself is `true'`, which means it will _allow_ any `selects` to the `anon` user. + +If you'd prefer to use the dashboard to add your policy you can do so by clicking "Add Policy" in the Policies tab and making a policy like this: + +![Add a read only policy in Supabase](/img/auth-deep-dive-2-2.png) + +You should now be able to read from your leaderboard, but will still not be able to write, update, or delete from it, which is exactly what we wanted! + +A quick reminder that you can always use your `service_role` API key to bypass these row level security policies. But be extra careful that you don't leak this key by including it in the client. This can be useful if you're building internal admin tools, or if you need to bulk insert or delete data via the API. + +In the next guide we will look at using Policies in combination with User Accounts, so that you can restrict access to data on a User by User basis: Watch [Part Three: Policies](/docs/learn/auth-deep-dive/auth-policies) + +### Resources + +- JWT debugger: https://jwt.io/ +- RESTED: https://github.com/RESTEDClient/RESTED + +### Next steps + +- Watch [Part One: JWTs](/docs/learn/auth-deep-dive/auth-deep-dive-jwts) + +- Watch [Part Three: Policies](/docs/learn/auth-deep-dive/auth-policies) +- Watch [Part Four: GoTrue](/docs/learn/auth-deep-dive/auth-gotrue) +- Watch [Part Five: Google Oauth](/docs/learn/auth-deep-dive/auth-google-oauth) +- Sign up for Supabase: [app.supabase.com](https://app.supabase.com) diff --git a/apps/reference/docs/postgres/api/about.md b/apps/reference/docs/postgres/api/about.md new file mode 100644 index 00000000000..0182279f986 --- /dev/null +++ b/apps/reference/docs/postgres/api/about.md @@ -0,0 +1,12 @@ +--- +id: about +title: Postgres API +description: A RESTful API for managing your Postgres. Fetch tables, add roles, and run queries +--- + +A RESTful API for managing your Postgres. Fetch tables, add roles, and run queries. + +## Usage + +- GitHub: https://github.com/supabase/postgres-meta +- Full documentation: https://supabase.github.io/postgres-meta/ diff --git a/apps/reference/docs/postgres/server/about.md b/apps/reference/docs/postgres/server/about.md new file mode 100644 index 00000000000..1f5db272b2d --- /dev/null +++ b/apps/reference/docs/postgres/server/about.md @@ -0,0 +1,16 @@ +--- +id: about +title: Postgres +description: 'The easiest way to get started with Postgres.' +--- + +We've talked to a lot of developers, and they often tell us that they know Postgres is the best database for their needs, but they still choose something that's easier to get started. + +We want to solve that problem. So we packaged Postgres with some useful plugins and built some one-click installers. Our goal is not to modify Postgres, but to provide some of the most common extensions with a simple installation process. + +## Resources + +- Find the repository here: [supabase/postgres](https://github.com/supabase/postgres/) +- Use with [Docker](https://github.com/supabase/postgres/wiki/Docker) +- Install on [Digital Ocean](https://github.com/supabase/postgres/wiki/Digital-Ocean) +- Install on [AWS](https://github.com/supabase/postgres/wiki/AWS-EC2) diff --git a/apps/reference/docs/postgres/server/aws.md b/apps/reference/docs/postgres/server/aws.md new file mode 100644 index 00000000000..e39b2af09a3 --- /dev/null +++ b/apps/reference/docs/postgres/server/aws.md @@ -0,0 +1,9 @@ +--- +id: aws +title: AWS +description: 'Host your own Postgres server' +--- + +# Quick install + +We are still in the process of registering for the AWS Marketplace. Subscribe to the releases on this repo to get notified when we are accepted. diff --git a/apps/reference/docs/postgres/server/digitalocean.md b/apps/reference/docs/postgres/server/digitalocean.md new file mode 100644 index 00000000000..8cbb9a34f73 --- /dev/null +++ b/apps/reference/docs/postgres/server/digitalocean.md @@ -0,0 +1,41 @@ +--- +id: digitalocean +title: DigitalOcean +description: 'Host your own Realtime server' +--- + +## Create your droplet + +Head over to our Digital Ocean marketplace [listing](https://marketplace.digitalocean.com/apps/supabase-postgres) and create your droplet. You are free to create one even at the most basic configuration. No restrictions for you here. + +## Set up the password + +Set up the password for the DB Superuser **postgres**. + +SSH into your instance using the user **root** and type in the following once you are in: + +``` +$ sudo -u postgres psql +``` + +This logs you into the **psql** terminal as the DB Superuser **postgres**. + +![psql Screenshot](https://dev-to-uploads.s3.amazonaws.com/i/j0kdzn07wu8uawmr6nmz.png) + +Set your password with this command: + +``` +$ \password +``` + +Enter your desired password afterward and re-enter it when prompted. Once done, you can now exit your SSH connection. + +## Try out your new database + +With any SQL client of your choice (Such as [DBeaver](https://dbeaver.io/)), connect to your database with the following credentials: + +- Host: **_insert droplet ip address_** +- Port: **5432** +- User: **postgres** +- Password: **_insert your chosen password_** +- Database: **postgres** diff --git a/apps/reference/docs/postgres/server/docker.md b/apps/reference/docs/postgres/server/docker.md new file mode 100644 index 00000000000..2fa4922e4a8 --- /dev/null +++ b/apps/reference/docs/postgres/server/docker.md @@ -0,0 +1,19 @@ +--- +id: docker +title: Docker +description: 'Host your own Postgres server' +--- + +## Docker + +The image is now available in [Docker Hub](https://hub.docker.com/r/supabase/postgres) under the name `supabase/postgres`. + +## Docker compose + +You can use the [docker-compose file](https://github.com/supabase/postgres/blob/develop/docker/docker-compose.yml) available in this repository as your starting point. You can then run: + +``` +$ docker-compose up +``` + +As the image is based on the [postgreSQL 12 image](https://hub.docker.com/_/postgres), environment variables from the postgreSQL 12 image are applicable to this image. diff --git a/apps/reference/docs/reference copy.mdx b/apps/reference/docs/reference copy.mdx new file mode 100644 index 00000000000..9b47f8dd6d7 --- /dev/null +++ b/apps/reference/docs/reference copy.mdx @@ -0,0 +1,494 @@ +--- +id: reference +title: Reference Documentation +sidebar_label: Overview +description: 'Reference Docs' +hide_table_of_contents: true +--- + +import Link from '@docusaurus/Link' + +The Supabase Reference Docs provide technical descriptions of the products and how to use them. + +
+
+ {/* Examples - coming soon */} + {/*
+ +
+

Examples

+

Code examples and snippets for Supabase products.

+
+ +
*/} + {/* CLI */} +
+ +
+

CLI

+

Manage your Supabase projects from the command line.

+
+ +
+ {/* */} +
+
+ +## Tools + +The Supabase Reference Docs provide technical descriptions of the products and how to use them. + +
+
+ {/* Examples - coming soon */} +
+ +
+

Auth

+

Auth reference.

+
+ +
+{/* NOT YET IMPLEMENTED +
+ +
+

Connection Pool

+

PgBouncer reference docs.

+
+ +
+ */} +
+
+ +## Client Libraries + +
+
+ {/* Database */} +
+ +
+

JavaScript

+

JavaScript and TypeScript documentation.

+
+ +
+ {/* Auth */} +
+ +
+

Dart

+

Dart and Flutter documentation.

+
+ +
+
+
+ +### Library Structure + +Our approach for client libraries is modular. Each sub-library is a standalone implementation for a single external system, maintained by Supabase or our community. +This is one of the ways we support existing tools and open source contributors. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Supabase Tool: + + PostgREST + + + + GoTrue + + + + Realtime + + + + Storage + + + + Edge Functions + +
JavaScript (TypeScript) + + supabase-js + + + + postgrest-js + + + + gotrue-js + + + + realtime-js + + + + storage-js + + + + functions-js + +
Dart + + supabase-dart + + + + postgrest-dart + + + + gotrue-dart + + + + realtime-dart + + + + storage-dart + + + + functions-dart + +
Flutter + + supabase-flutter + + -----
Community
C# + + supabase-csharp + + + + postgrest-csharp + + + + gotrue-csharp + + + + realtime-csharp + + + + storage-csharp + + -
Go- + + postgrest-go + + -- + + storage-go + + -
Java-- + + gotrue-java + + ---
Kotlin- + + postgrest-kt + + + + gotrue-kt + + ---
Python + + supabase-py + + + + postgrest-py + + + + gotrue-py + + + + realtime-py + + + + storage-py + + -
Ruby + + supabase-rb + + + + postgrest-rb + + ----
Rust- + + postgrest-rs + + ----
Swift + + supabase-swift + + + + postgrest-swift + + + + gotrue-swift + + + + realtime-swift + + + + storage-swift + + -
diff --git a/apps/reference/docs/support.md b/apps/reference/docs/support.md new file mode 100644 index 00000000000..4c8f1572ffa --- /dev/null +++ b/apps/reference/docs/support.md @@ -0,0 +1,21 @@ +--- +id: support +title: Support +description: Supabase Support +--- + +How can we help? + +## Community Support + +For help and questions about best practices, we have a discussion forum set up on GitHub: https://github.com/supabase/supabase/discussions + +## Business Support + +We offer email based support for business users. You can email us at support@supabase.io. + +If you need SLAs, guaranteed response times, or other enterprise level services, please contact us at this email address. + +## Slack Support + +If you are building with Supabase and you would like to set up a shared Slack channel (via [Slack Connect](https://slack.com/connect)), please reach out to us at support@supabase.io. diff --git a/apps/reference/docusaurus.config.js b/apps/reference/docusaurus.config.js index aeb4c92c3be..72349d8ec6a 100644 --- a/apps/reference/docusaurus.config.js +++ b/apps/reference/docusaurus.config.js @@ -132,6 +132,11 @@ const config = { themeConfig: /** @type {import('@docusaurus/preset-classic').ThemeConfig} */ ({ + docs: { + sidebar: { + autoCollapseCategories: true, + }, + }, navbar: { // title: 'Supabase Docs', logo: { diff --git a/apps/reference/nav/_referenceSidebars.js b/apps/reference/nav/_referenceSidebars.js index aad2202596d..167b84482d9 100644 --- a/apps/reference/nav/_referenceSidebars.js +++ b/apps/reference/nav/_referenceSidebars.js @@ -3,9 +3,202 @@ const sidebars = { { type: 'category', label: 'Overview', - items: ['about'], + items: [ + 'about', + 'architecture', + 'guides/hosting/platform', + 'guides/local-development', + 'guides/examples', + ], collapsed: true, }, + { + type: 'category', + label: 'Quickstarts', + collapsed: true, + items: [ + 'guides/with-angular', + 'guides/with-expo', + 'guides/with-flutter', + 'guides/with-ionic-angular', + 'guides/with-ionic-react', + 'guides/with-ionic-vue', + 'guides/with-nextjs', + 'guides/with-nuxt-3', + 'guides/with-react', + 'guides/with-redwoodjs', + 'guides/with-solidjs', + 'guides/with-svelte', + 'guides/with-sveltekit', + 'guides/with-vue-3', + ], + }, + { + type: 'category', + label: 'Database', + collapsed: true, + items: [ + 'guides/database', + 'guides/database/connecting-to-postgres', + 'guides/database/tables', + 'guides/database/functions', + 'guides/database/full-text-search', + // 'guides/database/json', + // 'guides/database/arrays', + // 'guides/database/sql-to-api', + { + type: 'category', + label: 'Extensions', + collapsed: true, + items: [ + 'guides/database/extensions', + // 'guides/database/extensions/pgtap', + 'guides/database/extensions/plv8', + 'guides/database/extensions/http', + 'guides/database/extensions/uuid-ossp', + ], + }, + { + type: 'category', + label: 'Configuration', + collapsed: true, + items: [ + 'guides/database/timeouts', + 'guides/database/replication', + 'guides/database/managing-passwords', + 'guides/database/managing-timezones', + ], + }, + ], + }, + { + type: 'category', + label: 'APIs', + collapsed: true, + items: ['guides/api', 'guides/api/generating-types'], + }, + { + type: 'category', + label: 'Functions', + collapsed: true, + items: ['guides/functions'], + }, + { + type: 'category', + label: 'Auth', + collapsed: true, + items: [ + 'guides/auth', + { + type: 'category', + label: 'Authentication', + collapsed: true, + items: [ + 'guides/auth/auth-email', + 'guides/auth/auth-magic-link', + 'guides/auth/auth-apple', + 'guides/auth/auth-azure', + 'guides/auth/auth-bitbucket', + 'guides/auth/auth-discord', + 'guides/auth/auth-facebook', + 'guides/auth/auth-github', + 'guides/auth/auth-gitlab', + 'guides/auth/auth-google', + 'guides/auth/auth-keycloak', + 'guides/auth/auth-linkedin', + 'guides/auth/auth-notion', + 'guides/auth/auth-slack', + 'guides/auth/auth-spotify', + 'guides/auth/auth-twitch', + 'guides/auth/auth-twitter', + 'guides/auth/auth-workos', + 'guides/auth/auth-zoom', + 'guides/auth/auth-twilio', + 'guides/auth/auth-vonage', + 'guides/auth/auth-messagebird', + ], + }, + { + type: 'category', + label: 'Authorization', + collapsed: true, + items: [ + 'guides/auth/row-level-security', + 'guides/auth/managing-user-data', + ], + }, + { + type: 'category', + label: 'Deep Dive', + collapsed: true, + items: [ + 'learn/auth-deep-dive/auth-deep-dive-jwts', + 'learn/auth-deep-dive/auth-row-level-security', + 'learn/auth-deep-dive/auth-policies', + 'learn/auth-deep-dive/auth-gotrue', + 'learn/auth-deep-dive/auth-google-oauth', + ], + }, + ], + }, + { + type: 'category', + label: 'Storage', + collapsed: true, + items: ['guides/storage'], + }, + { + type: 'category', + label: 'Platform', + collapsed: true, + items: [ + 'guides/platform/logs', + 'guides/platform/metrics', + 'going-into-prod', + 'guides/platform/performance', + 'guides/platform/permissions', + ], + }, + { + type: 'category', + label: 'Self Hosting', + collapsed: true, + items: ['guides/hosting/overview', 'guides/hosting/docker'], + }, + { + type: 'category', + label: 'Integrations', + collapsed: true, + items: [ + 'guides/integrations/appsmith', + 'guides/integrations/auth0', + 'guides/integrations/clerk', + 'guides/integrations/dashibase', + 'guides/integrations/directus', + 'guides/integrations/draftbit', + 'guides/integrations/pgmustard', + 'guides/integrations/plasmic', + 'guides/integrations/prisma', + 'guides/integrations/snaplet', + 'guides/integrations/stytch', + 'guides/integrations/supertokens', + 'guides/integrations/vercel', + ], + }, + { + type: 'category', + label: 'See Also', + collapsed: true, + items: [ + 'faq', + 'handbook/contributing', + 'handbook/supasquad', + 'company/terms', + 'company/privacy', + 'company/aup', + 'company/sla', + ], + }, ], reference: [ { diff --git a/apps/reference/package-lock.json b/apps/reference/package-lock.json index cda2170089d..80f37469fb2 100644 --- a/apps/reference/package-lock.json +++ b/apps/reference/package-lock.json @@ -14,6 +14,7 @@ "@mdx-js/react": "^1.6.22", "clsx": "^1.2.1", "docusaurus-theme-search-typesense": "^0.5.3", + "jsrsasign": "^10.5.26", "prism-react-renderer": "^1.3.5", "react": "^17.0.2", "react-dom": "^17.0.2" @@ -8332,6 +8333,14 @@ "graceful-fs": "^4.1.6" } }, + "node_modules/jsrsasign": { + "version": "10.5.26", + "resolved": "https://registry.npmjs.org/jsrsasign/-/jsrsasign-10.5.26.tgz", + "integrity": "sha512-TjEu1yPdI+8whpe6CA/6XNb7U1sm9+PUItOUfSThOLvx7JCfYHIfuvZK2Egz2DWUKioafn98LPuk+geLGckxMg==", + "funding": { + "url": "https://github.com/kjur/jsrsasign#donations" + } + }, "node_modules/keyv": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/keyv/-/keyv-3.1.0.tgz", @@ -19462,6 +19471,11 @@ "universalify": "^2.0.0" } }, + "jsrsasign": { + "version": "10.5.26", + "resolved": "https://registry.npmjs.org/jsrsasign/-/jsrsasign-10.5.26.tgz", + "integrity": "sha512-TjEu1yPdI+8whpe6CA/6XNb7U1sm9+PUItOUfSThOLvx7JCfYHIfuvZK2Egz2DWUKioafn98LPuk+geLGckxMg==" + }, "keyv": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/keyv/-/keyv-3.1.0.tgz", diff --git a/apps/reference/package.json b/apps/reference/package.json index d47236636db..4614bb01534 100644 --- a/apps/reference/package.json +++ b/apps/reference/package.json @@ -26,6 +26,7 @@ "@mdx-js/react": "^1.6.22", "clsx": "^1.2.1", "docusaurus-theme-search-typesense": "^0.5.3", + "jsrsasign": "^10.5.26", "prism-react-renderer": "^1.3.5", "react": "^17.0.2", "react-dom": "^17.0.2" diff --git a/apps/reference/src/components/Collapsable.js b/apps/reference/src/components/Collapsable.js new file mode 100644 index 00000000000..467da37cc18 --- /dev/null +++ b/apps/reference/src/components/Collapsable.js @@ -0,0 +1,10 @@ +import React from 'react' + +export default function Collapsable({ title, children }) { + return ( +
+ {title} +
{children}
+
+ ) +} diff --git a/apps/reference/src/components/CustomCodeBlock.js b/apps/reference/src/components/CustomCodeBlock.js new file mode 100644 index 00000000000..484c8896661 --- /dev/null +++ b/apps/reference/src/components/CustomCodeBlock.js @@ -0,0 +1,68 @@ +import React, { useState } from 'react' +import CodeBlock from '@theme/CodeBlock' + +export default function CustomCodeBlock({ + header, + code, + highlight, + js, + jsHighlight, + response, + language, +}) { + const [showResponse, toggleResponse] = useState(false) + + let wrapperClass = '' + if (header) wrapperClass += ' code-with-header' + if (response) wrapperClass += ' code-with-response' + + return ( + <> +
+ {header &&
{header}
} + <> + {code && ( + + {code} + + )} + {js && {js}} + +
+ {response && ( + <> + + + )} + + ) +} + +const styles = { + responseShown: { + textAlign: 'right', + display: 'block', + borderRadius: '0', + color: 'var(--custom-primary)', + borderTop: '1px solid #444', + }, + responseHidden: { + textAlign: 'right', + display: 'block', + borderBottom: 'none', + borderRadius: '0 0 4px 4px', + borderTop: '1px solid #444', + color: '#ccc', + }, +} diff --git a/apps/reference/src/components/Extensions.js b/apps/reference/src/components/Extensions.js new file mode 100644 index 00000000000..4503cf07592 --- /dev/null +++ b/apps/reference/src/components/Extensions.js @@ -0,0 +1,72 @@ +import React, { useState } from 'react' +import extensions from '@site/src/data/extensions.json' + +export default function Extensions() { + const [filter, setFilter] = useState('') + return ( + <> +
+ setFilter(e.target.value)} + /> +
+
+ {extensions + .filter((x) => x.name.indexOf(filter) >= 0) + .map((extension) => ( +
+
+

+ {extension.name} +

+

+ {extension.comment.charAt(0).toUpperCase() + + extension.comment.slice(1)} +

+
+
+ ))} +
+ + ) +} + +const styles = { + inputContainer: { + marginBottom: '15px', + }, + input: { + border: '1px solid var(--ifm-panel-border-color)', + borderRadius: 4, + backgroundColor: 'var(--custom-background-color-diff)', + color: 'var(--ifm-font-color-base)', + margin: 0, + padding: '6px 8px', + width: 300, + }, + column: { + margin: '5px 0px', + padding: '0px 5px', + }, + card: { + border: '1px solid var(--ifm-panel-border-color)', + borderRadius: 5, + padding: 8, + }, + title: { + margin: 0, + fontSize: '0.9rem', + border: '1px solid var(--ifm-panel-border-color)', + }, + description: { + fontSize: '0.8rem', + margin: 0, + }, +} diff --git a/apps/reference/src/components/Figure.js b/apps/reference/src/components/Figure.js new file mode 100644 index 00000000000..2e90ff02667 --- /dev/null +++ b/apps/reference/src/components/Figure.js @@ -0,0 +1,12 @@ +import React from 'react' + +export default function Figure({ src, alt, caption }) { + return ( +
+
+ {alt} +
{caption}
+
+
+ ) +} diff --git a/apps/reference/src/components/GithubCard.js b/apps/reference/src/components/GithubCard.js new file mode 100644 index 00000000000..67f4bd2e13b --- /dev/null +++ b/apps/reference/src/components/GithubCard.js @@ -0,0 +1,42 @@ +import React from 'react' + +export default function GithubCard({ + title, + description, + href, + stars, + handle, +}) { + return ( + +
+

+ {title.toUpperCase()} +

+ {description} +
+
+
+
@{handle}
+
{stars} ★
+
+
+ ) +} + +const styles = { + hr: { + margin: '15px 0 10px 0', + }, + h3: { + margin: 0, + textTransform: 'capitalize', + }, + cardBase: { + display: 'flex', + flexDirection: 'row', + justifyContent: 'space-between', + padding: '0 15px 10px 15px', + fontSize: '0.8em', + }, +} diff --git a/apps/reference/src/components/HowCard.js b/apps/reference/src/components/HowCard.js new file mode 100644 index 00000000000..de33c4d66e3 --- /dev/null +++ b/apps/reference/src/components/HowCard.js @@ -0,0 +1,57 @@ +import React from 'react' + +export default function HowCard({ + title, + description, + featureTitle, + features, +}) { + return ( +
+
+

{title}

+
+ {description} +
{featureTitle}
+
+ {features.map((x, i) => ( +
+ + ✔ + + {x} +
+ ))} +
+
+
+
+ ) +} + +const styles = { + h4: { + padding: 10, + textAlign: 'center', + borderBottom: '1px solid #000', + margin: 0, + }, + h5: { + textTransform: 'uppercase', + // opacity: 0.5, + margin: '10px 0 0px 0', + fontSize: '0.9em', + }, + card: { + border: '1px solid #000', + boxShadow: 'none', + }, + cardBase: { + fontSize: '0.9em', + }, + check: { + width: 10, + height: 10, + marginRight: 10, + }, +} diff --git a/apps/reference/src/components/JwtGenerator.js b/apps/reference/src/components/JwtGenerator.js new file mode 100644 index 00000000000..aa768cb3374 --- /dev/null +++ b/apps/reference/src/components/JwtGenerator.js @@ -0,0 +1,115 @@ +import React, { useState } from 'react' +import KJUR from 'jsrsasign' +import CustomCodeBlock from './CustomCodeBlock' + +const JWT_HEADER = { alg: 'HS256', typ: 'JWT' } +const now = new Date() +const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()) +const fiveYears = new Date(now.getFullYear() + 5, now.getMonth(), now.getDate()) +const anonToken = ` +{ + "role": "anon", + "iss": "supabase", + "iat": ${Math.floor(today / 1000)}, + "exp": ${Math.floor(fiveYears / 1000)} +} +`.trim() + +const serviceToken = ` +{ + "role": "service_role", + "iss": "supabase", + "iat": ${Math.floor(today / 1000)}, + "exp": ${Math.floor(fiveYears / 1000)} +} +`.trim() + +export default function JwtGenerator({}) { + const [jwtSecret, setJwtSecret] = useState( + 'your-super-secret-jwt-secret-with-at-least-32-characters-long' + ) + const [token, setToken] = useState(anonToken) + const [signedToken, setSignedToken] = useState('') + + const handleKeySelection = (e) => { + const val = e.target.value + if (val == 'service') setToken(serviceToken) + else setToken(anonToken) + } + + const generate = () => { + const signedJWT = KJUR.jws.JWS.sign(null, JWT_HEADER, token, jwtSecret) + setSignedToken(signedJWT) + } + + return ( +
+
+ + setJwtSecret(e.target.value)} + /> +
+
+ + +
+
+ +