React JS / Next JS: Reset Password using WordPress Rest API

React JS / Next JS: Reset Password using WordPress Rest API

It also works the exactly same if you are building an e-commerce store using WooCommerce REST API.

Β·

2 min read

Why do we need this?

πŸ“• There is no REST API endpoint out of the box to reset the password but we have to add additional functionality by installing the plugin on WordPress and then we can leverage it.

Let's start πŸ₯‚

πŸ˜Άβ€πŸŒ«οΈ Backend Implementation (WordPress Dashboard)

1. Install Plugin

πŸ‘‰ Install plugin on your WordPress dashboard.

Screenshot 2022-05-07 at 10.07.33 PM.png

2. Verification of Installation

πŸ‘‰ Here are a few steps that can confirm whether the plugin is installed successfully or not.

  1. Make an HTTP request on <yourdomain>/wp-json. Screenshot 2022-05-07 at 6.16.53 PM.png

  2. In response, you must have bdpwr/v1 in the namespaces field. Otherwise, this plugin is not configured properly and you have to read the full docs of the plugin or may need to consult with the community of that plugin. Screenshot 2022-05-07 at 6.21.18 PM.png

πŸ‘¨πŸ»β€πŸ’» Frontend Implementation (React JS / Next JS)

1. Send Code to Email

πŸ“• Email must be registered otherwise it will fail the HTTP request.

  • Request Example
    • Endpoint: <yourdomain>/wp-json/bdpwr/v1/reset-password
    • Method: POST
    • Parameters: email
export async function sendCodeToEmail({ email }) {
  try {
    const { data } = await axios.post(`${siteURL}/wp-json/bdpwr/v1/reset-password`, { email });
    return { data };
  } catch (error) {
    console.log({ error })
    return { error: 'Invalid email!' }
  }
}

βœ… Success Response

{
    data: {
        status: 200
    },
    message: "A password reset email has been sent to your email address."
}

2. Create New Password

✍️ Check your Gmail account, you will see an email with 4 digits secret code with some descriptions (you can customize the description and language by doing extra configurations, you will need to read the docs of the plugin).

  • Request Example
    • Endpoint: <yourdomain>/wp-json/bdpwr/v1/set-password
    • Method: POST
    • Parameters: email, password, code
export async function resetCustomerPasswordWithCode({ email, code, newPassword }) {
  try {
    const { data } = await axios.post(`${siteURL}/wp-json/bdpwr/v1/set-password`, { email, password: newPassword, code });
    return { data };
  } catch (error) {
    console.log({ error })
    return { error: 'Something went wrong...' }
  }
}

βœ… Success Response

{
    data: {
        status: 200
    },
    message: "Password reset successfully."
}

🎯 Conclusion

  1. Install the plugin on the WordPress dashboard.
  2. Sending 4-digit code to registered email.
  3. Creating a new password using 4 digit code.

Hope you enjoyed it, comments are open, you are welcome, let's communicate there 🀝

Β