Skip to main content

Allow users to change their email

caution

SuperTokens does not provide the UI for users to update their email, you will need to create the UI and setup a route on your backend to have this functionality.

In this section we will go over how you can create a route on your backend which can update a user's email. Calling this route will check if the new email is valid and not already in use and proceed to update the user's account with the new email. There are two types of flows here:

Flow 1: Update email without verifying the new email.#

In this flow a user is allowed to update their accounts email without verifying the new email id.

Step 1: Creating the /change-email route#

  • You will need to create a route on your backend which is protected by the session verification middleware, this will ensure that only a authenticated user can access the protected route.
  • To learn more about how to use the session verification middleware for other frameworks click here
import { verifySession } from "supertokens-node/recipe/session/framework/express";
import { SessionRequest } from "supertokens-node/framework/express"
import express from "express";

let app = express();

app.post("/change-email", verifySession(), async (req: SessionRequest, res: express.Response) => {
// TODO: see next steps
})

Step 2: Validate the new email and update the account#

  • Validate the input email.
  • Check that the account you are trying to update is not social account.
  • Update the account with the input email.
// the following example uses express
import ThirdPartyEmailPassword from "supertokens-node/recipe/thirdpartyemailpassword";
import { verifySession } from "supertokens-node/recipe/session/framework/express";
import { SessionRequest } from "supertokens-node/framework/express"
import express from "express";

let app = express();

app.post("/change-email", verifySession(), async (req: SessionRequest, res: express.Response) => {

let session = req.session!;
let email = req.body.email;

// Validate the input email
if (!isValidEmail(email)) {
// TODO: handle invalid email error
return
}

// Check that the account to be updated is not a social account
{
let userId = session!.getUserId();
let userAccount = await ThirdPartyEmailPassword.getUserById(userId!);
if (userAccount!.thirdParty !== undefined) {
// TODO: handle error, cannot update email for third party users.
return
}
}

// Update the email
let resp = await ThirdPartyEmailPassword.updateEmailOrPassword({
userId: session.getUserId(),
email: email,
});

if (resp.status === "OK") {
// TODO: send successfully updated email response
return
}
if (resp.status === "EMAIL_ALREADY_EXISTS_ERROR") {
// TODO: handle error that email exists with another account.
return
}
throw new Error("Should never come here");

})

function isValidEmail(email: string) {
let regexp = new RegExp(
/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
);
return regexp.test(email);
}

Flow 2: Updating email after verifying the new email.#

In this flow the user's account is updated once they have verified the new email.

Step 1: Creating the /change-email route#

  • You will need to create a route on your backend which is protected by the session verification middleware, this will ensure that only a authenticated user can access the protected route.
  • To learn more about how to use the session verification middleware for other frameworks click here
import { verifySession } from "supertokens-node/recipe/session/framework/express";
import { SessionRequest } from "supertokens-node/framework/express"
import express from "express";

let app = express();

app.post("/change-email", verifySession(), async (req: SessionRequest, res: express.Response) => {
// TODO: see next steps
})

Step 2: Validate the email and initiate the email verification flow#

  • Validate the input email
  • Check that the user's account is not a social account.
  • Check if the input email is associated with an account.
  • Check if the input email is already verified.
  • If the email is NOT verified, create and send the verification email.
  • If the email is verified, update the account with the new email.
// the following example uses express
import ThirdPartyEmailPassword from "supertokens-node/recipe/thirdpartyemailpassword";
import EmailVerification from "supertokens-node/recipe/emailverification";
import { verifySession } from "supertokens-node/recipe/session/framework/express";
import { SessionRequest } from "supertokens-node/framework/express"
import express from "express";

let app = express();

app.post("/change-email", verifySession(), async (req: SessionRequest, res: express.Response) => {

let session = req.session!;
let email = req.body.email;

// validate the input email
if (!isValidEmail(email)) {
// TODO: handle error, email is invalid
return
}

// Check if the user's account is not a third party account
{
let sessionId = session!.getUserId();
let userAccount = await ThirdPartyEmailPassword.getUserById(sessionId!);
if (userAccount!.thirdParty !== undefined) {
// TODO handle error, cannot update password for third party users.
return
}
}

// Then, we check if the email is verified for this user ID or not.
// It is important to understand that SuperTokens stores email verification
// status based on the user ID AND the email, and not just the email.
let isVerified = await EmailVerification.isEmailVerified(session.getUserId(), email);

if (!isVerified) {
// Before sending a verification email, we check if the email is already
// being used by another user. If it is, we throw an error.
let user = (await ThirdPartyEmailPassword.getUserById(session.getUserId()))!;
for (let i = 0; i < user?.tenantIds.length; i++) {
// Since once user can be shared across many tenants, we need to check if
// the email already exists in any of the tenants.
let usersWithEmail = await ThirdPartyEmailPassword.getUsersByEmail(user.tenantIds[i], email);
for (let y = 0; y < usersWithEmail.length; y++) {
if (usersWithEmail[y].id !== session.getUserId()) {
// TODO handle error, email already exists with another user.
return
}
}
}

// Now we create and send the email verification link to the user for the new email.
await EmailVerification.sendEmailVerificationEmail(session.getTenantId(), session.getUserId(), email);

// TODO send successful response that email verification email sent.
return
}

// Since the email is verified, we try and do an update
let resp = await ThirdPartyEmailPassword.updateEmailOrPassword({
userId: session.getUserId(),
email: email,
});

if (resp.status === "OK") {
// TODO: send successful response that email has been updated
return
}
if (resp.status === "EMAIL_ALREADY_EXISTS_ERROR") {
// TODO: handle error, email already exists for another account
return
}
throw new Error("Should never come here");

})

function isValidEmail(email: string) {
let regexp = new RegExp(
/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
);
return regexp.test(email);
}

Multi Tenancy
  • Notice that we loop through all the tenants that this user belongs to check that for each of the tenants, there is no other user with the new email. If we did not do this, then calling updateEmailOrPassword would fail because the email is already used by another user in one of the tenants that this user belongs to. So in that case, we do not want to go through the verification process either.
  • We also pass in the tenantId of the current session when calling the sendEmailVerificationEmail function, so that the link generated will open the the tenant's UI that the user is currently interacting with.
  • When calling updateEmailOrPassword, it will return EMAIL_ALREADY_EXISTS_ERROR if the new email exists in any of the tenants that the user ID is a part of.

Step 3: Override the verifyEmailPost API to update the user's account on successful email verification#

  • Update the accounts email on successful email verification.
import SuperTokens from "supertokens-node";
import ThirdPartyEmailPassword from "supertokens-node/recipe/thirdpartyemailpassword";
import EmailVerification from "supertokens-node/recipe/emailverification";
import Session from "supertokens-node/recipe/session";

SuperTokens.init({
appInfo: {
apiDomain: "...",
appName: "...",
websiteDomain: "...",
},
recipeList: [
ThirdPartyEmailPassword.init({}),
EmailVerification.init({
mode: "REQUIRED",
override: {
apis: (oI) => {
return {
...oI,
verifyEmailPOST: async function (input) {
let response = await oI.verifyEmailPOST!(input);
if (response.status === "OK") {
// This will update the email of the user to the one
// that was just marked as verified by the token.
await ThirdPartyEmailPassword.updateEmailOrPassword({
userId: response.user.id,
email: response.user.email,
});
}
return response;
},
};
},
},
}),
Session.init(),
],
});