Web Developers : 15-Sharing Authentication and Appwrite Session State Globally with React Context
Sharing Authentication and Appwrite Session State Globally with React Context
In modern web development, managing authentication and session states is crucial for creating seamless user experiences. In this blog post, we'll explore how to share authentication and Appwrite session state globally in a React application using React Context. This tutorial is inspired by a YouTube video titled "Web Developers: 15 - Sharing Authentication and Appwrite Session State Globally with React Context".
What is Appwrite?
Before diving into the implementation, let’s briefly discuss Appwrite. Appwrite is an open-source backend server that simplifies the development of web and mobile applications. It provides a suite of APIs for managing user authentication, databases, storage, and more.
Why Use React Context?
React Context provides a way to share values like authentication state across the entire application without passing props down manually at every level. This becomes especially useful for global states like user authentication and session management.
Prerequisites
To follow along with this tutorial, ensure you have:
- Basic knowledge of React
- An Appwrite account and setup
- Node.js and npm installed on your machine
Setting Up Your React Application
First, create a new React application if you don't have one already. You can do this using Create React App:
npx create-react-app my-app
cd my-app
Next, install the Appwrite SDK:
npm install appwrite
Create the Authentication Context
We will create a context to manage the authentication state. In your src directory, create a new folder named context, and inside it, create a file named AuthContext.js.
// src/context/AuthContext.js
import React, { createContext, useState, useEffect } from 'react';
import { Client, Account } from 'appwrite';
const AuthContext = createContext();
const client = new Client();
client.setEndpoint('https://[YOUR_APPWRITE_ENDPOINT]') // Your Appwrite Endpoint
.setProject('[YOUR_PROJECT_ID]'); // Your project ID
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const account = new Account(client);
const getUser = async () => {
try {
const userData = await account.get();
setUser(userData);
} catch (error) {
console.error("User not logged in", error);
}
};
useEffect(() => {
getUser();
}, []);
return (
<AuthContext.Provider value={{ user, setUser }}>
{children}
</AuthContext.Provider>
);
};
export const useAuth = () => React.useContext(AuthContext);
Breakdown of the Code
- Client Initialization: We initialize the Appwrite client with the endpoint and project ID.
- State Management:
userstate holds the authenticated user data. We useuseEffectto fetch user information on component mount. - Context Provider: The
AuthProvidercomponent wraps the application and provides the authentication context to its children.
Using the AuthProvider in Your Application
Wrap your application with AuthProvider in index.js:
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { AuthProvider } from './context/AuthContext';
ReactDOM.render(
<AuthProvider>
<App />
</AuthProvider>,
document.getElementById('root')
);
Accessing Authentication State in Components
To access the authentication state, you will use the useAuth hook we created. Here's an example of a simple component that displays the user's information:
// src/components/UserProfile.js
import React from 'react';
import { useAuth } from '../context/AuthContext';
const UserProfile = () => {
const { user } = useAuth();
return (
<div>
{user ? (
<h1>Hello, {user.name}</h1>
) : (
<h1>Please log in</h1>
)}
</div>
);
};
export default UserProfile;
Handling User Login and Logout
You can extend your authentication context to include methods for logging in and logging out users. For example:
// Add this inside the AuthProvider in AuthContext.js
const login = async (email, password) => {
try {
const session = await account.createSession(email, password);
await getUser(); // Fetch user after login
return session;
} catch (error) {
console.error("Login failed", error);
}
};
const logout = async () => {
try {
await account.deleteSession('current');
setUser(null);
} catch (error) {
console.error("Logout failed", error);
}
};
// Update the provider value
return (
<AuthContext.Provider value={{ user, setUser, login, logout }}>
{children}
</AuthContext.Provider>
);
Conclusion
In this tutorial, we successfully set up a global authentication state management system using React Context and Appwrite. This approach allows you to maintain user sessions across your application efficiently.
Feel free to expand upon this foundation by adding routes, improving error handling, or customizing your user experience. Happy coding!
Further Reading
By implementing these techniques, you can create a robust and user-friendly application that efficiently manages authentication and session states.
Connect with SkillBakery Studios
Explore more tutorials, tools, and resources:
Posted by SkillBakery Studios


No comments:
Post a Comment