How do you programmatically invite Identity users with the GoTrue API?

I want to programmatically invite users to my site instead of logging into the Netlify panel and pressing the “Invite” button.

I’m just using cURL to test things out. This command works fine for signing up a user to a site:

curl -X POST -H "Content-Type: application/json" \
-d '{"email": "me@example.com","password": "secret"}' \
https://<site>.netlify.app/.netlify/identity/signup

But I want the user to be invited to set their own password.

I had a look at the GoTrue API Endpoints to see if there was a way to send an invite to an email and came up with this:

curl -H "Authorization: Bearer <JWT TOKEN>" \
-H "Content-Type: application/json" -d '{"email": "me@example.com"}' \
https://<site>.netlify.app/.netlify/identity/invite

This seems to be correct, but I’m having trouble finding out how you’re supposed to get a valid token for the request.

I’ve tried:
• Using a personal access token. This doesn’t work for the GoTrue API (and it isn’t a JWT token)
• Logging into my site and using the JWT token issued to my user inside the CURL command. Doing this returns {"code":401,"msg":"User not allowed"} which seems to indicate that I need an specially issued JWT token.

How do I generate the JWT token to make this work?

Hey @Rotisserie,

You can’t invite users from client-side. You need to use serverless functions. Take this for example:

import Axios from 'axios'
export async function handler({body}, {clientContext: {identity: {token, url}}}) {
  const {email} = JSON.parse(body)
  return Axios({
    data: {
      email
    },
    headers: {
      authorization: `Bearer ${token}`
    },
    method: 'post',
    url: `${url}/invite`
  }).then(() => {
    return {
      body: JSON.stringify({
        'message': 'invite sent successfully'
      }),
      statusCode: 200
    }
  }).catch(({response: {data}}) => {
    return {
      body: JSON.stringify({
        data,
        'message': 'failed'
      }),
      statusCode: 500
    }
  })
}

You can curl to this endpoint with the email as body.

Make sure to run some checks in here to see if you really wish to invite this user or else anyone can spam this endpoint with their email and get an invite token generated.

1 Like