Open pdomala opened 1 month ago
Adding my sample repo with Supabase where the error can be re-produced. https://github.com/pdomala/nextjs14-supabase-sample
I've got the same issue with linkedin provider. my code worked for a while , then stopped working..
@pdomala ok i figured out, you have to have a auth/callback/route to handle the code
thingy
await supabase.auth.exchangeCodeForSession(code);
@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!
Struggling with this too followed the docs to no avail
I got the same issue...
Having the same issue. I set up everything according to the docs. The user is signed in successfully upon first sign up but once they log out they are unable to log back in. The error code is 403: invalid claim: missing sub claim.
Same here
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
Kinda worried about using this in production now ..
On Tue, 16 Apr 2024, 2:02 am Daniel, @.***> wrote:
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 @./auth-js/dist/module/lib/fetch.js:62:11) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async _handleRequest @./auth-js/dist/module/lib/fetch.js:116:9) at async _request @./auth-js/dist/module/lib/fetch.js:92:18) at async eval @./auth-js/dist/module/GoTrueClient.js:1064:24) at async SupabaseAuthClient._useSession @./auth-js/dist/module/GoTrueClient.js:949:20) at async SupabaseAuthClient._getUser @./auth-js/dist/module/GoTrueClient.js:1058:20) at async eval @./auth-js/dist/module/GoTrueClient.js:1041:20) at async eval @./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 @.***/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
— Reply to this email directly, view it on GitHub https://github.com/supabase/supabase-js/issues/992#issuecomment-2057507689, or unsubscribe https://github.com/notifications/unsubscribe-auth/ACFZKU3K5VCTPYTMUA6D6P3Y5QI33AVCNFSM6AAAAABFG25D7CVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDANJXGUYDONRYHE . You are receiving this because you are subscribed to this thread.Message ID: @.***>
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.
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
middleware.ts
file is in root (/src or your equv)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 other things I did along the way which I'm not sure contributed to me getting it working but adding here for completeness
next dev --turbo
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
I may be wrong but I don't think you're supposed to use NEXT_PUBLIC_XXX env vars on the server side!
Oh, they just env variable no? they should just work. I use them other places in the code and they work fine for their function
Yeah but the next public prefix means it's for client side use! To be safe I believe we shouldn't use that on the server you can create the same vars but without that prefix.
On Tue, 16 Apr 2024, 2:26 am Daniel, @.***> wrote:
Oh, they just env variable no? they should just work. I use them other places in the code and they work fine for their function
— Reply to this email directly, view it on GitHub https://github.com/supabase/supabase-js/issues/992#issuecomment-2057548232, or unsubscribe https://github.com/notifications/unsubscribe-auth/ACFZKU6Y6PXDV47SEXMMKVLY5QLUBAVCNFSM6AAAAABFG25D7CVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDANJXGU2DQMRTGI . You are receiving this because you are subscribed to this thread.Message ID: @.***>
Ah right, i'll do some refactoring and give that a go.. So just to confirm you have google OAuth working currently correct?
Yep! Working with the above code
On Tue, 16 Apr 2024, 2:29 am Daniel, @.***> wrote:
Ah right, i'll do some refactoring and give that a go.. So just to confirm you have google OAuth working currently correct?
— Reply to this email directly, view it on GitHub https://github.com/supabase/supabase-js/issues/992#issuecomment-2057553975, or unsubscribe https://github.com/notifications/unsubscribe-auth/ACFZKU2KLGURZ6XHNFHHQO3Y5QMBTAVCNFSM6AAAAABFG25D7CVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDANJXGU2TGOJXGU . You are receiving this because you are subscribed to this thread.Message ID: @.***>
Hmm my issue isnt that the authentication and account creation doesnt work, That works fine. The issue i am getting is that, after the code has been extract and an exchange token is set. I cant seem to get a user when I try to query the auth.getUser(). If that makes sense
Like i can see the user data after the account creation in the db, but when i try querying i dont get anything back. And its not a rls issue ive checked
Facing the same error, but it only happens if I call supabase.auth.getUser() in an API route handler. If called in a server component, no errors.
Facing the same error, but it only happens if I call supabase.auth.getUser() in an API route handler. If called in a server component, no errors.
same here!
Facing the same error, but it only happens if I call supabase.auth.getUser() in an API route handler. If called in a server component, no errors.
Yeah i got around fixing this by making a supavase client that uses supabase url and supabase secret Key. Not anon key, this allows you to use the client in api route
It actually works fine. I guess you're all mixing up the server and client side supabase clients at some point.
The two resources that you need are these (combine these snippets):
If you want to make it work on the server side, most everything touching supabase should be server client.
A few more tips on the side:
config.toml
, locally)I have the same Issue with NUXT 3
This is happening for me as well when calling a request to a route handler from a server component.
Bug report
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 errorAuthApiError: invalid claim: missing sub claim
To Reproduce
System information
@supabase/supabase-js": "^2.39.8
14.1.3
v20.10.0