A simple and flexible authentication library for React applications, built on top of NextAuth.js.
To install the React AuthJS Library, run the following command in your project directory:
npm install react-authjs-library
First, wrap your main application component with the AuthProvider
:
import { AuthProvider } from 'react-authjs-library';
function App() {
return (
<AuthProvider>
{/* Your app components */}
</AuthProvider>
);
}
The library provides several components and hooks for managing authentication:
import { SignInButton } from 'react-authjs-library';
function LoginPage() {
return (
<div>
<h1>Login</h1>
<SignInButton />
</div>
);
}
import { SignOutButton } from 'react-authjs-library';
function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
<SignOutButton />
</div>
);
}
Wrap components that require authentication with ProtectedRoute
:
import { ProtectedRoute } from 'react-authjs-library';
function PrivateContent() {
return (
<ProtectedRoute>
<h2>This content is only visible to authenticated users</h2>
</ProtectedRoute>
);
}
Use the useAuth
hook to access the current authentication state:
import { useAuth } from 'react-authjs-library';
function UserProfile() {
const { user, isAuthenticated, isLoading } = useAuth();
if (isLoading) return <div>Loading...</div>;
if (!isAuthenticated) return <div>Please sign in</div>;
return (
<div>
<h1>Welcome, {user.name}!</h1>
{/* Display user profile information */}
</div>
);
}
To configure the authentication providers and options, you need to set up NextAuth.js in your project. Refer to the NextAuth.js documentation for detailed instructions on how to configure various authentication providers.
- This library is a wrapper around NextAuth.js, so you'll need to configure NextAuth.js separately in your project.
- Ensure you have the necessary backend setup to handle authentication requests.
- The current implementation is designed for client-side usage. For server-side rendering or more advanced configurations, refer to the NextAuth.js documentation.
You can customize the appearance of the SignInButton
and SignOutButton
components by passing a className
prop:
<SignInButton className="my-custom-button-class" />
<SignOutButton className="my-custom-button-class" />
Contributions are welcome! Please feel free to submit a Pull Request.
This project is licensed under the MIT License.