How to Login Post Redirect

I have my paywall in production (with a custom domain not using localhost) that uses a login redirect to go through but i don’t know how to properly continue the login flow and log the user in after calling the continue state

i get redirected right now to a /continue route after the redirection to /continue that isn’t an error page but there is a network error and i get redirected to an empty page of my site with the footer at the bottom

here is how my user is redirected to the /continue route and the continue action

checkout.tsx:

import React from 'react';
import { useAuth0 } from '@auth0/auth0-react';
import Stripe from 'stripe';
import queryString from 'query-string';
import jwt, { JwtPayload } from 'jsonwebtoken'; // Import the JWT library

const stripe = new Stripe('rk_test_51NOmOvHwLkK28gsPFWpd2flfcAWf9f2yvMTpB7D3m2s0rAFc21CIEPwtRS9Uz0NqfieZ5MY7xcAYgCuNCIzbzrYE004d5XPiyV', {
  apiVersion: '2022-11-15',
});

const Checkout = () => {
  const sessionToken = ***********************
  const { user } = useAuth0();
  //const [customerId, setCustomerId] = useState(null);


  //const customerId = user?.app_metadata?.stripe_customer_id;
  //console.log(customerId)
  const priceId = '**********'
  const successUrl = 'https://www.**************.com/continue'
  const cancelUrl = 'https://www.*****************.com/about'


  async function createCheckoutSession() {
    // Parse the URL to get state and redirect_uri
    const parsedUrl = queryString.parse(window.location.search);
    const sessionToken = parsedUrl.session_token;
    const customerId = parsedUrl.customerId;
    const redirectUri = parsedUrl.redirect_uri;
    // Check if the state and redirectUri exist
    if (sessionToken && redirectUri) {
      // Create the checkout session with state in the success_url
      
      const session = await stripe.checkout.sessions.create({
        customer: user?.app_metadata?.stripe_customer_id,
        payment_method_types: ['card'],
        line_items: [{ price: priceId, quantity: 1 }],
        mode: 'subscription',
        success_url: `${redirectUri}?session_token=${sessionToken}`,
        cancel_url: cancelUrl,
      });
      
      if (session.url) {
        window.location.href = session.url; // Redirect to Stripe checkout page
      }
    };
  }

  return (
    <div>
      <br></br><br></br><br></br>
      {/* Render your component's content */}
      <button onClick={createCheckoutSession}>Checkout for our ECOmium Plan!</button>
    </div>
  );
};

export default Checkout;

REDIRECT ACTION (don’t know if what I have is accurate for the continue):

/**
* Handler that will be called during the execution of a PostLogin flow.
*
* @param {Event} event - Details about the user and the context in which they are logging in.
* @param {PostLoginAPI} api - Interface whose methods can be used to change the behavior of the login.
*/
exports.onExecutePostLogin = async (event, api) => {
  try {
    // Your existing logic for creating a Stripe customer

    const sessionToken = api.redirect.encodeToken({
      secret: event.secrets.NEW_STATE,
      payload: {
        customerId: event.user.app_metadata.stripe_customer_id,
      },
    });
    console.log(sessionToken)

    // Redirect the user to the Stripe checkout page with session_token query parameter
    api.redirect.sendUserTo('https://www.***************.com/checkout', { 
      query: 
      { 
        session_token: sessionToken, 
        redirect_uri: `https://www.****************.com/continue`,

      },

    });
  } catch (error) {
    console.error(error.message);

    api.access.deny(
      "We could not create your account, problem with stripe redirection.\n" +
        "Please contact support for assistance."
    );
  }
};

exports.onContinuePostLogin = async (event, api) => {
  try {

    // Access the session_token query parameter from the URL
    const payload = api.redirect.validateToken({
      secret: event.secrets.NEW_STATE,
      tokenParameterName: "session_token",
    });

    
    // Check if the payload is valid
    if (payload) {
      // Log the payload for debugging
      console.log('Valid payload:', payload);

      // Log in the user using Auth0 action
      await api.auth.loginWithCredentials({
        username: event.user.email,
      });
    
      // Redirect the user to the desired page after successful login
    } else {
      console.error('Invalid session token');
      api.access.deny(
        "We could not log you in due to an invalid session token.\n" +
        "Please contact support for assistance."
      );
    }
  
    
  } catch (error) {
    console.error(error.message);

    api.access.deny(
      "We could not log you in, problem with coming back to app from Stripe.\n" +
        "Please contact support for assistance."
    );
  }
};

error:


main-a4f8b28ae051f6df.js:1 TypeError: Cannot read properties of null (reading 'content')
    at r (main-a4f8b28ae051f6df.js:1:4685)
    at main-a4f8b28ae051f6df.js:1:4551
    at Array.forEach (<anonymous>)
    at Object.updateHead (main-a4f8b28ae051f6df.js:1:4539)
    at Object.n [as _pendingUpdate] (main-a4f8b28ae051f6df.js:1:86661)
    at main-a4f8b28ae051f6df.js:1:86933
    at uI (framework-7a7e500878b44665.js:9:84075)
    at oU (framework-7a7e500878b44665.js:9:113138)
    at o (framework-7a7e500878b44665.js:9:107691)
    at x (framework-7a7e500878b44665.js:33:1364)

main-a4f8b28ae051f6df.js:1 A client-side exception has occurred, see here for more info: https://nextjs.org/docs/messages/client-side-exception-occurred

Hi @secomm,

When the user logs in to your application by providing their credentials and you have a redirect action, they will be sent to the redirect URL before the login flow completes. Then when you send the user back to the /continue endpoint with the state appended to the request, the user will resume the authentication flow and finish the login process to your application.

For example: https://{yourAuth0Domain}/continue?state=THE_ORIGINAL_STATE

Looking at your code snippet, I see that you are sending them to the https://www.***************.com/checkout URL. So far so good.

Then in your onContinuePostLogin function, you seem to be calling an invalid method with await api.auth.loginWithCredentials. Firstly, this method does not exist as a callable method in the Actions Triggers: post-login - API Object. Secondly, you do not need to explicitly call any method to log the user in. As long as you complete the redirect by sending the user to the /continue?state=THE_ORIGINAL_STATE endpoint, your user should complete the login flow accordingly.

I hope the explanation was clear!

Please let me know if you have any additional questions.

Thanks,
Rueben

1 Like

hi @rueben.tiow!
hope youre doing well

ive also tried that before and just done this
(all code commented out)

or even removed it

exports.onContinuePostLogin = async (event, api) => {
/*
  try {

    let decodedToken;

    decodedToken = api.redirect.validateToken({
      secret: event.secrets.NEW_STATE,
      tokenParameterName: 'session_token',
    });

  } catch (error) {

  // console.log(error.message);

    return api.access.deny('Error occurred during redirect.');

  }
  */

}; 

but i still face the same error and I’m not redirected back to the home page or logged in

why is that - im redirecting back with the correct state too?

Hi @secomm,

Thank you for the response.

Just to clarify, after commenting out/removing the code block, are you still experiencing the TypeError: Cannot read properties of null (reading 'content') error?

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.