How to Use Appwrite for Authentication and Email Verification with React and TypeScript
In this blog, we will walk through how to integrate Appwrite, an open-source backend-as-a-service (BaaS) platform, into your React + TypeScript application to implement Google login and email verification functionality. By the end of this guide, your application will have a smooth authentication flow with Google login and email verification ready.
What is Appwrite?
Before diving into the technical details, let’s first understand Appwrite. Appwrite is an open-source backend-as-a-service platform that provides a set of easy-to-use APIs for various backend services, including user authentication, databases, file storage, and more. With Appwrite, developers can avoid the hassle of building a backend from scratch, allowing them to focus on creating amazing app features.
Key Features of Appwrite
Real-time Database: Appwrite offers a real-time database with support for queries, filtering, and sorting.
User Authentication: Secure login and registration with support for multiple authentication methods, such as OAuth2, email/password, and more.
File Storage: Store and manage files securely with easy upload and download features.
Cloud Functions: Write serverless functions to execute backend logic.
For this guide, we’ll focus on the user authentication feature of Appwrite.
Creating an Appwrite Account
To start with Appwrite, you must sign up and create a new account on the Appwrite platform. Once logged in, you can create a new project to house all your app’s backend data and services.
Setting Up a Project in Appwrite
After creating your account, you should create a new project within the Appwrite console. This project will handle your app’s backend tasks, including authentication.
Go to the Appwrite console.
Click "Create New Project" and enter a project name and ID.
Note your Project ID and Appwrite Endpoint, as we’ll need them later in our React app.
Configuring Google OAuth2 in Appwrite
Head to the Authentication section in the Appwrite console and select the settings tab.
Under OAuth2 Providers, enable Google and provide the necessary Client ID and Client Secret from the Google Developer Console.
Getting Google OAuth2 Credentials
To get your Google OAuth2 credentials:
Go to the Google Developer Console.
Create a new project and go to the APIs & Services section.
Go to the Credentials section and create OAuth 2.0 credentials.
Copy the Client ID and Client Secret provided and add them to the Appwrite console under the Google OAuth provider settings.
- Enter the App Secret. NOTE You need to use the Client Secret value from your Google Credentials > OAuth 2.0 Client IDs.
Enabling Google Authentication in Appwrite
Users can log in using their Google account once you’ve added the Google OAuth2 credentials to Appwrite.
Project Setup
Let's start by creating a new React.js project.
npx create-react-app appwrite-auth-project
This command will create a new folder called appwrite-auth-project
with the basic structure of a React project.
Running the Project
- Navigate to the directory of your newly created project:
cd appwrite-auth-project
- Run the following command to start the application on a development server:
npm start
React will start the development server and automatically open your application in the browser.
Installing Appwrite SDK
Install the Appwrite SDK to communicate with the backend from your React app.
npm install appwrite
Integrating Appwrite SDK with React
In your React app, create a file appwrite.ts
where you’ll configure the Appwrite SDK.
import { Client, Account, OAuthProvider } from 'appwrite';
const client = new Client()
.setEndpoint('https://[YOUR_APPWRITE_URL]')
.setProject('[YOUR_PROJECT_ID]');
const account = new Account(client);
export { OAuthProvider,account }
Creating a Google Login Component
Next, create a GoogleLogin.tsx
component where users can log in with Google.
import React, { useState } from 'react';
import { account, OAuthProvider } from './appwrite';
const GoogleLogin: React.FC = () => {
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleGoogleLogin = async () => {
setLoading(true);
setError(null);
try {
const redirectURL = `${window.location.origin}/dashboard`; // Redirect after successful login
await account.createOAuth2Session(OAuthProvider.Google,redirectURL);
} catch (err) {
setError('Login failed',err);
} finally {
setLoading(false);
}
};
return (
<div>
<button type="button" onClick={handleGoogleLogin} disabled={loading}>
<GoogleIcon />
<span>Sign in with Google</span>
</button>
{error && <p>{error}</p>}
</div>
);
};
export default GoogleLogin;
Redirecting After Successful Login
Once the user successfully logs in with Google, Appwrite will handle the authentication and redirect the user to the specified URL. In the code above, we redirect the user to the /dashboard
page after a successful login.
Error Handling in Login Flow
If the login fails for any reason (e.g., incorrect credentials or network issues), the error is caught, and an appropriate message is displayed.
Why Email Verification is Important
In Appwrite, email verification is required only when users sign up using an email and password. If a user logs in with Google, their email is already verified by Google, making additional verification unnecessary
Implementing Email Verification in Appwrite
When a user registers with an email and password, Appwrite provides the createVerification
method to send a verification email. The user must click on the verification link sent to their email to confirm their account.
By ensuring email verification for password-based signups, you can enhance security and and reduce fake accounts.
const sendVerificationEmail = async () => {
try {
await account.createVerification('http://localhost:3000/verify-email');
} catch (err) {
console.error('Failed to send verification email', err);
}
};
Handling Email Verification in React
Once the user receives the verification email, they will click the verification link to confirm their email address. You can create a page in your app to handle this action.
Creating the Email Verification Page
Create a VerifyEmail.tsx
component that will handle the verification process.
import React, { useEffect, useState } from 'react';
import { account } from './appwrite';
import { Loader } from '@aws-amplify/ui-react';
const VerifyEmail: React.FC = () => {
const [message, setMessage] = useState<string>('');
const location = useLocation();
const navigate = useNavigate();
const handleUpdateVerification = async (userId: string, secret: string) => {
try {
await account.updateVerification(userId, secret);
toast.success("Email verified successfully!");
navigate("/dashboard");
} catch (error) {
const exception = error as AppwriteException;
navigate("/verify-email");
}
};
useEffect(() => {
const searchParams = new URLSearchParams(location.search);
const userId = searchParams.get('userId');
const secret = searchParams.get('secret');
if (userId && secret) {
handleUpdateVerification(userId, secret);
}
}, [location.search]);
return <Loader />;
};
export default VerifyEmail;
After clicking the "Send Verification Email" button, you will receive an account verification link in your email. Simply click on the link, and that's it! Your email will be successfully verified! 🎉
That concludes this topic. Thank you for reading!
If you found this article helpful, please consider liking and sharing it with others. If you have any questions, feel free to comment; I will do my best to provide a helpful response.