Can't get post user login action to work

I’m trying to migrate from Hooks to Actions with no luck.

I have a hook that works great post user signup. All I need to do is send the user data to my API. It’s so simple!!! But for some reason it’s so hard for me in Actions.

I’m using a post login action since I need the client_id as well as the number of times a user has logged in so I can check to see if it’s the first time they log in and also if they’re in dev or prod environment.

Here is my code:

const axios = require(‘axios’);

exports.onExecutePostLogin = async (event, api) => {
const client_id = event.client.client_id;

const requestBody = {
email: event.user.email,
auth0SubId: event.user.user_id,
username: event.user.username
};

if (client_id === ‘CLIENTID_FIRST’ && event.stats.logins_count === 1) {
const prodEndpoint = ‘PROD_ENDPOINT_WORKS’;
console.log(‘Request sent to PROD endpoint:’, prodEndpoint);
await axios.request({
method: ‘post’,
url: prodEndpoint,
data: requestBody
}).catch(error => {
console.error(‘An error occurred during the API call:’, error);
throw error;
});
} else if (client_id === ‘CLIENTID_SECOND’ && event.stats.logins_count === 1) {
const devEndpoint = ‘DEV_ENDPOINT_WORKS’;
console.log(‘Request sent to DEV endpoint:’, devEndpoint);
await axios.request({
method: ‘post’,
url: devEndpoint,
data: requestBody
}).catch(error => {
console.error(‘An error occurred during the API call:’, error);
throw error;
});
}

return;
};

What happens when this runs:
*In dev environment I get this Failed Login error"description": “connect ECONNREFUSED 127.0.0.1:3001”
*In prod environment I get a similar Failed Login “AxiosError: Request failed with status code 500”
*I use these same endpoints in my hooks and they work great.
*I know I’m using the right client_ids since in the Auth0 logs I can see “Request sent to DEV endpoint:” and “Request sent to PROD endpoint:” that I put in this code for debugging. I can trigger both!
*The Request body that I’m sending to my endpoints looks good
*My DEV_ENDPOINT_WORKS and PROD_ENDPOINT_WORKS endpoints aren’t even being hit at all
*Always the same “Failed Login” error 500. ChatGPT tells me to check my server code but it doesn’t even get hit at all.

Any help would be greatly appreciated!!

ECONNREFUSED error means that connection could not be made…

I think connecting to 127.0.0.1:3001 is not valid URL form Auth0 action… You need to have custom domain or static IP… You can use CDN tunnel or temporary domain forexample by using ngrok…

Auth0 needs public available endpoint to perform fetch on it…

Thanks so much for your reply!

Might be relevant: I have a local dev environment that I can connect to no problem with auth0 hooks. I’m just trying to migrate. So all the endpoints work in both my dev and prod environments but only when I use auth0 hooks. I can’t get it to work with actions tho, even with the same endpoints :frowning:

:thinking: When you say you have a hook are you referring to Auth0 Hooks? Or react hooks in the Auth0 React SDK for Single Page Apps? It’s just that the former is server side technology - i.e. runs in the context of the Auth0 Tenant - and the latter is client side technology, i.e. runs in the context of the browser.

Making localhost calls in the context of the latter is perfectly reasonable - especially in a development environment. But making localhost calls in the context of the former is pretty much impossible - particularly if localhost is intended to refer to your local machine. As @damikun says, you would likely need to use some sort of tunnel or static IP address to do that. And in any case, 127.0.0.1 would almost certainly not be the IP address that would be used.

FYI, Auth0 Actions is intended as a replacement for Auth0 Hooks, not anything React related :slight_smile:

Hope this helps :sunglasses:

2 Likes

Hi Peter, thanks for your reply.

By hooks I mean Auth0 hooks in the Auth pipeline. The code is all on my auth0 tenant.

I do not mean react hooks.

Let’s assume the local dev enviroment issue is solved (I can get trhe endpoint to work well in dev env with hooks anyway). This doesn’t explain why the prod environment API endpoint is not hit when I’m in prod environment.

In my Auth0 hooks, I use the exact same production enpoint and it works great.

In hooks I noticed it could not accept a try / catch block, and instead I had to use .catch(). I was worried Actions might have similar limitation and that I was writing this code incorrectly.

Thank you to anyway who has been helping me with this.

:thinking: Looking over this code fragment that you shared previously, I think I can see the potential issue. You can either:

try {

  await axios.request({
    method: ‘post’,
    url: prodEndpoint,
    data: requestBody
  });
} catch (error)  {
  ...
}

or you can

axios.request({
  method: ‘post’,
  url: prodEndpoint,
  data: requestBody
})
.then(result => {
})
.catch(error => {
  console.error(‘An error occurred during the API call:’, error);
  throw error;
});

But what you have at the moment is essentially incorrect, and an error from an await perspective. This is probably why your API isn’t being called, as the axios request isn’t being executed.

Hope this helps :sunglasses:

1 Like

I think we’re closer! Thanks for pointing out errors that I made!

I updated the code to this:

const axios = require('axios');

exports.onExecutePostLogin = async (event, api) => {
  const client_id = event.client.client_id;
    const logins_count = event.stats?.logins_count;

  // Validate the event object and required properties
  if (!client_id || !logins_count) {
    console.error('Invalid event object or missing properties.');
    return;
  }

  const requestBody = {
    email: event.user?.email,
    auth0SubId: event.user?.user_id,
    username: event.user?.username
  };
  // console.log('requestBody:', requestBody);

  if (client_id === REDACTED && logins_count === 1) {
    const prodEndpoint = 'REDACTED';
    console.log('Request sent to PROD endpoint:', prodEndpoint);

    try {
      await axios.post(prodEndpoint, requestBody);
    } catch (error) {
      console.error('An error occurred during the API call:', error);
      throw error;
    }
  } else if (client_id === 'REDACTED' && logins_count === 1) {
    const devEndpoint = 'REDACTED';
    console.log('Request sent to DEV endpoint:', devEndpoint);

    try {
      await axios.post(devEndpoint, requestBody);
    } catch (error) {
      console.error('An error occurred during the API call:', error);
      throw error;
    }
  }
  return;
};

In the logs I still get this error though. Please note the logs section:

{
  "action_name": "testtt",
  "response": {
    "error": {
      "code": "ERR_BAD_RESPONSE",
      "message": "Request failed with status code 500",
      "name": "AxiosError",
      "stack": "AxiosError: Request failed with status code 500\n    at settle (/data/layers/layers-kZGp/kZGpkl7ckW1DFDsUsDMTaIcrTZdmqx52UzL2aRvFilE/node_modules/axios/dist/node/axios.cjs:1909:12)\n    at IncomingMessage.handleStreamEnd (/data/layers/layers-kZGp/kZGpkl7ckW1DFDsUsDMTaIcrTZdmqx52UzL2aRvFilE/node_modules/axios/dist/node/axios.cjs:2989:11)\n    at IncomingMessage.emit (node:events:539:35)\n    at IncomingMessage.emit (node:domain:537:15)\n    at endReadableNT (node:internal/streams/readable:1345:12)\n    at processTicksAndRejections (node:internal/process/task_queues:83:21)"
    },
    "logs": "Request sent to PROD endpoint: REDACTED\nAn error occurred during the API call: AxiosError: Request failed with status code 500\n    at settle (/data/layers/layers-kZGp/kZGpkl7ckW1DFDsUsDMTaIcrTZdmqx52UzL2aRvFilE/node",
    "stats": {
      "total_request_duration_ms": 126,
      "total_runtime_execution_duration_ms": 119,
      "runtime_processing_duration_ms": 2,
      "action_duration_ms": 117,
      "boot_duration_ms": 2,
      "network_duration_ms": 7
    }
  },
  "error": {
    "id": "invalid_argument",
    "msg": "Invalid Argument"
  },
  "started_at": "2023-06-17T17:46:58.685694477Z",
  "ended_at": "2023-06-17T17:46:58.812465136Z"
}

I am dumb. I made a silly error.

replace this:

auth0SubId: event.user?.user_id,

with

auth0SubId: event.user?.user_id.substring(6, event.user.user_id.length)

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