Programmatically invite users in Netlify Function

My site name is brave-payne-ff9bfe.

I am trying to deploy a function that programmatically invites a user to join my site (instead of using the invite button in the Netlify UI), but I keep getting a 405: Method Not Allowed.

Here is the code for my function:

import fetch from 'node-fetch';

export async function handler(event, context) {

  const { identity } = context.clientContext;
  const inviteUrl = `${identity.url}/invite`;
  const adminAuthHeader = "Bearer " + identity.token;

    try {
      return fetch(inviteUrl, {
        method: "POST",
        headers: { Authorization: adminAuthHeader },
        body: JSON.stringify({ email: JSON.parse(event.body).email }),
      })
      .then(response => {
        console.log("response: ",response);
        return response.json();
      })
      .then(data => {
        console.log("Invited a user! 204!");
        console.log(JSON.stringify({ data }));
        return { statusCode: 204 };
      })
      .catch(e => {return e});
  } catch (e) { return e; };
}

Here is the contents of the HTTP response:

response:  Response {
  size: 0,
  [Symbol(Body internals)]: {
    body: PassThrough {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      [Symbol(kCapture)]: false,
      [Symbol(kCallback)]: null
    },
    stream: PassThrough {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      [Symbol(kCapture)]: false,
      [Symbol(kCallback)]: null
    },
    boundary: null,
    disturbed: false,
    error: null
  },
  [Symbol(Response internals)]: {
    type: 'default',
    url: 'https://netlify-dev-locally-emulated-identity.netlify.app/.netlify/identity/invite',
    status: 405,
    statusText: 'Method Not Allowed',
    headers: {
      age: '1',
      'alt-svc': 'clear',
      connection: 'close',
      'content-length': '0',
      date: 'Thu, 24 Feb 2022 20:30:57 GMT',
      server: 'Netlify',
      via: '1.1 google',
      'x-nf-request-id': '01FWPPVYV3HN3KJZ17Y77ZFG0J'
    },
    counter: 1,
    highWaterMark: 16384
  }
}

Hey @jimmend

The Invite users button in the Netlify UI doesn’t use that endpoint. Check out [Support Guide] Understanding and using Netlify's API which states:

The most important advice I can give you about using our API is to watch how we do it! Our entire admin UI works via this API…

This is an undocumented endpoint though (from what I can tell.) It may or may not work for you (now), and may or may not change in the future.