mitchelvanbever / remix-auth-supabase

MIT License
102 stars 14 forks source link

Remix Auth - Supabase Strategy

Strategy for using supabase with Remix Auth

This strategy aims to provide an easy way to start using supabase for authentication in Remix.run apps! It uses remix-auth as its base bootstrapped from remix-auth-template) (thanks @sergiodxa πŸš€).

πŸ“– Examples

NOTICE 🚧

This library is maintained by people who do not make a living creating and maintining open source libraries, it's just a hobby and life takes priority over hobbies.

Having that said: Remix-auth-strategy was not designed with the intention to handle everything that we currently handle (refreshing tokens for example). This unfortunately could lead to scenarios where some of the features may not work as expected (beware).

Having all of this said, we're happy to keep this library alive for anyone who wants to (keep) using it.

πŸ’œ

Our official recommendation for production grade remix applications with supabase is to use the supa fly stack by RPHLMR 😎

Supported runtimes

Runtime Has Support
Node.js βœ…
Cloudflare βœ…

Introduction

The way remix-auth (and it's templates) are designed are not a direct fit for what I had in mind for a seamless authentication strategy with Supabase. After some back and forth between the community and playing around with various setups in vitest ⚑ we decided to create a strategy that supports the following:

How to use

Install the package (and remix-auth)

Breaking change v2 to v3

To allow for more freedom and support some of the different authentication types the verify no longer just sends the form, but it now sends the entire request. See Setup authenticator & strategy

Setup sessionStorage, strategy & authenticator

// app/auth.server.ts
import { createCookieSessionStorage } from '@remix-run/node';
import { Authenticator, AuthorizationError } from 'remix-auth';
import { SupabaseStrategy } from 'remix-auth-supabase-strategy';
import { Session, supabaseClient } from '~/supabase';

export const sessionStorage = createCookieSessionStorage({
  cookie: {
    name: 'sb',
    httpOnly: true,
    path: '/',
    sameSite: 'lax',
    secrets: ['s3cr3t'], // This should be an env variable
    secure: process.env.NODE_ENV === 'production'
  }
});

export const supabaseStrategy = new SupabaseStrategy(
  {
    supabaseClient,
    sessionStorage,
    sessionKey: 'sb:session', // if not set, default is sb:session
    sessionErrorKey: 'sb:error' // if not set, default is sb:error
  },
  // simple verify example for email/password auth
  async ({ req, supabaseClient }) => {
    const form = await req.formData();
    const email = form?.get('email');
    const password = form?.get('password');

    if (!email) throw new AuthorizationError('Email is required');
    if (typeof email !== 'string') throw new AuthorizationError('Email must be a string');

    if (!password) throw new AuthorizationError('Password is required');
    if (typeof password !== 'string') throw new AuthorizationError('Password must be a string');

    return supabaseClient.auth.api.signInWithEmail(email, password).then(({ data, error }): Session => {
      if (error || !data) {
        throw new AuthorizationError(error?.message ?? 'No user session found');
      }

      return data;
    });
  }
);

export const authenticator =
  new Authenticator() <
  Session >
  (sessionStorage,
  {
    sessionKey: supabaseStrategy.sessionKey, // keep in sync
    sessionErrorKey: supabaseStrategy.sessionErrorKey // keep in sync
  });

authenticator.use(supabaseStrategy);

Using the authenticator & strategy πŸš€

checkSession works like authenticator.isAuthenticated but handles token refresh

// app/routes/login.ts
export const loader: LoaderFunction = async ({ request }) =>
  supabaseStrategy.checkSession(request, {
    successRedirect: '/private'
  });

export const action: ActionFunction = async ({ request }) =>
  authenticator.authenticate('sb', request, {
    successRedirect: '/private',
    failureRedirect: '/login'
  });

export default function LoginPage() {
  return (
    <Form method="post">
      <input type="email" name="email" />
      <input type="password" name="password" />
      <button>Sign In</button>
    </Form>
  );
}
// app/routes/private.ts
export const loader: LoaderFunction = async ({ request }) => {
  // If token refresh and successRedirect not set, reload the current route
  const session = await supabaseStrategy.checkSession(request);

  if (!session) {
    // If the user is not authenticated, you can do something or nothing
    // ⚠️ If you do nothing, /profile page is display
  }
};

// Handle logout action
export const action: ActionFunction = async ({ request }) => {
  await authenticator.logout(request, { redirectTo: '/login' });
};
Refresh token or redirect
// If token is refreshing and successRedirect not set, it reloads the current route
await supabaseStrategy.checkSession(request, {
  failureRedirect: '/login'
});
Redirect if authenticated
// If the user is authenticated, redirect to /private
await supabaseStrategy.checkSession(request, {
  successRedirect: '/private'
});
Get session or null : decide what to do
// Get the session or null, and do different things in your loader/action based on
// the result
const session = await supabaseStrategy.checkSession(request);
if (session) {
  // Here the user is authenticated
} else {
  // Here the user is not authenticated
}

Tips

Prevent infinite loop 😱

// app/routes/login.ts
export const loader: LoaderFunction = async ({ request }) => {
  // Beware, never set failureRedirect equals to the current route
  const session = supabaseStrategy.checkSession(request, {
    successRedirect: '/private',
    failureRedirect: '/login' // ❌ DONT'T : infinite loop
  });

  // In this example, session is always null otherwise it would have been redirected
};

Redirect to

Example

With Remix.run it's easy to add super UX

// app/routes/private.profile.ts
export const loader: LoaderFunction = async ({ request }) =>
  // If checkSession fails, redirect to login and go back here when authenticated
  supabaseStrategy.checkSession(request, {
    failureRedirect: '/login?redirectTo=/private/profile'
  });
// app/routes/private.ts
export const loader: LoaderFunction = async ({ request }) =>
  // If checkSession fails, redirect to login and go back here when authenticated
  supabaseStrategy.checkSession(request, {
    failureRedirect: '/login'
  });
// app/routes/login.ts
export const loader = async ({ request }) => {
  const redirectTo = new URL(request.url).searchParams.get('redirectTo') ?? '/profile';

  return supabaseStrategy.checkSession(request, {
    successRedirect: redirectTo
  });
};

export const action: ActionFunction = async ({ request }) => {
  // Always clone request when access formData() in action/loader with authenticator
  // πŸ’‘ request.formData() can't be called twice
  const data = await request.clone().formData();
  // If authenticate success, redirectTo what found in searchParams
  // Or where you want
  const redirectTo = data.get('redirectTo') ?? '/profile';

  return authenticator.authenticate('sb', request, {
    successRedirect: redirectTo,
    failureRedirect: '/login'
  });
};

export default function LoginPage() {
  const [searchParams] = useSearchParams();

  return (
    <Form method="post">
      <input name="redirectTo" value={searchParams.get('redirectTo') ?? undefined} hidden readOnly />
      <input type="email" name="email" />
      <input type="password" name="password" />
      <button>Sign In</button>
    </Form>
  );
}