/* Codeboosh */

Automatically Set A User Role on Signup With Netlify Identity

Netlify Identity is a great simple way to add authentication to your static website. However, at the moment if you are using the Netlify Identity Widget you have to create a function in order to automatically give users in a role on signup.

Create A Function

Firstly, you need to add a function called something like handle-signup.js to the functions folder in your project, or wherever your Netlify functions live in your project.

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

You can even add some more custom metadata to the user if you want.

exports.handler = function(event, context, callback) {
    const data = JSON.parse(event.body);
    const { user } = data;
        
    const responseBody = {
        app_metadata: {
        roles: ["registered"],
            my_user_info: "registered user here"
        },
        user_metadata: {
            ...user.user_metadata,
            custom_data_from_function: "some extra super data"
        }
    };
    callback(null, {
        statusCode: 200,
        body: JSON.stringify(responseBody)
    });
};

Trigger The Function On Signup

Next in the Netlify dashboard you need to go to “Site settings”, “Identity”, then add a webhook pointing at the function you just created that triggers on “signup”. See example below.

User Role On Signup

Now when users sign up using Netlify Identity they will have the role “registered”. This could be used for example restricting access to certain pages.

Restrict Pages Based On User Role

The example below shows how to restrict the page “/secret-page” to users who have the registered role and redirect those who do not have that role with a 401.

[[redirects]]
  from = "/secret-page"
  to ="/secret-page"
  force = true
  status = 200
  conditions = {Role = ["registered"]}

[[redirects]]
  from = "/secret-page"
  to = "/"
  force = true
  status = 401

👍 Thanks for reading. Have a great rest of your day.