Authenticate Users with GitHub OAuth using Supabase and Next.js Client Components

Share this video with your friends

Send Tweet

Supabase includes multiple authentication strategies. In this lesson, we create a Supabase client to trigger the OAuth authentication flow with GitHub.

Additionally, we discuss the differences between Client and Server Components in the Next.js App Router:

  • Client Components: user interactivity
  • Server Components: data fetching

Lastly, we create a Route Handler to exchange an authentication code from GitHub for their Supabase session.

Code Snippets

Authenticate with GitHub OAuth

await supabase.auth.signInWithOAuth({
  provider: "github",
  options: {
    redirectTo: "http://localhost:3000/auth/callback",
  },
});

Exchange code for Supabase session

await supabase.auth.exchangeCodeForSession(code);

Resources

Armando
Armando
~ a year ago

The moment I set the variable

const supabase = createClientComponentClient();

I receive an error

"Unhandled Runtime Error TypeError: webpack_require.n is not a function. (In 'webpack_require.n(cross_fetch__WEBPACK_IMPORTED_MODULE_0__)', 'webpack_require.n' is undefined)"

I tried everything and I have no clue how to move on from this error.

Armando
Armando
~ a year ago

correction. The error above is happening when creating the auth-button

"use client";

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

export default function AuthButton() {
  const supabase = createClientComponentClient();

  const handleSignOut = async () => {
    await supabase.auth.signOut();
  };

  const handleSignIn = async () => {
    await supabase.auth.signInWithOAuth({
      provider: "github",
      options: {
        redirectTo: "http://localhost:3000/auth/callback",
      },
    });
  };

  return (
    <>
      <button onClick={handleSignIn}>Login</button>
      <button onClick={handleSignOut}>Logout</button>
    </>
  );
}
Armando
Armando
~ a year ago

For those having issues with this, upgrading @supabase/auth-helpers-nextjs to version 0.7.3 fixed the issue.

~ a year ago

any idea why this could be happening?

Unhandled Runtime Error Error: Hydration failed because the initial UI does not match what was rendered on the server.

Warning: Expected server HTML to contain a matching <pre> in <body>.

See more info here: https://nextjs.org/docs/messages/react-hydration-error

Component Stack pre

Oussama
Oussama
~ 9 months ago

The error with "the initial UI does not match what was rendered on the server" happened to me too, as I had a chrome extension that beautifies JSON whenever the returned page body contains only JSON. To solve it add a div as a wrapper and the error should be gone, or disable the chrome extension ^^