Add authentication to your Sitecore site using Auth0 with NextJs – Forgot Password
G?ran Halvarsson
Experienced Fullstack & Sitecore MVP | AI Enthusiast | .NET, Azure, Kubernetes, Sitecore Specialist
Friends I hope you are enjoying spring. The month of May in Sweden is truly beautiful. The landscape bursts into lush greenery, flowers bloom, and the weather becomes comfortably warm. It’s a perfect time to enjoy outdoor activities and experience the stunning natural beauty of the country.
But as a coder, who wants to be outside when you can stay indoors in a dark room and code all day in front of your screen? ??
In my previous post, Add authentication to your Sitecore site using Auth0 with?NextJs, I discussed how to integrate Auth0 into your Sitecore Next.js site. Continuing with this theme, let’s now explore how to add the Forgot Password functionality.
Let’s start We will update the login component, so that we can offer users to change their password.
In our LoginForm component, we will add the UI for the Forgot Password feature:
{activeTab === 'forgotPassword' && (
<div className={styles.generalForm}>
<form className={styles.form} onSubmit={handleForgotPasswordSubmit}>
<h2 className={styles.title}>Forgot Password</h2>
<input className={styles.input} name="email" type="email" placeholder="Enter your email" required />
<button className={styles.button} type="submit">Send Reset Link</button>
</form>
</div>
)}
And the handler function handleForgotPasswordSubmit will manage the form submission for the Forgot Password feature:
const handleForgotPasswordSubmit = async (event: { preventDefault: () => void; currentTarget: HTMLFormElement | undefined; }) => {
event.preventDefault();
const formData = new FormData(event.currentTarget);
const email = formData.get('email');
// Assuming you have an API endpoint or NextAuth.js method to handle password reset
try {
const res = await fetch('/api/auth/changePassword', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email
}),
});
if (!res.ok) {
throw new Error(res.errors);
}
setActiveTab('login');
setErrorMessage(''); // Clear any existing error messages
setSuccessMessage('Password reset email sent successfully. Please check your email.');
setTimeout(() => {
setSuccessMessage(''); // Optionally clear the success message after some time
}, 5000); // 5000 milliseconds = 5 seconds
console.log('Sending password reset email to:', email);
// Reset form or show a success message
} catch (error) {
console.error('Password reset error:', error);
setErrorMessage('Failed to send password reset email. Please try again.');
}
};
Let’s take a look at what our handleForgotPasswordSubmit function is doing under the hood:
领英推荐
In a nutshell, our handleForgotPasswordSubmit function takes care of the whole “Forgot Password” process smoothly, making sure users get the feedback they need whether things go right or wrong.
Let’s continue and create the endpoint /api/auth/changePassword that handles password change requests for users through Auth0.
export default async function handler(req, res) {
const domain = process.env.DOMAIN;
const connection = process.env.CONNECTION;
const client_id = process.env.CLIENT_ID;
if (req.method === 'POST') {
const { email } = req.body;
try {
const auth0Res = await fetch(`https://${domain}.auth0.com/dbconnections/change_password`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
client_id,
email,
connection,
}),
});
if (!auth0Res.ok) {
throw new Error(`Change password failed: ${await auth0Res.text()}`);
}
// Since the expected response is not JSON, just read the text response
const responseText = await auth0Res.text();
res.status(200).json({ success: true, message: responseText });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
} else {
res.setHeader('Allow', ['POST', 'OPTIONS']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
Let’s take a look at what our handler function is doing under the hood:
Our handler function is all about sending a password reset request to Auth0. It takes an email address, sends it to Auth0, and handles the response. If everything goes well, it lets the user know a password reset email is on its way. If something goes wrong, it catches the error and sends back a helpful error message.
And that’s it! Now you’ve got a smooth Forgot Password process integrated into your Sitecore Next.js site using Auth0. It’s always a good feeling to make your app more user-friendly, isn’t it?
I hope you found this guide helpful and that it makes your coding journey a bit easier. If you have any questions, run into issues, or just want to share how it’s going, drop a comment below or reach out to me. I’m always happy to chat!
That’s all for now folks???