InvalidCheck: pkceCodeVerifier value could not be parsed. Read more at https://errors.authjs.dev#invalidcheck

Ready to post? :mag: First, try searching for your answer.
I’m getting an error pkceCodeVerifier value could not be parsed issue when a user accept invitation else for normal signin or signup it’s working fine.
I have created a regular app in Auth0 also set all the required URL.
Application Login URI : {myapplication base url}/api/authorize
Allowed Callback URLs: {myapplication base url}/apj/auth/callback/auth0
Allowed Logout URLs: {myapplication base url}
Allowed Web Origins: {myapplication base url}

Below is the code for the NextAuth configuration file and provider configuration for Auth0.

const authConfig = {
  debug: true, // Enabled because we are in development
  providers: [
    Auth0Provider({
      clientId: process.env.AUTH0_CLIENT_ID,
      clientSecret: process.env.AUTH0_CLIENT_SECRET,
      issuer: process.env.AUTH0_ISSUER,
      authorization: {
        params: {
          prompt: "login",
        },
      },
    }),
  ],
  adapter: DrizzleAdapter(db, {
    usersTable: users,
    accountsTable: accounts,
    sessionsTable: sessions,
    verificationTokensTable: verificationTokens,
  }),
  callbacks: {
    async signIn({ user, account, profile }: ISigninAuth0) {
      const updates: IUpdateUser = {};

      if (profile?.email_verified && !user?.emailVerified) {
        updates.emailVerified = new Date();
      }

      if (Object.keys(updates).length > 0) {
        await updateUserByEmail(user.email!, updates);
      }
      return true;
    },
    session: async ({ session, user }) => {
      const userData = await getUser(user.id);
      if (!userData) {
        throw new Error("User data not found");
      }
      return {
        ...session,
        user: {
          id: user.id,
          ...{
            name: userData.name,
            email: userData.email,
            emailVerified: userData.emailVerified,
          }
        },
      };
    },
  },
  trustHost: true,
} satisfies NextAuthConfig;


const { auth: uncachedAuth, handlers, signIn, signOut } = NextAuth(authConfig);

const auth = cache(uncachedAuth);

export { auth, handlers, signIn, signOut };

Organization admin invites user to join the organization by using Auth0 management API.

POST  /api/v2/organizations/{id}/invitations
Body: {
  "inviter": {
    "name": "string"
  },
  "invitee": {
    "email": "user@example.com"
  },
  "client_id": "string",
  "user_metadata": {},
  "ttl_sec": 0,
  "roles": [
    "string"
  ],
  "send_invitation_email": true
}

The user receives an email with a link to join the organization. The user clicks on the link (link looks like {myapplication base url}/api/authorize?invitation={invitation_id}&organization={organization_id}) and is redirected to our website.
There i extract the invitation_id and organization_id from the query params and generate a new invitation link with the following code:

const baseUrl = `myauth0domain/authorize`;
const url = new URL(baseUrl);
url.searchParams.append("response_type", "code");
url.searchParams.append("client_id", clientId);
url.searchParams.append("redirect_uri", redirectUri);
url.searchParams.append("invitation", invitation);
url.searchParams.append("organization", organizationId);
url.searchParams.append("scope", "openid profile email");
const finalUrl = url.toString();
return NextResponse.redirect(new URL(finalUrl as string, baseURL));

Then user is redirected to the Auth0 login page and after successful login, the user is redirected to the our website with the code in the query params. There i got an error “pkceCodeVerifier can not be parsed” and the user is not logged in." I have checked the logs in Auth0 all logs are fine. I using the regular app of auth0 in this that flow is handled by Auth0 itself.

I have also passed the code challenge, code challenge method and state in the URL but still getting the same error. Below is the code for the same:

// code verifier
function base64URLEncode(str: any) {
  return str.toString('base64')
      .replace(/\+/g, '-')
      .replace(/\//g, '_')
      .replace(/=/g, '');
}
const verifier = base64URLEncode(crypto.randomBytes(32));


//  code challenge
function sha256(buffer) {
  return crypto.createHash('sha256').update(buffer).digest();
}
const  challenge = base64URLEncode(sha256(verifier));
url.searchParams.append('code_challenge', challenge);
url.searchParams.append('code_challenge_method', 'S256');
url.searchParams.append('state', state);

I have also tried to set the cookie options in the NextAuth configuration file but still getting the same error. Below is the code for the same:

cookies: {
  pkceCodeVerifier: {
    name: "authjs.pkce.code_verifier",
    options: {
      httpOnly: true,
      sameSite: "none",
      path: "/",
      secure: true,  // Set to true in production
    },
  },
},

I have also added the code verifier in the cookies below is the code

const baseUrl = `myauth0domain/authorize`;
const url = new URL(baseUrl);
url.searchParams.append("response_type", "code");
url.searchParams.append("client_id", clientId);
url.searchParams.append("redirect_uri", redirectUri);
url.searchParams.append("invitation", invitation);
url.searchParams.append("organization", organizationId);
url.searchParams.append("scope", "openid profile email");
const finalUrl = url.toString();
const response = NextResponse.redirect(new URL(finalUrl as string, baseURL));
const cookieOptions = {
        httpOnly: true,
        secure: false,
        maxAge: 900, // 15 minutes
        path: '/',
      };

response.headers.set(
  'Set-Cookie',
  serialize('authjs.pkce.code_verifier', verifier, cookieOptions)
);
return response

Simple signUp/signIn Works fine but when I try to log in with the invitation link then i get the error. Can anyone help me with this issue?

Hi @anujchandel

Welcome to the Auth0 Community!

I am sorry about the delayed response to your post.

If you are still having issues, I would recommend to review the following posts:

You might not be modifying the base64 string correctly. I recommend using the following:

.replace('+', '-')
.replace('/', '-')
.replace('=', '')
.encode('utf-8')

If you are still having issues after reviewing the above posts or you found a solution of your own, please feel free to let me know by leaving a reply!

Kind Regards,
Nik