Logo

dev-resources.site

for different kinds of informations.

What does Supabase use for its Authentication?

Published at
12/25/2024
Categories
opensource
typescript
npm
supabase
Author
ramunarasinga-11
Author
16 person written this
ramunarasinga-11
open
What does Supabase use for its Authentication?

In this article, we analyse the authentication mechanism Supabase uses. You may have used Supabase Auth, but have you ever wondered what Supabase uses for its authentication? well, let’s find out.

Image description

signin.tsx

We have to start at Signin page, this can be found in studio workspace. Supabase is a monorepo and contains workspaces in apps folder.

and packages.

Let’s pick SignInForm as it has email and password based authentication. At line 51,, you will find the below component:

import SignInForm from 'components/interfaces/SignIn/SignInForm'

<SignInForm />
Enter fullscreen mode Exit fullscreen mode

SignInForm.tsx

In the file — SignIn/SignInForm.tsx, you will find the below code:

<Form
  validateOnBlur
  id="signIn-form"
  initialValues={{ email: '', password: '' }}
  validationSchema={signInSchema}
  onSubmit={onSignIn}
>
  {({ isSubmitting }: { isSubmitting: boolean }) => {
    return (
      <div className="flex flex-col gap-4">
        <Input
          id="email"
          name="email"
          type="email"
          label="Email"
          placeholder="[email protected]"
          disabled={isSubmitting}
          autoComplete="email"
        />

        <div className="relative">
          <Input
            id="password"
            name="password"
            type="password"
            label="Password"
            placeholder="&bull;&bull;&bull;&bull;&bull;&bull;&bull;&bull;"
            disabled={isSubmitting}
            autoComplete="current-password"
          />

          {/* positioned using absolute instead of labelOptional prop so tabbing between inputs works smoothly */}
          <Link
            href="/forgot-password"
            className="absolute top-0 right-0 text-sm text-foreground-lighter"
          >
            Forgot Password?
          </Link>
        </div>

        <div className="self-center">
          <HCaptcha
            ref={captchaRef}
            sitekey={process.env.NEXT_PUBLIC_HCAPTCHA_SITE_KEY!}
            size="invisible"
            onVerify={(token) => {
              setCaptchaToken(token)
            }}
            onExpire={() => {
              setCaptchaToken(null)
            }}
          />
        </div>

        <LastSignInWrapper type="email">
          <Button
            block
            form="signIn-form"
            htmlType="submit"
            size="large"
            disabled={isSubmitting}
            loading={isSubmitting}
          >
            Sign In
          </Button>
        </LastSignInWrapper>
      </div>
    )
  }}
</Form>
Enter fullscreen mode Exit fullscreen mode

onSignIn function

In the onSignIn function, auth.signInWithPassword is called.

const onSignIn = async ({ email, password }: { email: string; password: string }) => {
    const toastId = toast.loading('Signing in...')

    let token = captchaToken
    if (!token) {
      const captchaResponse = await captchaRef.current?.execute({ async: true })
      token = captchaResponse?.response ?? null
    }

    const { error } = await auth.signInWithPassword({
      email,
      password,
      options: { captchaToken: token ?? undefined },
    })
    ...
  }
Enter fullscreen mode Exit fullscreen mode

auth is imported from lib/gotrue as shown below:

import { auth, buildPathWithParams, getReturnToPath } from 'lib/gotrue'
Enter fullscreen mode Exit fullscreen mode

auth in lib/gotrue

You will find the below code in lib/gotrue for the auth function.

import { getAccessToken, gotrueClient } from 'common'
export const auth = gotrueClient
Enter fullscreen mode Exit fullscreen mode

auth is assigned a function named gotrueClient and this is imported from ‘common’. What’s common here? is that another npm package? no…

common package

Supabase is a monorepo and has a package named common. In the common/index.ts at line 6, you will find the below import:

export * from './gotrue'
Enter fullscreen mode Exit fullscreen mode

gotrueClient

At line 107, in common/gotrue.ts, you will find this below code:

export const gotrueClient = new AuthClient({
  url: process.env.NEXT_PUBLIC_GOTRUE_URL,
  storageKey: STORAGE_KEY,
  detectSessionInUrl: shouldDetectSessionInUrl,
  debug: debug ? (persistedDebug ? logIndexedDB : true) : false,
  lock: navigatorLockEnabled ? navigatorLock : undefined,
})
Enter fullscreen mode Exit fullscreen mode

AuthClient is imported from @supabase/auth-js.

import { AuthClient, navigatorLock } from '@supabase/auth-js'
Enter fullscreen mode Exit fullscreen mode

Read more about @supabase/auth-js.

In conclusion, Supabase uses its own library for its authentication.

About me:

Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.

I am open to work on an interesting project. Send me an email at [email protected]

My Github - https://github.com/ramu-narasinga
My website - https://ramunarasinga.com
My Youtube channel - https://www.youtube.com/@thinkthroo
Learning platform - https://thinkthroo.com
Codebase Architecture - https://app.thinkthroo.com/architecture
Best practices - https://app.thinkthroo.com/best-practices
Production-grade projects - https://app.thinkthroo.com/production-grade-projects

References:

  1. https://github.com/supabase/supabase/blob/master/apps/studio/pages/sign-in.tsx

  2. https://github.com/supabase/supabase/blob/master/apps/studio/pages/sign-in.tsx#L51

  3. https://github.com/supabase/supabase/tree/master/packages

  4. https://github.com/supabase/supabase/blob/master/packages/common/index.tsx

  5. https://www.npmjs.com/package/@supabase/auth-js

supabase Article's
30 articles in total
Favicon
Building Production-Grade Web Applications with Supabase – Part 1
Favicon
Tracing and Metrics in supabase/storage
Favicon
Understanding Storage backends in supabase/storage
Favicon
Auth in Supabase storage
Favicon
Overview of supabase storage repository
Favicon
Harnessing the Power of Self-Hosted Supabase on Coolify: A Complete Guide to Server Setup and OAuth Providers Integration
Favicon
checa como se hace una conexión entre nextjs y la autenticación de supabase
Favicon
Deploying an Existing Express API + Prisma + Supabase Project to Vercel
Favicon
Custom schema specific Supabase Server Component clients in Grida Form workspace
Favicon
Custom schema specific Supabase Client Component clients in Grida Form workspace
Favicon
Introducing Supabase Client Playground: The Ultimate Tool for Streamlined Query Testing
Favicon
hCaptcha, a bot detection tool, usage in Supabase and Chatwoot
Favicon
Securing Client-Side Routes in Next.js with Supabase
Favicon
How to Transfer PostgreSQL Database from Local to Supabase on macOS
Favicon
Supabase | My Way of Designing & Managing DB
Favicon
What does Supabase use for its Authentication?
Favicon
É seguro guardar dados do usuário no localStorage?
Favicon
Supabase RLS Alternative
Favicon
Build Queue Worker using Supabase Cron, Queue and Edge Function
Favicon
Supabase Just Got More Powerful: Queue, Cron, and Background Tasks in Edge Functions
Favicon
Comparison of the middleware implementation between Supabase Auth documentation and the nextjs-stripe-supabase.
Favicon
How Supabase implemented micro-frontends using Multi Zones in Next.js
Favicon
Unlocking User Data: Building a Secure Supabase Edge Function
Favicon
Usecase: TumbleLog
Favicon
Supabase Edge Functions
Favicon
Setup Astro With Supabase and Prisma
Favicon
We launched SupaCharts! Visualize Beautiful Charts from your Supabase Data.
Favicon
A Free Minimalistic SaaS Starter Kit for Fast MVP Building
Favicon
supabase注册并创建项目和添加数据表
Favicon
Integrating GitHub Authentication with NextAuth.js: A Step-by-Step Guide

Featured ones: