Handling User Authentication Using React and Appwrite
Learn in depth on how to authenticate users in your React projects with Appwrite Cloud which eliminates the need for backend code
Published on - by Jacob KyaloIntroduction
Appwrite is an open-source platform that lets you add Auth, Databases, Functions and Storage to your projects and build any application at any scale without hassle using your preferred coding languages and tools.
Appwrite helps developers to add backend functionality to their apps without need to write backend code using languages like Python, PHP or NodeJs. It is a BaaS.
Services offered
Appwrite offers services such as:
- Auth: Auth helps in authenticating users with different ways like Email/Password, OAuth, and more
- Databases: For storing and managing your application data
- Storage: For storing files for your application such images in buckets
- Functions: Used for writing serverless functions
- Realtime: Used for subscribing to realtime events if your application requires them e.g. if you are building a Chat Application
Our main focus in this article is Auth which is a very crucial component when building applications. Am assumming that you have a already running React application. The first thing to do is to install the Appwrite package
npm install appwrite
Next you need to configure Appwrite with your project. In this case with web sdk. So create a appwrite.config.js file and add the following code
import { Client, Account } from "appwrite";
const client = new Client();
client
.setEndpoint(import.meta.env.VITE_API_ENDPOINT)
.setProject(import.meta.env.VITE_APPWRITE_PROJECT_ID);
export const account = new Account(client);
PROJECT_ID and API_ENDPOINT can be obtained from appwrite console when you create a new project
Next thing is to create functions that will do the following:
- Register a user
- Login a user
- Logout a user
- Get information of currently loggedin user
- Persist a user on page render/refresh
Create a context for Auth like context/AuthContext.jsx file and add the following code. Context helps in managing state in React without additional third-party libraries like Redux
import { useState, createContext, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { ID } from "appwrite";
import { account } from "../config/appwrite.config";
export const AuthContext = createContext(null);
export default function AuthContextProvider({ children }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(false);
const navigate = useNavigate();
const registerUser = async (email, password, name) => {
try {
setLoading(true);
await account.create(ID.unique(), email, password, name);
setLoading(false);
await account.createEmailSession(email, password);
let accountDetails = await account.get();
setUser(accountDetails);
toast.success("Account created successfully");
navigate("/");
} catch (error) {
console.log(error.message);
setLoading(false);
}
};
const loginUser = async (email, password) => {
try {
setLoading(true);
await account.createEmailSession(email, password);
setLoading(false);
let accountDetails = await account.get();
setUser(accountDetails);
toast.success("Login successful");
navigate("/");
} catch (error) {
console.log(error.message);
setLoading(false);
}
};
const logoutUser = async () => {
try {
setLoading(true);
await account.deleteSession("current");
setLoading(false);
setUser(null);
localStorage.removeItem("cookieFallback");
toast.success("Logout successful");
navigate("/auth/login");
} catch (error) {
console.log(error.message);
setLoading(false);
}
};
const persistUser = async () => {
try {
let accountDetails = await account.get();
setUser(accountDetails);
} catch (error) {
toast.error(error.message);
}
};
useEffect(() => {
persistUser();
}, []);
const values = {
user,
loading,
signupUser,
loginUser,
logoutUser,
};
return <AuthContext.Provider value={values}>{children}</AuthContext.Provider>;
}
The account.get() function gets the information of currently loggedin user and keeps it in a state user while the persistUser function makes sure that on page refresh a user is still loggedin because this function runs on every page render due to use of useEffect hook.
Then you can wrap your app with this context provider and use the useContext hook to get these functions and utilize them in your components. You can also use a custom hook to abstract the useContext hook functionality.
That's it. You can now authenticate users in your application.
There is more to Appwrite Auth. For more information visit Appwrite docs.