Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: deprecate withApiAuth, withPageAuth, and withMiddlewareAuth. #364

Merged
merged 9 commits into from
Nov 4, 2022

Conversation

thorwebdev
Copy link
Member

@thorwebdev thorwebdev commented Nov 3, 2022

To make these helpers more flexible as well as more maintainable and easier to upgrade for new versions of Next.js, we're stripping them down to the most useful part which is managing the cookies and giving you an authenticated supabase-js client in any environment (client, server, middleware/edge).

Therefore we're marking the withApiAuth, withPageAuth, and withMiddlewareAuth higher order functions as deprectaed and they will be removed in the next minor release (v0.6.X).

Please follow the steps below to update your API routes, pages, and middleware handlers. Thanks!

withApiAuth deprecated!

Use createServerSupabaseClient within your NextApiHandler:

Before

// pages/api/protected-route.ts
import { withApiAuth } from '@supabase/auth-helpers-nextjs';

export default withApiAuth(async function ProtectedRoute(req, res, supabase) {
  // Run queries with RLS on the server
  const { data } = await supabase.from('test').select('*');
  res.json(data);
});

After

// pages/api/protected-route.ts
import { NextApiHandler } from 'next';
import { createServerSupabaseClient } from '@supabase/auth-helpers-nextjs';

const ProtectedRoute: NextApiHandler = async (req, res) => {
  // Create authenticated Supabase Client
  const supabase = createServerSupabaseClient({ req, res });
  // Check if we have a session
  const {
    data: { session }
  } = await supabase.auth.getSession();

  if (!session)
    return res.status(401).json({
      error: 'not_authenticated',
      description:
        'The user does not have an active session or is not authenticated'
    });

  // Run queries with RLS on the server
  const { data } = await supabase.from('test').select('*');
  res.json(data);
};

export default ProtectedRoute;

withPageAuth deprecated!

Use createServerSupabaseClient within getServerSideProps:

Before

// pages/profile.js
import { withPageAuth, User } from '@supabase/auth-helpers-nextjs';

export default function Profile({ user }: { user: User }) {
  return <pre>{JSON.stringify(user, null, 2)}</pre>;
}

export const getServerSideProps = withPageAuth({ redirectTo: '/' });

After

// pages/profile.js
import {
  createServerSupabaseClient,
  User
} from '@supabase/auth-helpers-nextjs';
import { GetServerSidePropsContext } from 'next';

export default function Profile({ user }: { user: User }) {
  return <pre>{JSON.stringify(user, null, 2)}</pre>;
}

export const getServerSideProps = async (ctx: GetServerSidePropsContext) => {
  // Create authenticated Supabase Client
  const supabase = createServerSupabaseClient(ctx);
  // Check if we have a session
  const {
    data: { session }
  } = await supabase.auth.getSession();

  if (!session)
    return {
      redirect: {
        destination: '/',
        permanent: false
      }
    };

  return {
    props: {
      initialSession: session,
      user: session.user
    }
  };
};

withMiddlewareAuth deprecated!

Before

import { withMiddlewareAuth } from '@supabase/auth-helpers-nextjs';

export const middleware = withMiddlewareAuth({
  redirectTo: '/',
  authGuard: {
    isPermitted: async (user) => {
      return user.email?.endsWith('@gmail.com') ?? false;
    },
    redirectTo: '/insufficient-permissions'
  }
});

export const config = {
  matcher: '/middleware-protected'
};

After

import { createMiddlewareSupabaseClient } from '@supabase/auth-helpers-nextjs';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export async function middleware(req: NextRequest) {
  // We need to create a response and hand it to the supabase client to be able to modify the response headers.
  const res = NextResponse.next();
  // Create authenticated Supabase Client.
  const supabase = createMiddlewareSupabaseClient({ req, res });
  // Check if we have a session
  const {
    data: { session }
  } = await supabase.auth.getSession();

  // Check auth condition
  if (session?.user.email?.endsWith('@gmail.com')) {
    // Authentication successful, forward request to protected route.
    return res;
  }

  // Auth condition not met, redirect to home page.
  const redirectUrl = req.nextUrl.clone();
  redirectUrl.pathname = '/';
  redirectUrl.searchParams.set(`redirectedFrom`, req.nextUrl.pathname);
  return NextResponse.redirect(redirectUrl);
}

export const config = {
  matcher: '/middleware-protected'
};

@thorwebdev thorwebdev changed the base branch from next to main November 3, 2022 15:22
@thorwebdev thorwebdev changed the title chore: strip down nextjs chore: deprecate withApiAuth, withPageAuth, and withMiddlewareAuth. Nov 3, 2022
Copy link
Contributor

@silentworks silentworks left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@dijonmusters
Copy link
Contributor

Awesome work Thor! These new functions look amazing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
3 participants