Skip to content

Instantly share code, notes, and snippets.

Created Sep 6, 2021
What would you like to do?
Auth0 Action - Account linking
* 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) => {
const axios = require("axios");
const ManagementClient = require("auth0").ManagementClient;
const { CLIENT_ID, CLIENT_SECRET } = event.secrets;
// Get the Management API v2 token
const {
data: { access_token },
} = await axios
grant_type: "client_credentials",
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
audience: "https://DOMAIN/api/v2/",
headers: { "content-type": "application/json" },
.catch((error) => {
// Create an instance of the Management API client
const management = new ManagementClient({
token: access_token,
domain: "DOMAIN",
// Check if there already is an account with this email address
const users = await management.getUsersByEmail(;
console.log('Users count:', users.length);
// If there isn't any account with this email address, return and let user continue
// There should never be more than 2 accounts with the same address, but just in case this happens somehow,
// we return here, so that a new account will be created for this user (better than to crash with error)
if (users.length !== 2) {
// Link user accounts
const linkedUserIdentities = await[1].user_id, {
user_id: users[0].user_id,
provider: users[0].identities[0].provider,
// Leave custom claim to let FE know
api.idToken.setCustomClaim("https://DOMAIN/account_linking_data", {
primary_user_id: users[1].user_id,
secondary_user_id: users[0].user_id,
// Return the linked account instead so user can continue without re-authentication
event.user = {
identities: linkedUserIdentities
return {
user: {
identities: linkedUserIdentities
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment