Persist Metadata in Auth0 Actions After Lazy Migration
During lazy migration, when import mode is active for a custom database, metadata passed in the "Login" and "Get User" actions intermittently fail to populate in the user profile. To resolve this issue, implement a post-login action that verifies the metadata is available and performs a one-time update if it is missing.
- Custom Database
- Lazy Migration
- Import Mode
To ensure metadata is always migrated from the custom database script, implement a post-login action that validates metadata availability and performs a one-time update if it is missing, using the provided sample code as a starting point.
const axios = require('axios');
exports.onExecutePostLogin = async (event, api) => {
// 1. Check if the LEGACY_METADATA is already present
// If it exists, exit early.
if (event.user.app_metadata && event.user.app_metadata.LEGACY_METADATA) {
return;
}
// 2. If missing, fetch the data from the legacy system
try {
// NOTE: Replace this URL with the actual endpoint used to query your legacy database.
// It's highly recommended to store API keys/tokens in Auth0 Action Secrets.
const response = await axios.get('https://your-api.com/legacy-users', {
params: {
email: event.user.email
},
headers: {
'Authorization': `Bearer ${event.secrets.LEGACY_API_SECRET}`
}
});
// Extract the information from your API's response payload
const LEGACY_INFO = response.data.sub; // Adjust based on the actual API response
// 3. Set the missing metadata on the Auth0 profile
if (LEGACY_INFO) {
api.user.setAppMetadata('LEGACY_METADATA', LEGACY_INFO);
}
} catch (error) {
console.error('Failed to fetch LEGACY_INFO from legacy system:', error.message);
// Optional: Deny the login if this metadata is strictly required for your apps to function
// api.access.deny('Critical metadata missing. Please contact support.');
}
};
After setting the metadata, the metadata becomes available in the event.user object during the next action. For the sample Action code provided, Auth0 stores the metadata at event.user.app_metadata.LEGACY_METADATA.