Email Verification on Signup from Frontend and Backend
In this article, we will discuss how to implement email verification on signup from both the frontend and backend using Django rest framework with Reactjs.
Frontend Implementation
On the frontend side, we will create a signup form where users can enter their email address and password. Once the user submits the form, we will send a verification email to the provided email address. The user will then need to click on a verification link to activate their account.
“`jsx
import React, { useState } from ‘react’;
const SignupForm = () => {
const [email, setEmail] = useState(”);
const [password, setPassword] = useState(”);
const handleSubmit = async (e) => {
e.preventDefault();
// Send a POST request to the backend to register the user
const response = await fetch(‘http://localhost:8000/api/signup/’, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’,
},
body: JSON.stringify({ email, password }),
});
// Show a success message to the user
const data = await response.json();
alert(data.message);
};
return (
setEmail(e.target.value)} placeholder=”Email” />
setPassword(e.target.value)} placeholder=”Password” />
);
};
export default SignupForm;
“`
Backend Implementation
On the backend side, we will create an API endpoint that handles user registration and email verification. When a user signs up, we will generate a unique verification token and send it via email. When the user clicks on the verification link, we will verify their email address and activate their account.
“`python
from django.core.mail import send_mail
from django.utils.crypto import get_random_string
from rest_framework.views import APIView
from rest_framework.response import Response
class SignupAPIView(APIView):
def post(self, request):
email = request.data.get(’email’)
password = request.data.get(‘password’)
# Generate a unique verification token
verification_token = get_random_string(length=32)
# Send a verification email to the user
send_mail(
‘Activate Your Account’,
f’Click on the following link to activate your account: http://localhost:8000/api/verify/?token={verification_token}’,
‘noreply@example.com’,
[email],
fail_silently=False,
)
return Response({‘message’: ‘Please check your email to activate your account.’})
“`
Conclusion
By implementing email verification on signup from both the frontend and backend, we can ensure that only valid email addresses are used during the registration process. This helps prevent fake accounts and increases the security of our application.
when is the next upload?
Thanks for making such a good tutorials on DRF and React. Go ahead and complete the full project with nested serializer, image upload, payment method.
love it ♥