Great news! Seems like it worked. My testing was fairly limited though and I might have missed something. Let me know if something doesn’t work.
Side note: I’m sorry I am not sharing this as a repo for now as I implemented this in a project I already have. I can link to its repo, but you’d have to find the relevant code which would be a waste. I could setup another repo, but I was excited to share the solution promptly.
So, here you go:
First run:
npm i gotrue-js node-fetch
In your client-side JS:
import GoTrue from 'gotrue-js' // This added around 15 KB to my bundle
let auth = new GoTrue({
APIUrl: 'https://website.netlify.app/.netlify/identity'
/*
The above URL is also displayed in the Identity tab of the website. I suppose it's safe to keep the URL
in the client-side code because it's a non-customizable URL provided by Netlify. So, probably anyone
can guess the URL. For example, https://www.website.com/ will have it at
https://www.website.com/.netlify/identity.
I sincerely hope Netlify is able to control who can connect to this URL.
*/
})
/*
Create any random email and password as you are anyways going to delete the user. It's recommend
that you generate a random email, (if not password), for each function call so that if multiple users try
to call the function at the same time, it won't return 'user already exists' error
*/
auth.signup(email, password).then(() => {
auth.login(email, password).then(response => {
fetch('/.netlify/functions/functionName/', {
headers: {
Authorization: 'Bearer ' + response.token.access_token
}
}).then(/*carry on*/)
}
}
In your serverless function:
const fetch = require('node-fetch')
exports.handler = async (event, context) => {
const {identity, user} = context.clientContext
if (user) {
return fetch(identity.url + '/admin/users/' + user.sub, {
method: 'DELETE',
headers: {
Authorization: 'Bearer ' + identity.token
}
}).then(() => {
// rest of the function here
})
} else {
// show error
}
}
I have typed the code here directly, so chances are I might have missed some brackets or made a mistake with indention or something. So, try it once and let me know if it works.
Note that, you cannot delete the user from Netlify CLI. So, to test the deletion, you’d have to publish the website.