supabase-js: Nextjs14 with Supabase Auth - AuthApiError: invalid claim: missing sub claim

Bug report

  • I confirm this is a bug with Supabase, not with my own application.
  • I confirm I have searched the Docs, GitHub Discussions, and Discord.

Describe the bug

I am trying to setup Supabase authentication using Google Oauth provider. I am following the instructions details in the below link https://supabase.com/docs/guides/auth/server-side/nextjs

I created a login page with a button which calls supabase.auth.signInWithOAuth({ provider: 'google' }. I see the use being created in Supabase. But when I try to get the session using below code. I get the session as null and the console throws this error AuthApiError: invalid claim: missing sub claim

const supabase = createClient();
const { data: session, error } = await supabase.auth.getSession();
console.log(session);
console.log(error);
AuthApiError: invalid claim: missing sub claim
    at handleError (webpack-internal:///(rsc)/./node_modules/@supabase/gotrue-js/dist/module/lib/fetch.js:52:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async _handleRequest (webpack-internal:///(rsc)/./node_modules/@supabase/gotrue-js/dist/module/lib/fetch.js:89:9)
    at async _request (webpack-internal:///(rsc)/./node_modules/@supabase/gotrue-js/dist/module/lib/fetch.js:74:18)
    at async eval (webpack-internal:///(rsc)/./node_modules/@supabase/gotrue-js/dist/module/GoTrueClient.js:831:24)
    at async SupabaseAuthClient._useSession (webpack-internal:///(rsc)/./node_modules/@supabase/gotrue-js/dist/module/GoTrueClient.js:754:20)
    at async SupabaseAuthClient._getUser (webpack-internal:///(rsc)/./node_modules/@supabase/gotrue-js/dist/module/GoTrueClient.js:825:20)
    at async eval (webpack-internal:///(rsc)/./node_modules/@supabase/gotrue-js/dist/module/GoTrueClient.js:813:20)
    at async eval (webpack-internal:///(rsc)/./node_modules/@supabase/gotrue-js/dist/module/GoTrueClient.js:699:28) {
  __isAuthError: true,
  status: 401

To Reproduce

System information

  • OS: MacOS
  • Browser (if applies) Chrome
  • Version of supabase-js: @supabase/supabase-js": "^2.39.8
  • Next JS Version: 14.1.3
  • Version of Node.js: v20.10.0

About this issue

  • Original URL
  • State: open
  • Created 3 months ago
  • Reactions: 3
  • Comments: 25

Most upvoted comments

After 3 days of non-stop debugging I found this: https://github.com/ElectricCodeGuy/SupabaseAuthWithSSR which was a god send I refactored all the code based off this and mixed in some code from the official docs and it seems to be working now, some tips I’ve gathered along the way, and what I did

  • make sure middleware.ts file is in root (/src or your equv)
  • do not rename the middleware file it is a next.js thing
  • i was initially changing all the example code from the docs to .js but i now have all my ssr code in typescript (not sure if this made a difference but I did it to follow the docs and the example repo above so as not to make any of my own mistakes)
  • some forums online suggest you use persistSession: false when creating the SB client but i did not - the only time i did this was when i required using my service_role key when calling SB from a stripe webhook
  • edit: i didn’t manage to get this to work with google oauth on the server side, so in my code (below) it is still all client side, the reason i needed SSR in the first place was to call SB within my APIs / specifically for stripe webhooks

other things I did along the way which I’m not sure contributed to me getting it working but adding here for completeness

  • set up typescript in my project, https://nextjs.org/docs/pages/building-your-application/configuring/typescript
  • started using next dev --turbo
  • i removed a custom auth context wrapper i had to go back down to basics
  • edit: a lot of stuff i saw online also asks you to set your own cookies / local storage / call supabase’s setSession - in the end my code got very convoluted and i was confusing myself so I stripped all that out as well
  • edit: one thing that did help me was to put console.logs in the middleware and log the session every time the middleware function was hit so i could make sure it was working
  • edit: i used incognito and cleared my local storage/ session storage / cookies manually just to be sure when i was still messing around with them manually

here’s my code for reference:

auth/callback/route.ts

import { createSupabaseServerClient } from "util/supabase/server";
import { NextResponse } from "next/server";

export async function GET(request: Request) {
  const { searchParams, origin } = new URL(request.url);

  const code = searchParams.get("code");

  // if "next" is in param, use it in the redirect URL
  const next = searchParams.get("next") ?? "/";

  if (code) {
    const supabase = createSupabaseServerClient();

    const { error } = await supabase.auth.exchangeCodeForSession(code);

    if (!error) {
      return NextResponse.redirect(`${origin}${next}`);
    }
  }

  // TODO: Create this page
  // return the user to an error page with instructions
  return NextResponse.redirect(`${origin}/auth/auth-error`);
}

middleware.ts

import { NextResponse, type NextRequest } from "next/server";
import { createSupabaseReqResClient } from "./util/supabase/server";

export async function middleware(request: NextRequest) {
  let response = NextResponse.next({
    request: {
      headers: request.headers,
    },
  });

  const supabase = createSupabaseReqResClient(request, response);

  const {
    data: { user },
  } = await supabase.auth.getUser();

  // protects the "/account" route and its sub-routes
  // redirect user to homepage
  if (!user && request.nextUrl.pathname.startsWith("/account")) {
    return NextResponse.redirect(new URL("/", request.url));
  }

  // protects the "/purchase" route and its sub-routes
  // redirect user to sign-in
  if (!user && request.nextUrl.pathname.startsWith("/purchase")) {
    return NextResponse.redirect(new URL("/", "sign-in"));
  }

  return response;
}

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     * Feel free to modify this pattern to include more paths.
     */
    "/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
  ],
};

util/supabase/server.ts

import { type NextRequest, type NextResponse } from "next/server";
import { cookies } from "next/headers";
import { getCookie, setCookie } from "cookies-next";
import { createServerClient, type CookieOptions } from "@supabase/ssr";

// server component can only get cookies and not set them, hence the "component" check
export function createSupabaseServerClient(component: boolean = false) {
  return createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        get(name: string) {
          return cookies().get(name)?.value;
        },
        set(name: string, value: string, options: CookieOptions) {
          if (component) return;
          cookies().set(name, value, options);
        },
        remove(name: string, options: CookieOptions) {
          if (component) return;
          cookies().set(name, "", options);
        },
      },
    }
  );
}

export function createSupabaseServerComponentClient() {
  return createSupabaseServerClient(true);
}

export function createSupabaseReqResClient(
  req: NextRequest,
  res: NextResponse
) {
  return createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        get(name: string) {
          return getCookie(name, { req, res });
        },
        set(name: string, value: string, options: CookieOptions) {
          setCookie(name, value, { req, res, ...options });
        },
        remove(name: string, options: CookieOptions) {
          setCookie(name, "", { req, res, ...options });
        },
      },
    }
  );
}

util/supabase/client.ts

import { createBrowserClient } from "@supabase/ssr";

export function createSupabaseBrowserClient() {
  return createBrowserClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
  );
}

Google auth button component

"use client";

import React, { useState } from "react";
import Button from "components/Buttons/Button";
import LoadingIcon from "components/Loading/LoadingIcon";
import { useSearchParams } from "next/navigation";

import { createSupabaseBrowserClient } from "util/supabase/client";

function AuthGoogle(props) {
  const [pending, setPending] = useState(null);
  const searchParams = useSearchParams();
  const next = searchParams.get("next") ?? "/";
  const supabase = createSupabaseBrowserClient();

  const onSigninWithGoogle = async () => {
    await supabase.auth.signInWithOAuth({
      provider: "google",
      options: {
        redirectTo: `${location.origin}/auth/callback?next=${next}`,
      },
    });
  };

  return (
    <div className="flex flex-col justify-items-center">
      <Button
        variant="primary"
        size="lg"
        disabled={pending === provider}
        onClick={() => {
          onSigninWithGoogle();
        }}
        startIcon={
          pending !== provider && (
            <img
              src="https://uploads.divjoy.com/icon-google.svg"
              alt="Google"
              className="w-5 h-5"
            />
          )
        }>
        {pending === provider && <LoadingIcon className="w-6" />}

        {pending !== provider && <>Continue with Google</>}
      </Button>
    </div>
  );
}

export default AuthGoogle;

May also be worth noting that when I created a SB client for my service_role key, I did it this way

import { createClient } from "@supabase/supabase-js"; // Note: this does not use @supabase/ssr unlike functions in /util/supabase

const supabase = createClient(
  process.env.SUPABASE_URL,
  process.env.SUPABASE_SERVICE_ROLE_SECRET, // Note: this should never be exposed to the client!
  {
    auth: {
      // these options are outlined in the docs: https://supabase.com/docs/reference/javascript/admin-api
      autoRefreshToken: false,
      persistSession: false,
    },
    db: { schema: "public" },
  }
);

not using the @supabase/ssr package

P.S. Am just a junior dev so apologies in advance if any of this isn’t sound advice

Authentication seems to be broken atm. My linkedIn auth provider was broken yesterday, a fix was put out for that this morning. But google Auth provider is broken too. getting this error data: { user: null }, error: AuthApiError: invalid claim: missing sub claim at handleError (webpack-internal:///(rsc)/./node_modules/@supabase/auth-js/dist/module/lib/fetch.js:62:11) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async _handleRequest (webpack-internal:///(rsc)/./node_modules/@supabase/auth-js/dist/module/lib/fetch.js:116:9) at async _request (webpack-internal:///(rsc)/./node_modules/@supabase/auth-js/dist/module/lib/fetch.js:92:18) at async eval (webpack-internal:///(rsc)/./node_modules/@supabase/auth-js/dist/module/GoTrueClient.js:1064:24) at async SupabaseAuthClient._useSession (webpack-internal:///(rsc)/./node_modules/@supabase/auth-js/dist/module/GoTrueClient.js:949:20) at async SupabaseAuthClient._getUser (webpack-internal:///(rsc)/./node_modules/@supabase/auth-js/dist/module/GoTrueClient.js:1058:20) at async eval (webpack-internal:///(rsc)/./node_modules/@supabase/auth-js/dist/module/GoTrueClient.js:1041:20) at async eval (webpack-internal:///(rsc)/./node_modules/@supabase/auth-js/dist/module/GoTrueClient.js:897:28) { __isAuthError: true, status: 403, code: ‘bad_jwt’

my callback route looks like this ` import { cookies } from ‘next/headers’ import { NextResponse } from ‘next/server’ import { type CookieOptions, createServerClient } from ‘@supabase/ssr

export async function GET(request: Request) { const { searchParams, origin } = new URL(request.url) const code = searchParams.get(‘code’) // if “next” is in param, use it as the redirect URL const next = searchParams.get(‘next’) ?? ‘/’ console.log(‘code:’, code)

if (code) { const cookieStore = cookies() const supabase = createServerClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, { cookies: { get(name: string) { return cookieStore.get(name)?.value }, set(name: string, value: string, options: CookieOptions) { cookieStore.set({ name, value, …options }) }, remove(name: string, options: CookieOptions) { cookieStore.delete({ name, …options }) }, }, } ) const { error } = await supabase.auth.exchangeCodeForSession(code) if (!error) { return NextResponse.redirect(${origin}/dashboard) } console.log(error); }

// return the user to an error page with instructions return NextResponse.redirect(${origin}/auth/auth-code-error) } async function signInWithGoogle() { const supabase = supabaseBrowser(); const { error } = await supabase.auth.signInWithOAuth({ provider: ‘google’, options: { queryParams: { access_type: ‘offline’, prompt: ‘consent’, }, redirectTo: ${window.location.origin}/auth/callback, } }); if (error) { console.error(‘Error signing in:’, error); } } ` It sucessfully creates the user, but and logs in but when i try to fetch userId or session i run into the prescribed error

Yeah, its slowing down my development process. The linkedIn one wasnt supabase’s fault tbf, LinkedIn had release a breaking change without communicating it and that causes linkedIn auth to be broken. But the fix for that was merged this morning so it might take a while before that gets rolled out. But then my Google auth had also been broken.

@pdomala ok i figured out, you have to have a auth/callback/route to handle the code thingy

await supabase.auth.exchangeCodeForSession(code);

Can u send me sample code of your auth/callback/route.ts ?

Thank you!

@pdomala ok i figured out, you have to have a auth/callback/route to handle the code thingy

await supabase.auth.exchangeCodeForSession(code);

Adding my sample repo with Supabase where the error can be re-produced. https://github.com/pdomala/nextjs14-supabase-sample

  • Add env with Supabase URL and Anon key
  • npm run dev