Automatically assigning roles on sign up event with serverless function

Hi, I’m trying to assign roles for users who have signed up to our site via Netlify Identity with the use of serverless functions. I’ve followed the guide here. It’s a bit hard to follow and I’m still a beginner in JS, but I’ve basically used the same code from the blog:

 exports.handler = function(event, context, callback) {
  const data = JSON.parse(event.body);
  const { user } = data;
    
  const responseBody = {
    app_metadata: {
      roles: ["authorized"]
    },
    user_metadata: {
      ...user.user_metadata, // append current user metadata
    }
  };
  callback(null, {
    statusCode: 200,
    body: JSON.stringify(responseBody)
  });
};

When I build the site, I can see functions are being built, assuming everything is going as expected. But after inviting myself and signing up, my account has no roles, and I was expecting it to be “Authorized”.

I’d love to learn more on setting this up, with future plans on automating it based off user’s email addresses as well. I’d appreciate any guidance on this issue!

Welcome to the forums @NikShafiq

Reading the article you shared, there is perhaps a slight discrepancy with some information. It mentions creating a serverless function handle-signup however as per Trigger functions on Identity events the sign-up triggered function is identity-signup.

Using the code from the article in a function identity-signup.js was successful in adding the role automatically to the user on sign-up.

You can see the bare-basic repository I created here
https://github.com/coelmay/netlify-signup-test

1 Like

Thanks @coelmay, that seems to fix the issue.

After changing the function name, it was still not assigning roles from a sign up. But doing a quick clear cache and deploy fixed that up! :grin:

2 Likes