Auth helpers and more in Supabase

Aug 21, 2022

Introduction

After lots of experiments with Prisma and next-auth, both of which I love ❤️. I have found relief in having something like Supabase power my backend. Even if I’m using a combined approach with a CMS and a backend, Supabase makes things so much easier. We will chat about that on another post.

Moving from Next Auth to Supabase

For now, I’ve been replacing all my prisma models as well as the authentication components to migrate everything to prisma, and found that some of the methods for authentication were missing from Supabase when compared to Next Auth js. Things like authenticated API endpoints, or accessing the session from the server side.


You can deal with all of this with the use of a very simple and helpful library called @supabase/auth-helpers-nextjs.

Redirecting unauthenticated users

Although the methods above are quite convenient, withPageAuth does not provide a redirection in the following flow.

  1. User accesses Settings (a protected page)
  2. Is the user authenticated?
    1. Yes: render Settings
    2. No: redirectTo: your login page


This flow is ideal, but a common practice is to keep the URL they where trying to access, so we can send them there immediately after redirection, how can we do that here?


import { withPageAuth } from "@supabase/auth-helpers-nextjs";

export const withCustomPageAuth = (ctx) => {
  const redirectTo = `/auth/signin?callbackUrl=${ctx.resolvedUrl}`;
  return withPageAuth({ redirectTo })(ctx);
};
/lib/auth/with-custom-page-auth.ts


//....
import { withCustomPageAuth } from "@lib/auth/with-custom-page-auth";
//...

export default Settings(props) => {
	/...
}

// simple statement
export const getServerSideProps = withCustomPageAuth;

// advanced statement
// if you want to edit the flow, you can do
export const getServerSideProps = (ctx) => {
	// do your stuff here.
	return withCustomPageAuth(ctx);
}
/pages/settings.tsx