-
-
Notifications
You must be signed in to change notification settings - Fork 239
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
invalid request: both auth code and code verifier should be non-empty #545
invalid request: both auth code and code verifier should be non-empty #545
Comments
I am also seeing this with using google oauth. Our initiation of the auth flow is on the client and I am seeing this error on the server, not sure if that is important. |
I ran into this error earlier and the issue was caused by not passing the response from the sign in process to the callback request and using it to create the client, as shown in the docs. So from:
To:
|
I am running into this with |
Seeing exactly the same thing (client-initiated Google PKCE failing on |
The issue in the code seems to be the use of two different clients. You are using the auth helpers along with the normal supabase client, this won't work and will result in the error you are getting. We have a branch of the auth-helpers with PKCE support that you should use until we make the final release. You can install this using: npm install @supabase/auth-helpers-sveltekit@next You shouldn't mix the auth-helpers client with a normal supabase-js client unless you are planning to do things with the |
Yes, this was exactly my issue. Using 0.2.0-next.3 I've now moved on to a new error: |
@KrisBraun do you have a repo somewhere that I can check out the code? I'm still thinking there is a mix going on with the supabase-js client libraries. |
@silentworks To avoid confusing the original issue here, I've created #549. The issue seems to be related to |
@silentworks I was mixing clients and what you suggested did fix it for me locally, but I'm still getting the error on Vercel unfortunately |
@probablykasper thats likely due to either incorrect version being installed on Vercel or your code is cached on there somehow. Try deploying the fixed version to a new Vercel setup and report back here if there are still errors. |
That was my suspicion as well, but no luck. The lockfile does use |
@probablykasper I'm going to make a big ask of you, but can you create a minimal reproducible example repo that I can take a look at please? |
I tried reproducing it with the new 0.10.0 version, and the issue wasn't there. I'll let you know once I figure out more! |
I played with this in the debugger and found a reliable repro. The blog post also confirms the following flow:
"Another client" cold mean an incognito window, another browser, another device, etc. E.g. someone initiated sign in from the browser on a desktop, then open the magic link from a mobile email app. Or initiated from the main browser app, but continued in a webview with a separate cookies store. If I understand correctly, the code verifier shouldn't leave the client (that's the whole point of PKCE). So the fix here would just be failing gracefully from Supabase/GoTrue, and let the project display a recovery path. Something shorter than
Workaround for now is to catch it (as it's not returned via Edit: Example with screenshots and code added here: #545 (comment) |
This comment was marked as off-topic.
This comment was marked as off-topic.
I am having this exact issue, but only when I run I am using the code example from the documentation without much changes so the error is appearing on the callback page. I thought that maybe I am missing the redirect URL configured in Supabase, but it's there. SvelteKit @ 1.20.2 |
Issue for me is with email confirmation flow not oauth. Works fine locally. Should point out, it seems to actually confirm the email but throws an error. This is happening on Vercel and it's kicking out:
For now, I have worked around this simply by suppressing the offending function. This obviously isn't an ideal situation though: try {
await supabase.auth.exchangeCodeForSession(code)
} catch (error) {} |
@silentworks, Is this mentioned anywhere in the docs? I spent pretty much all day today trying to get OAuth to work in SSR mode on a NextJS project with a refine.dev template and coming across this information earlier would have been incredibly helpful! Also, the naming is rather misleading - |
Updating the auth helpers made the error go away for me @silentworks |
I'm having the same error with |
Same issue. Not able to reproduce it locally. Also, on Vercel, only some users are experiencing it :/ Thanks @tholder, probably gonna use this fix as well for now… |
nb: I'm using App Router on NextJS 13.4.7 I did some digging this evening and found that my NextJS route handler is not receiving cookies when calling I confirmed this by changing the I noticed this because throughout my debugging, the cookie was in the client and was being seen by the middleware, yet the exception we're talking about was still thrown... The problem I have now is that only Route Handlers and Server Actions can return cookies to the client, so using a Server Component will not be possible. I'll share if I find a solution, but it seems this could be a NextJS issue rather than a Supabase issue? |
Did some more digging... in an older YouTube video on the Supabase channel, the presenter describes that there is a bug in NextJS with However, in a newer video, this seems to no longer be the case... I'm still experiencing empty cookies in NextJS 13.4.7, though :/ |
After much googling and trawling the Vercel's GitHub discussions/issues, I've not found a solution to this. In the end, I've taken a hacky approach in my middleware to handle the auth cookie, since cookies are available there for every request. I feel there is probably a way to do this with a ServerComponent and Server Actions, but I've already lost too much time to this issue and I want to get back to developing my project. This is what my middleware looked like now: import { createMiddlewareClient } from '@supabase/auth-helpers-nextjs'
import { NextResponse, NextRequest } from 'next/server'
import type { Database } from '@/supabase/database.types'
export async function middleware(req: NextRequest) {
const res = NextResponse.next()
const url = new URL(req.url)
const supabase = createMiddlewareClient<Database>({ req, res })
if (url.pathname === "/auth/callback") {
const code = url.searchParams.get('code')
if (code) {
await supabase.auth.exchangeCodeForSession(code)
}
} else {
await supabase.auth.getSession()
}
return res
} Needless to say, this is not idea. There are quite a few discussions/issues related to cookies in NextJS 13:
I couldn't find many that are exactly about cookies being missing: So I made my own report with an example to clearly describe this exact case: |
Hi @ky1ejs, For what it's worth, I'm also working with Next.js and I've did the following which works for me: //app/auth/callback/route.ts
import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs';
import { cookies } from 'next/headers';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import type { Database } from '@/types/database.types';
import { ROUTES } from '@/consts';
export async function GET(request: NextRequest) {
const requestUrl = new URL(request.url);
const code = requestUrl.searchParams.get('code');
if (code) {
const supabase = createRouteHandlerClient<Database>({ cookies });
await supabase.auth.exchangeCodeForSession(code);
}
// URL to redirect to after sign in process completes
return NextResponse.redirect(`${requestUrl.origin}${ROUTES.accountNew}`);
}
Hope this helps 🎉 |
This comment was marked as off-topic.
This comment was marked as off-topic.
OK, I solved it partly — it works if I send a signup email with However, what doesn't work, and what I need for my use case is sending a signup email via API route. So probably something is wrong with Can someone try sending a sign up email via API route with |
Also still struggling with this. Pretty bad UX in my app and can't seem to get around the code verifier being stored locally. |
I have the same issue on nextjs and supabase-auth-nextjs. I have a workaround where I use import { useEffect } from 'react';
import { createClientComponentClient } from '@supabase/supabase-js';
import { useRouter } from 'next/router';
export default function Home() {
const supabase = createClientComponentClient();
const router = useRouter();
useEffect(() => {
// Set up an authentication listener
const { data: { subscription } } = supabase.auth.onAuthStateChange(
async (event, session) => {
console.log(`Supabase auth event in home: ${event}`);
if (event === 'SIGNED_IN') {
// Redirect to the dashboard upon successful sign-in
router.push('/dashboard');
}
if (session !== null) {
// Redirect to the dashboard if a session is present
console.log('session is:', session);
router.push('/dashboard');
}
// Additional checks or redirects can be implemented
}
);
// Cleanup function: unsubscribe the auth listener when the component unmounts
return () => {
subscription.unsubscribe();
};
}, []);
return (
<div>
{/* Your home page content */}
</div>
);
} |
We have published a new guide on how to handle this from the email perspective and framework side of things. This requires an email template change and a new endpoint in your application https://supabase.com/docs/guides/auth/server-side/email-based-auth-with-pkce-flow-for-ssr If you are using the Supabase CLI and want to customize your email templates, you can do this now by following this guide https://supabase.com/docs/guides/cli/customizing-email-templates |
Awesome! So, should |
@edgarasben yes if you are doing any auth process that uses magic links (signUp, resetPasswordForEmail, inviteUserByEmail and signInWithOtp). If you plan on doing |
If I need both, and there is only one email template, will the /callback route be able to handle the updated email templates? |
@edgarasben but |
Closing this out as we now have a guide showing how to get around this issue: |
Looks like the problem still continues for signInWithOAuth in nextjs@13.4.19. @silentworks
client component const signInWithGithub = async () => {
await supabase.auth.signInWithOAuth({
provider: "github",
options: {
redirectTo: window.location.origin + "/auth/callback",
},
});
}; app/auth/callback/route.js import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
export const dynamic = "force-dynamic";
export async function GET(request) {
const requestUrl = new URL(request.url);
const code = requestUrl.searchParams.get("code");
if (code) {
const supabase = createRouteHandlerClient({ cookies });
await supabase.auth.exchangeCodeForSession(code);
}
return NextResponse.redirect(requestUrl.origin);
} |
Re-opening this issue as a number of users have reported it still happening. Can anyone still experiencing this please also state the browser they are using along with Next version and if its app router or pages directory? |
@silentworks I encounter the same error with The complete code for my import type { SupabaseClient } from '@supabase/supabase-js';
import { redirect } from '@sveltejs/kit';
export const GET = async ({
url,
locals: { supabase }
}: {
url: URL;
locals: { supabase: SupabaseClient };
}) => {
const code = url.searchParams.get('code');
if (code) {
await supabase.auth.exchangeCodeForSession(code);
}
throw redirect(303, '/');
}; The error message: |
For those using Remix (and likely other frameworks). One potential cause is that you're not forwarding the // app/routes/sign-up.tsx
import { createServerClient } from "@supabase/auth-helpers-remix";
export async function action({ request, context }) {
const response = new Response()
const supabase = createServerClient(
SUPABASE_URL,
SUPABASE_ANON_KEY,
{
request,
response,
cookieOptions: {
name: context.env.SUPABASE_COOKIE_NAME,
},
},
);
await supabase.auth.signUp({ ... }) // this updates the `response` headers
// or redirect(..., { headers: response.headers })
return json(..., { headers: response.headers })
} Double check in your dev tools that a cookie named something like |
This comment was marked as duplicate.
This comment was marked as duplicate.
Also still expecting this using SvelteKit and following the guide from the official docs 1:1 and then using
|
@z-x your issues is related to you using the IP address and your browser not being able to read the cookie. If anyone else is doing this you need to setup your cookieOptions correctly when using |
@vinch is this with magic links or OAuth? If magic links we have a guide on how to resolve this https://supabase.com/docs/guides/auth/server-side/email-based-auth-with-pkce-flow-for-ssr. @Alex-Yakubovsky this guide would also be the same for Remix too. |
I've tested this again in my setup using SvelteKit with OAuth and cannot replicate what folks are reporting here. It's best one of your provide a minimal reproducible example repository otherwise I won't be able to help much with this. My test OAuth projects are all here for the framework of your choice https://github.com/supabase-community/supabase-by-example/tree/main/oauth-flow Kapture.2023-09-14.at.19.59.22.mp4 |
i am also having same issue, with all latest version supabase js, auth helpers and same code |
I'm going to close this issue again until someone actually provides an reproducible example repo as I've showed in my recording and examples I've linked. This is working but folks keep on adding on here I have the same issue without any reproducible examples. |
Repro is easy, just do a |
@silentworks My reproduction (nuxt-modules/supabase#262 (comment)) using nuxtjs/supabase may be of interest. This reproduction is for a reset password flow. Particularly the SPA method exposes some extra detail. I suspect this particular network request is causing the error:
Could be a bug in nuxtjs/supabase, though. Not sure. Unfortunately for me this bug is blocking and means I will have to migrate to a different platform :( |
@silentworks I've cloned https://github.com/supabase-community/supabase-by-example/tree/main/reset-flow/nuxt I can reproduce the problem where I get the above result:
OS: Windows 11 |
@ErwinAI you will need to raise that with the Nuxt team as they manage the Nuxt Supabase integration. The solution is outlined here https://supabase.com/docs/guides/auth/server-side/email-based-auth-with-pkce-flow-for-ssr but unfortunately Nuxt works a bit different when it comes to the server compared to other SSR frameworks. Also note the issue is due to you requesting the reset in one browser/device and then clicking the link on another device, this is not permitted when using the |
@mennankara please read existing comments before adding new ones, I've added a link in previous comments on how to address this https://supabase.com/docs/guides/auth/server-side/email-based-auth-with-pkce-flow-for-ssr, if you aren't doing this then it won't work. |
Bug report
Describe the bug
When calling
auth.exchangeCodeForSession(code)
this error is thrown:To Reproduce
Login callback handler:
This is how I'm starting the login:
Expected behavior
error
property, not thrown.Screenshots
If applicable, add screenshots to help explain your problem.
System information
The text was updated successfully, but these errors were encountered: