A collection of framework specific Auth utilities for working with Supabase.

Overview

@supabase/auth-helpers

A collection of framework specific Auth utilities for working with Supabase.

Supported Frameworks

Coming soon

Examples and Packages

  • Examples
  • Packages
    • @supabase/auth-helpers-nextjs: the supabase auth helper nextjs library used by nextjs application
    • @supabase/auth-helpers-react: the supabase auth helper reactjs library used by nextjs application
    • shared: shared typescript types used by @supabase/auth-helpers-nextjs library
    • config: eslint configurations (includes eslint-config-next and eslint-config-prettier)
    • tsconfig: tsconfig.jsons used throughout the monorepo

Each package/app is 100% TypeScript.

Utilities

This turborepo has some additional tools already setup for you:

Setup

This repository is a monorepo using PNPM.

Install pnpm

All commands below should be run at the root level of the cloned repository.

Install all examples and packages dependencies with pnpm

pnpm install

Build

To build all apps and packages, run the following command:

pnpm build

Develop

To develop all apps and packages, run the following command:

pnpm dev

Change logs

To generate a changelog entry, run the following command:

pnpm changeset
Comments
  • sveltekit helpers update

    sveltekit helpers update

    Closes #230

    What kind of change does this PR introduce?

    Support new versions of sveltekit (around 1.0.0-next.440 upwards, random guess based on their changelog)

    What is the current behavior?

    We can´t use auth helpers with the current version of sveltekit.

    Additional context

    Since there is no need for a Svelte component we could build the sveltekit helpers with tsup like the other packages.

    PS: SvelteKit is in release candidate phase!

    Edit: very sorry for this huge commit :/

    enhancement sveltekit 
    opened by david-plugge 67
  • Next.js 13 `app` directory support

    Next.js 13 `app` directory support

    With version v0.5.2 we've added a createServerComponentSupabaseClient which can be used server components to get an authenticated Supabase client. This is the PR which includes an example. Note that this needs to be used in combination with middleware as Next.js does not yet allow setting headers in server components.

    Docs to follow soon.

    enhancement nextjs 
    opened by thorwebdev 44
  • SvelteKit removed Session store

    SvelteKit removed Session store

    Bug report

    Describe the bug

    The latest version of SvelteKit removes the Session store, breaking the Svelte and SvelteKit auth helpers. See: https://github.com/sveltejs/kit/discussions/5883#discussion-4302953

    Expected behavior

    Be able to use auth-helpers with latest version of SvelteKit

    bug 
    opened by AlgorithmEnigma 27
  • Create auth helpers for Remix

    Create auth helpers for Remix

    Like with Next.js which currently has easy to use helpers and routes, the same could be done for Remix.

    I didn't find an open issue about this, although I heard it's planned, so it can be tracked here.

    enhancement remix 
    opened by VictorPeralta 26
  • Supabase Auth and Next.js SSR: User redirected back to my website after logging in sees the logged out version of the page.

    Supabase Auth and Next.js SSR: User redirected back to my website after logging in sees the logged out version of the page.

    Hi! I am using Next.js and Supabase Auth to build a platform for selling courses.

    When the user is logged in and has bought the course, I want to show them the content. When the user is logged out, I want to show them the paywall. It is important to me that course content is server-side rendered.

    I am checking whether the user is logged (and whether they own the course) inside getServerSideProps() like so:

    import { getUser } from '@supabase/auth-helpers-nextjs'
    import prisma from 'prisma/prismaClient'
    
    export async function getServerSideProps({ params, req, res }) {
      // Check whether the user owns this course
      let ownsCourse = false
      const { user } = await getUser({ req, res }) // Access the user object
      if (user) {
        const profile = await prisma.profile.findUnique({
          where: { id: user.id },
          include: { courses: true },
        })
        ownsCourse = profile.courses.some((c) => c.courseId === courseSlug)
      }
      [...]
    }
    

    My problem is that when the user logs in, and is redirected back to my website, they still see the logged out version of the page (with the paywall). They have to reload the page manually to see the signed in version.

    I'm guessing that happens because after the user is redirected back to my website, getServerSideProps() sees that they don't have any auth cookies yet, so it renders the signed out version of the page. Then the frontend code realizes that I just logged in, and sets the auth cookies, but at this point the page has already been rendered.

    Can you please share some advice? How can I solve this?

    You can see my code here.

    question nextjs 
    opened by lumenwrites 15
  • fix: type useSupabaseClient

    fix: type useSupabaseClient

    Fixes #273

    You can pass types that were generated with the Supabase CLI to the Supabase Client to get enhanced type safety and auto completion:

    // Creating a new supabase client object:
    import { Database } from '../db_types';
    
    const [supabaseClient] = useState(() =>
        createBrowserSupabaseClient<Database>()
      );
    
    // Retrieving a supabase client object from the SessionContext:
    import { useSupabaseClient } from '@supabase/auth-helpers-react';
    import { Database } from '../db_types';
    
    const supabaseClient = useSupabaseClient<Database>();
    
    opened by thorwebdev 12
  • npm install fails for @supabase/auth-helpers-sveltekit

    npm install fails for @supabase/auth-helpers-sveltekit

    Bug report

    Describe the bug

    unable to resolve dependency tree

    To Reproduce

    Steps to reproduce the behavior, please provide code snippets or a repository:

    1. come to any of the official sources such as npmjs.com, see that package was last updated few days ago and is at version 0.7.1 latest
    2. run "npm i @supabase/auth-helpers-sveltekit"
    3. watch screen fill with red

    Expected behavior

    stuff working as it should!

    Screenshots

    └ $ npm i @supabase/auth-helpers-sveltekit
    npm ERR! code ERESOLVE
    npm ERR! ERESOLVE unable to resolve dependency tree
    npm ERR!
    npm ERR! While resolving: [email protected]
    npm ERR! Found: @supabase/[email protected]
    npm ERR! node_modules/@supabase/supabase-js
    npm ERR!   @supabase/supabase-js@"^2.0.0-rc.10" from the root project
    npm ERR!
    npm ERR! Could not resolve dependency:
    npm ERR! peer @supabase/supabase-js@"^1.35.3" from @supabase/[email protected]
    npm ERR! node_modules/@supabase/auth-helpers-sveltekit
    npm ERR!   @supabase/auth-helpers-sveltekit@"*" from the root project
    npm ERR!
    npm ERR! Fix the upstream dependency conflict, or retry
    npm ERR! this command with --force, or --legacy-peer-deps
    npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
    npm ERR!
    npm ERR! See C:\Users\xxx\AppData\Local\npm-cache\eresolve-report.txt for a full report.
    
    npm ERR! A complete log of this run can be found in:
    npm ERR!     C:\Users\xxx\AppData\Local\npm-cache\_logs\2022-10-02T00_53_00_263Z-debug-0.log
    

    System information

    	"devDependencies": {
    		"@sveltejs/adapter-auto": "next",
    		"@sveltejs/kit": "next",
    		"svelte": "^3.46.0",
    		"vite": "^3.1.0"
    	},
    	"type": "module",
    	"dependencies": {
    		"@fontsource/fira-mono": "^4.5.0",
    		"@supabase/supabase-js": "^2.0.0-rc.10"
    	}
    

    Additional context

    this is so frustrating, auth-helper not playing nice with older version of supabase-js so need to update supabase-js but then current auth-helper doesn't like latest version of supabase-js, which in turn doesn't like earlier version of auth-helper. I feel like developers don't even bother testing, checking, updating documentation and just do it for the sake of github heatmap being filled up

    opened by secretgspot 12
  • NextJS - Invalid Refresh Token

    NextJS - Invalid Refresh Token

    On the latest release, using purely the example in examples/nextjs, after the exp time elapses, I'm getting the following error.

    image

    How can I make sure that the automatic token refresh fires off properly?

    (Local development via supabase start and its associated container(s))

    question nextjs 
    opened by ARMATAV 11
  • chore: next 12.2.x middleware upgrade

    chore: next 12.2.x middleware upgrade

    closes https://github.com/supabase-community/auth-helpers/issues/168 closes https://github.com/supabase-community/auth-helpers/issues/144 likely closes https://github.com/supabase-community/auth-helpers/issues/166

    my general idea for the middleware part would be, that we'll be able to define a list of route guards, each may have a list of path-matchers (similar to the stock matcher configuration) and each may have the options we were defining before with the nested routes.

    regarding the matchers I have yet to find a nice approach on how to replicate the behavior of the stock matchers. So, right now this is meant as a draft to get some feedback if that API would be sth. we could live & work with.

    opened by boredland 11
  • Next 13 example (app/ Directory)

    Next 13 example (app/ Directory)

    Feature request

    Next 13 has been released https://nextjs.org/blog/next-13#layouts and a new app structure with data fetching has been introduced (currently in beta).

    Is your feature request related to a problem? Please describe.

    I tried to adapt but I got errors on server side that the supabase client has problem with the polyfilled fetch provided by next.

    Describe the solution you'd like

    Just a minimal working example would be nice :)

    enhancement nextjs 
    opened by wiesson 10
  • "No cookie found!" in Console

    My Next app has a mix of public and protected pages. As shown in the example, I wrapped all pages in a UserProvider:

    import type { AppProps } from "next/app";
    import { UserProvider } from "@supabase/supabase-auth-helpers/react";
    import { supabaseClient } from "@supabase/supabase-auth-helpers/nextjs";
    
    function App({ Component, pageProps }: AppProps) {
      return (
        <UserProvider supabaseClient={supabaseClient}>
          <Component {...pageProps} />
        </UserProvider>
      );
    }
    
    export default App;
    

    However, on all pages, the error message No cookie found! is being printed to console if the user is not logged in. I believe this happens because the UserProvider is requesting /api/auth/user, which is handled by getUser.ts. getUser.ts checks if an access_token is present, which of course is always false if the user is not logged in.

    The problem is that this happens even on pages that don't even need the user to be logged in, e.g. my home page:

    import Head from "next/head";
    import type { NextPage } from "next";
    
    const HomePage: NextPage = () => {
      return (
        <div>
          <Head>
            <title>Hello world!</title>
            <link rel="icon" href="/favicon.ico" />
          </Head>
    
          <main>
            <h1>Hello world!</h1>
          </main>
        </div>
      );
    };
    
    export default HomePage;
    

    Is this the desired behavior or is there a way to only request the user if a page uses useUser()? I tried adding export const getServerSideProps = withPageAuth({ authRequired: false }); to the public pages, but doesn't change anything.

    Thanks for your help! 🎉

    bug 
    opened by gian-reto 10
  • useSession/useUser returns null initially when reloading page for a logged-in user

    useSession/useUser returns null initially when reloading page for a logged-in user

    Bug report

    useSession/useUser returns null initially when reloading page for a logged-in user.

    Describe the bug

    I am trying to conditionally render a login page with Supabase, whereby if the user is already logged in, there should be a redirect to the home page. I am using NextJS 13.

    Right now, I have this:

    import {
        Auth,
        // Import predefined theme
        ThemeSupa,
    } from '@supabase/auth-ui-react'
    import { useSession, useSupabaseClient } from '@supabase/auth-helpers-react'
    import { Box } from '@mantine/core';
    import { useRouter } from 'next/router'
    
    export default function AuthComp() {
        const supabase = useSupabaseClient()
        const session = useSession()
        const router = useRouter()
    
        console.log(session)
    
        if (session) {
            router.push('/')
        } else {
            return (
                <Box sx={{
                    paddingLeft: '35vw',
                    paddingRight: '35vw',
                    paddingTop: '10vh',
                }}>
                    <Auth
                        redirectTo="http://localhost:3000"
                        supabaseClient={supabase}
                        theme="dark"
                        appearance={{ theme: ThemeSupa }}
                        providers={['google', 'github', 'linkedin']}
                    />
                </Box>
            )
        }
    }
    

    However, it seems that useSession may be returning null at first, leading to the Auth-UI rendering for a split second, and then returning the session, leading to the redirect. image

    I want to make it so that the Auth-UI rendering for a split second does not happen. Is this possible? The docs are unclear about this.

    I have confirmed this happens if I use useUser as well.

    Expected behavior

    The hooks should only provide null if there is no user/session, and should not return null at all when the user is logged in.

    System information

    • OS: macOS
    • Browser (if applies) chrome
    • Version of supabase-js: 2.2.2
    • Version of next-js: 13.0.0
    bug 
    opened by vymao 0
  • Fix getServerSession parameter type

    Fix getServerSession parameter type

    "getServerSession" is mainly used inside a "LayoutServerLoad" function (it expose an event typed "ServerLoadEvent"), but the event object is only propagated to "getRequestSupabaseClient" that accept a generic "RequestEvent". It doesn't work if I need to get the server session from an api (see https://kit.svelte.dev/docs/routing#server) that by "RequestHandler" offer only a generic "RequestEvent" insead of an "ServerLoadEvent".

    What kind of change does this PR introduce?

    Bug fix

    What is the current behavior?

    getServerSession has incompatible event type if used by apis (see https://kit.svelte.dev/docs/routing#server)

    What is the new behavior?

    Only a replacement for a more generic type

    Additional context

    opened by epavanello 1
  • [Breaking] Allow initial responses from supabase to be reused from the server when doing SSR

    [Breaking] Allow initial responses from supabase to be reused from the server when doing SSR

    This is basically the SvelteKit version of #396, which is why I have not created a new issue.

    Also, this is the first time I'm doing a PR for this project, so please do point out if some things should be done differently.

    What kind of change does this PR introduce?

    One of SvelteKit's features is that if you use the fetch function provided in the load functions, you can avoid fetching data the server just fetched when the client loads.

    This is a breaking change, requiring a slight change to the hooks.server.ts/js file. Specifically:

    In the src/hooks.server.js we also need to whitelist some Supabase headers to prevent them from being stripped out by SvelteKit:

    If you don't have a custom handle hook, then you can add the following:

    import { allowSupabaseServerSideRequests } from '@supabase/auth-helpers-sveltekit';

    export const handle = allowSupabaseServerSideRequests;

    > Otherwise, you can add the following to your existing `handle` hook:
    > ```ts
    import { RequiredWhitelistedHeaders } from '@supabase/auth-helpers-sveltekit';
    
    export async function handle({ event, resolve }) {
      // ... your existing code
    
      const response = await resolve(event, {
        // This is the important bits.
        filterSerializedResponseHeaders(name: string, _value: string): boolean {
          return RequiredWhitelistedHeaders.includes(name);
        }
      });
    
      // ... More of your code
    
      return response;
    }
    

    I also fixed #409 to enable TypedSupabaseClient to be imported directly from @supabase/auth-helpers-sveltekit while I was here.

    What is the current behavior?

    Data is loaded twice, first on the server, then on the client on the initial navigation.

    What is the new behavior?

    Data is only loaded once, server side, on the initial load. Afterwards purely client side loading is used.

    opened by zlepper 0
  • TypedSupabaseClient should be moved directly to `@supabase/auth-helpers-sveltekit`

    TypedSupabaseClient should be moved directly to `@supabase/auth-helpers-sveltekit`

    Bug report

    Describe the bug

    The type TypedSupabaseClient is currently in @supabase/auth-helpers-sveltekit/dist/types, when imported.

    To Reproduce

    Try to import TypedSupabaseClient

    Expected behavior

    It should be imported from @supabase/auth-helpers-sveltekit instead.

    System information

    • OS: Windows
    		"@supabase/auth-helpers-sveltekit": "0.8.6",
    		"@supabase/supabase-js": "2.2.2"
    
    bug 
    opened by zlepper 0
  • [SvelteKit] Error: The

    [SvelteKit] Error: The "host" request header is not available at isSecureEnvironment - When fetching from API routes

    Bug report

    Describe the bug

    When fetching from an API route from a client side or server side page, Supabase auth lib will throw an error: Error: The "host" request header is not available at isSecureEnvironment

    To Reproduce

    Example repo to reproduce: https://github.com/chanmathew/sk-supabase-authhelpers-host-request-header-issue

    1. Create an API route, in the example repo, I created /routes/api/products/+server.ts
    2. Fetch from this new API route from a page (Doesn't matter if it's client side OR server side, I've tested and issue exists for both), in the example repo I made a server side fetch from /routes/products/+page.server.ts
    3. Load the /products page in browser and check logs in server console, you will see this error from Supabase auth helpers: Error: The "host" request header is not available at isSecureEnvironment

    Expected behavior

    This error should not be thrown, especially given the API route is not fetching data from Supabase and is completely unrelated.

    System information

    • OS: macOS Ventura 13.1 (22C65)
    • Browser: Chrome 108.0.5359.124
    • Version of supabase-js: 2.2.2
    • Version of Node.js: 16.17.0
    bug 
    opened by chanmathew 2
  • Injecting type definitions does not work

    Injecting type definitions does not work

    Bug report / Feature request

    Describe the bug / missing feature

    Typescript throws error "Expected 0 type arguments, but got 1" and types do not get injected when import { createClient } from "@supabase/auth-helpers-sveltekit"

    To Reproduce

    Steps to reproduce the behavior, please provide code snippets or a repository:

    ` import { createClient } from "@supabase/auth-helpers-sveltekit" import type { Database } from "./database.types";

    export const supabaseClient = createClient{PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY,} `

    Expected behavior

    Same behaviour when importing { createClient } from "@supabase/supabase-js"

    System information

    • Version of supabase-js': 2.2.2
    • Version of auth-helpers-sveltekit': 0.8.6
    • Version of sveltekit: 1.0.0

    Additional context

    When importing from "@supabase/supabase-js" type injecting works but logout functionality does not work any more

    Workaround

    Create 2 clients one with the import from "@supabase/supabase-js" and one with the import from "@supabase/auth-helpers-sveltekit"

    opened by TomsPoint 0
Releases(@supabase/[email protected])
Owner
Supabase Community
Maintained and supported by the Supabase Community.
Supabase Community
Work from is a web app created by Josh Cawthorne for the Supabase Hackathon.

Work From What is Work From? Work from is a web app created by Josh Cawthorne for the Supabase Hackathon. The concept of the app is for companies to b

Josh Cawthorne 86 Jan 3, 2023
Boilerplate for a NextJS and Supabase Project. Including full authentication with sign up, login and password recovery.

NextJS x Supabase Boilerplate Getting Started Environment variables Create the enviroment variables with the following command cp .env.local.dist .env

Dominik Amrugiewicz 9 Jun 13, 2022
Next.js + Prisma + Supabase simple Blog example

Next.js + Prisma + Supabase Blog Project About the Project Prisma connects the PostgreSQL Database provided by Supabase by using postgres connection s

Soham Shah 4 Nov 19, 2022
Edvora App is a web application based on an external API, showing data about different types of products and the user can filter these data by choosing a specific state, city or product name. Build with React.js

Edvora App is a web application based on an external API, showing data about different types of products and the user can filter these data by choosing a specific state, city or product name. Build with React.js

Kyrillos Hany 5 Mar 11, 2022
cms for next.js based on supabase for developers.

one cms for next.js based on supabase for developers. disclaimer one is in early and active development and currently not functional. all the @one pac

Jonas Wanner 6 Aug 27, 2022
Tamagui with Supabase, Expo, Next.js, Solito and Jotai

Tamagui + Supabase + Solito + Next + Expo Monorepo ⚡️ Instant clone & deploy ?? About This monorepo is a starter todo app, built using Supabase + Expo

Lachlan Hawthorne 15 Dec 12, 2022
Starter Antd 4.0 Admin App Mern( Node.js / React / Redux / Ant Design ) Crud & Auth , Dashboard

Starter Antd Admin (Crud & auth) Mern App (Express.js / React / Redux / MongoDB) App built for DigitalOcean MongoDB Hackathon CRM Starter Mern Antd Ad

Salah Eddine Lalami 208 Jan 8, 2023
React + Redux starter kit / boilerplate with Babel, hot reloading, testing, linting and a working example app built in

A comprehensive starter kit for rapid application development using React. Why Slingshot? One command to get started - Type npm start to start develop

Cory House 9.8k Dec 22, 2022
A markdown-it plugin and Nunjucks async filter to make working with Cloudinary in Eleventy easier.

Cloudinary Eleventy Helpers This is a collection of Eleventy Cloudinary helpers. It currently includes: A markdown-it plugin that converts local image

Jason Lengstorf 9 Feb 2, 2022
Read Blog. This is also a practical project. Working with APIs more and Routing and many new things.

React blog This is a React blog that created with a custom API. We serve the API in our system and run blog with it. Goals of this project In this pro

AmirHossein Mohammadi 7 Jul 25, 2022
JavaScript Testing utilities for React

Enzyme Enzyme is a JavaScript Testing utility for React that makes it easier to test your React Components' output. You can also manipulate, traverse,

enzyme - JavaScript Testing utilities for React 20k Dec 28, 2022
🐐 Simple and complete React DOM testing utilities that encourage good testing practices.

React Testing Library Simple and complete React DOM testing utilities that encourage good testing practices. Read The Docs | Edit the docs Table of Co

Testing Library 17.3k Jan 4, 2023
Set of property utilities for Stitches with theme tokens support. Use the built-in utils, or easily build custom ones.

Stitches Mix Set of property utilities for Stitches with theme tokens support. Use the built-in utils, or easily build custom ones. Usage To import al

João Pedro Schmitz 12 Aug 8, 2022
Utilities library built on top of Next.js providing feature extensions and helpers for common patterns

nextjs-utilites This library provides many helpful utilities for use in Next.js projects. Prerequisites This project requires NodeJS (version 8 or lat

Snehil K 5 Sep 7, 2022
A collection of composable React components for building interactive data visualizations

an ecosystem of composable React components for building interactive data visualizations. Victory Contents Getting Started Victory Native API Document

Formidable 10.1k Jan 3, 2023
A collection of sample apps built using GetStream and React Native

React Native samples [ Built with ♥ at Stream ] This repo contains projects and samples developed by the team and Stream community, using React Native

Stream 93 Jan 8, 2023
use this to replace redux,you can use useActions to change context value and useActions return a mutable function collection

English | 中文 NOTE react-context-mutation is a lighter and more convenient state manager designed for react applications. It aims to replace the Redux

null 19 Feb 22, 2022
A collection of free logos for open source projects

Libre Logos Libre Logos is a library of free logos. The logos are intended for open source projects and NGOs. Designers are invited to contribute. The

E. Cleopatra 144 Nov 11, 2022
Collection of Animated 60 FPS TabBar Component's based on React Navigation.

React Navigation TabBar Collection Collection of Animated 60 FPS TabBar Components based on React Navigation. Features 60 FPS Animation Beautiful TabB

Mikalyh 22 Dec 9, 2022