authweb3
v0.0.1
Published
A comprehensive authentication library for React and Next.js applications supporting email/password and Web3 wallet authentication with modern UI components.
Downloads
5
Maintainers
Readme
AuthWeb3
A comprehensive authentication library for React and Next.js applications, supporting both email/password authentication and Web3 wallet authentication with modern, customizable UI components.
Developed by Viainti - Expert Web3 Development
Features
- Email/password authentication with JWT tokens
- Web3 wallet authentication (MetaMask, Phantom, Solflare, etc.)
- Flexible database integration (Firebase, MongoDB, PostgreSQL, etc.)
- React hooks for easy state management
- TypeScript support
- Fully customizable UI (colors, logos, themes)
- Multiple display modes (modal, page, inline)
- Form validation with customizable rules
- Environment-based configuration
- Compatible with any database through configurable callbacks
Installation
npm install authweb3Requirements
- React 16.8.0+
- Next.js 12.0+ (optional, for Next.js integration)
- TypeScript 4.0+ (recommended)
Quick Start
npm install authweb3Basic Usage
Modal Authentication
import { AuthModal } from 'authweb3';
function App() {
const [isOpen, setIsOpen] = useState(false);
return (
<>
<button onClick={() => setIsOpen(true)}>
Sign In
</button>
<AuthModal
isOpen={isOpen}
onClose={() => setIsOpen(false)}
config={authConfig}
onSuccess={(user) => console.log('Authenticated:', user)}
/>
</>
);
}Page Authentication
import { AuthPage } from 'authweb3';
function LoginPage() {
return (
<AuthPage
config={authConfig}
title="Welcome Back"
subtitle="Sign in to your account"
onSuccess={(user) => console.log('Authenticated:', user)}
/>
);
}Tabbed Interface
AuthWeb3 supports tabbed authentication interfaces for better UX:
<AuthModal
isOpen={isOpen}
onClose={() => setIsOpen(false)}
config={authConfig}
showTabs={true} // Enable login/register tabs
defaultTab="login" // "login" or "register"
/>Quick Start
1. Configure your database
First, set up your database operations. Here's an example with a simple in-memory store (replace with your actual database):
import { AuthConfig } from 'authweb3';
const authConfig: AuthConfig = {
jwtSecret: 'your-secret-key',
jwtExpiresIn: '7d',
database: {
createUser: async (userData) => {
// Implement your database create logic
const user = {
id: Date.now().toString(),
...userData,
createdAt: new Date(),
};
// Save to database
return user;
},
findUserByEmail: async (email) => {
// Implement your database find logic
return null; // or found user
},
findUserByWallet: async (walletAddress) => {
// Implement your database find logic
return null; // or found user
},
updateUser: async (id, updates) => {
// Implement your database update logic
return updatedUser;
},
},
};2. Use the hooks in your React components
import React from 'react';
import { useAuth, useWallet, LoginForm, WalletConnect } from 'authweb3';
function App() {
const auth = useAuth(authConfig);
const wallet = useWallet();
const handleWalletLogin = async () => {
if (wallet.address) {
await auth.loginWithWallet(wallet.address);
}
};
if (auth.isAuthenticated) {
return (
<div>
<h1>Welcome, {auth.user?.email || wallet.address}</h1>
<button onClick={auth.logout}>Logout</button>
</div>
);
}
return (
<div>
<LoginForm
onLogin={auth.login}
onRegister={auth.register}
isLoading={auth.isLoading}
error={auth.error}
/>
<hr />
<WalletConnect
onConnect={wallet.connect}
onDisconnect={wallet.disconnect}
address={wallet.address}
isConnected={wallet.isConnected}
isConnecting={wallet.isConnecting}
error={wallet.error}
/>
{wallet.isConnected && (
<button onClick={handleWalletLogin} disabled={auth.isLoading}>
Login with Wallet
</button>
)}
</div>
);
}
export default App;3. In Next.js (App Router)
'use client';
import { useAuth } from 'authweb3';
export default function LoginPage() {
const auth = useAuth(authConfig);
// Your component logic
}Customization
Quick Color Customization
For simple color changes, use individual color props:
<AuthModal
isOpen={isOpen}
onClose={() => setIsOpen(false)}
config={authConfig}
primaryColor="#your-brand-color"
backgroundColor="#f8f9fa"
textColor="#1a1a1a"
/>Advanced Theme Customization
For complete control, use the theme object:
const customTheme = {
colors: {
primary: '#your-brand-color',
secondary: '#your-secondary-color',
background: '#ffffff',
text: '#000000',
border: '#e5e7eb',
error: '#ef4444',
success: '#10b981',
muted: '#6b7280'
},
borderRadius: '12px',
fontFamily: 'Inter, sans-serif',
spacing: {
small: '8px',
medium: '16px',
large: '24px'
},
logo: {
src: '/path/to/your/logo.png',
alt: 'Your Logo',
width: 120,
height: 40
}
};
<AuthModal
isOpen={isOpen}
config={authConfig}
theme={customTheme}
/>Social Providers
AuthWeb3 supports multiple social authentication providers:
<AuthModal
isOpen={isOpen}
config={authConfig}
socialProviders={['google', 'linkedin', 'telegram', 'line', 'tiktok', 'sms']}
/>Wallet Networks
Configure wallet connections for different networks:
<AuthModal
isOpen={isOpen}
config={authConfig}
supportedWallets={['metamask', 'phantom', 'solflare']}
/>Supported networks:
- EVM: MetaMask
- Solana: Phantom, Solflare
Modal Email Authentication
For ultra-compact interfaces, hide email forms behind a modal:
<AuthModal
isOpen={isOpen}
config={authConfig}
showEmailModal={true} // Shows "Continue with Email" button
modalTabs={true} // Enables tabs within the email modal
/>Features:
- Ultra Compact: No email fields visible initially
- On-Demand Access: Click "Continue with Email" to show modal
- Modal Tabs: Login/Register tabs within the modal
- Clean UI: Social providers and wallets take priority
- Professional Modal: Smooth animations and backdrop
- Form Validation: Full validation within modal context
Tabbed Authentication
For better user experience and space efficiency, enable tabbed authentication:
<AuthModal
isOpen={isOpen}
config={authConfig}
showTabs={true}
defaultTab="login"
/>Features:
- Space Efficient: Login and register forms in separate tabs
- Context Preservation: Email maintained when switching between tabs
- Smooth Transitions: Professional animations between tabs
- Error Management: Errors clear when switching tabs
- Responsive Design: Optimized for all screen sizes
Display Modes
Modal Mode
import { useState } from 'react';
import { AuthModal } from 'authweb3';
function App() {
const [isOpen, setIsOpen] = useState(false);
const handleAuthSuccess = (user) => {
console.log('User authenticated:', user);
setIsOpen(false);
// Redirect or update app state
};
return (
<>
<button
onClick={() => setIsOpen(true)}
style={{
padding: '12px 24px',
backgroundColor: '#000000',
color: '#ffffff',
border: 'none',
borderRadius: '8px',
cursor: 'pointer'
}}
>
Sign In
</button>
<AuthModal
isOpen={isOpen}
onClose={() => setIsOpen(false)}
config={authConfig}
theme={customTheme}
onSuccess={handleAuthSuccess}
onError={(error) => console.error('Auth error:', error)}
validationRules={{
email: { required: true, pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ },
password: { required: true, minLength: 8 }
}}
supportedWallets={['metamask', 'phantom', 'solflare']}
socialProviders={['google', 'github']}
/>
</>
);
}Page Mode
import { AuthPage } from 'authweb3';
function LoginPage() {
const handleAuthSuccess = (user) => {
console.log('User authenticated:', user);
// Redirect to dashboard or update app state
};
const handleAuthError = (error) => {
console.error('Authentication error:', error);
};
return (
<AuthPage
config={authConfig}
theme={customTheme}
title="Welcome to MyApp"
subtitle="Please sign in to continue"
onSuccess={handleAuthSuccess}
onError={handleAuthError}
validationRules={{
email: { required: true, pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ },
password: { required: true, minLength: 8 }
}}
supportedWallets={['metamask', 'phantom', 'solflare']}
socialProviders={['google', 'github']}
/>
);
}Inline Mode
import { LoginForm, WalletConnect } from 'authweb3';
function App() {
return (
<div className="auth-container">
<LoginForm
config={authConfig}
theme={customTheme}
onLogin={handleLogin}
onRegister={handleRegister}
/>
<WalletConnect
theme={customTheme}
onConnect={handleWalletConnect}
supportedWallets={['metamask', 'phantom', 'solflare']}
/>
</div>
);
}Form Validation
AuthWeb3 includes comprehensive form validation:
const validationRules = {
email: {
required: true,
pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
minLength: 5,
maxLength: 254
},
password: {
required: true,
minLength: 8,
pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/,
custom: (value) => {
if (value.includes('password')) {
return 'Password cannot contain the word "password"';
}
return null;
}
}
};
<LoginForm
validationRules={validationRules}
onValidationError={(errors) => {
console.log('Validation errors:', errors);
}}
/>Database Integration
Firebase Integration
import { initializeApp } from 'firebase/app';
import { getFirestore, collection, doc, setDoc, getDoc, query, where, getDocs } from 'firebase/firestore';
const firebaseConfig = {
// Your Firebase config
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const authConfig: AuthConfig = {
jwtSecret: process.env.JWT_SECRET!,
jwtExpiresIn: '7d',
database: {
createUser: async (userData) => {
const userRef = doc(collection(db, 'users'));
const user = {
id: userRef.id,
...userData,
createdAt: new Date(),
};
await setDoc(userRef, user);
return user;
},
findUserByEmail: async (email) => {
const q = query(collection(db, 'users'), where('email', '==', email));
const querySnapshot = await getDocs(q);
if (!querySnapshot.empty) {
return querySnapshot.docs[0].data();
}
return null;
},
findUserByWallet: async (walletAddress) => {
const q = query(collection(db, 'users'), where('walletAddress', '==', walletAddress));
const querySnapshot = await getDocs(q);
if (!querySnapshot.empty) {
return querySnapshot.docs[0].data();
}
return null;
},
updateUser: async (id, updates) => {
const userRef = doc(db, 'users', id);
await setDoc(userRef, updates, { merge: true });
return { id, ...updates };
},
},
};MongoDB Integration
import { MongoClient } from 'mongodb';
const client = new MongoClient(process.env.MONGODB_URI!);
const db = client.db('your-database');
const authConfig: AuthConfig = {
jwtSecret: process.env.JWT_SECRET!,
jwtExpiresIn: '7d',
database: {
createUser: async (userData) => {
const collection = db.collection('users');
const user = {
id: new ObjectId().toString(),
...userData,
createdAt: new Date(),
};
await collection.insertOne(user);
return user;
},
findUserByEmail: async (email) => {
const collection = db.collection('users');
return await collection.findOne({ email });
},
findUserByWallet: async (walletAddress) => {
const collection = db.collection('users');
return await collection.findOne({ walletAddress });
},
updateUser: async (id, updates) => {
const collection = db.collection('users');
await collection.updateOne(
{ id },
{ $set: updates }
);
return { id, ...updates };
},
},
};Environment Configuration
Create a .env file in your project root (see .env.example for reference):
# JWT Configuration
JWT_SECRET=your-super-secret-jwt-key-here
JWT_EXPIRES_IN=7d
# Database Configuration
MONGODB_URI=mongodb://localhost:27017/your-database
FIREBASE_API_KEY=your-firebase-api-key
FIREBASE_AUTH_DOMAIN=your-project.firebaseapp.com
FIREBASE_PROJECT_ID=your-project-id
# Wallet Configuration
SUPPORTED_WALLETS=metamask,phantom,solflare
INFURA_PROJECT_ID=your-infura-project-id
# UI Customization
BRAND_COLOR=#your-brand-color
LOGO_URL=https://your-domain.com/logo.pngLoad environment variables:
import dotenv from 'dotenv';
dotenv.config();
const authConfig: AuthConfig = {
jwtSecret: process.env.JWT_SECRET!,
jwtExpiresIn: process.env.JWT_EXPIRES_IN || '7d',
// ... other config
};AuthBuilder Tool
AuthWeb3 includes a visual builder tool for customizing your authentication interface:
Features
- Visual Theme Editor: Customize colors, fonts, and spacing in real-time
- Logo Upload: Add your brand logo with drag-and-drop
- Social Configuration: Enable/disable social providers and configure API keys
- Live Preview: See changes instantly in a preview pane
- Connection Testing: Test social API connections before deployment
- Export Configuration: Generate production-ready configuration files
Usage
npm run demoThen click the "🎨 Builder" button in the top-right corner.
Builder Interface
- Design Tab: Customize branding and colors
- Social Tab: Configure social authentication providers
- Preview Tab: See real-time preview of your authentication UI
Exporting Configuration
The builder generates a JSON configuration file that you can use in your production app:
import config from './auth-config.json';
const authConfig = {
// Your database config
};
<AuthModal
config={authConfig}
theme={config.theme}
socialProviders={config.socialProviders}
/>Advanced Usage
Custom Authentication Flow
import { useAuth, useWallet } from 'authweb3';
function CustomAuthFlow() {
const auth = useAuth(authConfig);
const wallet = useWallet();
const handleSocialLogin = async (provider: 'google' | 'github') => {
// Implement social login logic
const result = await auth.loginWithSocial(provider);
if (result.success) {
// Handle success
}
};
const handleWalletAuth = async () => {
if (wallet.isConnected) {
const signature = await wallet.signMessage('Sign in to MyApp');
await auth.loginWithWallet(wallet.address!, signature);
}
};
return (
<div>
<button onClick={() => handleSocialLogin('google')}>
Continue with Google
</button>
<button onClick={() => handleSocialLogin('github')}>
Continue with GitHub
</button>
<button onClick={handleWalletAuth} disabled={!wallet.isConnected}>
Sign in with Wallet
</button>
</div>
);
}Multi-step Authentication
function MultiStepAuth() {
const [step, setStep] = useState<'email' | 'verify' | 'complete'>('email');
const auth = useAuth(authConfig);
const handleEmailSubmit = async (email: string) => {
await auth.sendVerificationCode(email);
setStep('verify');
};
const handleVerification = async (code: string) => {
const result = await auth.verifyCode(code);
if (result.success) {
setStep('complete');
}
};
// Render different components based on step
}API Reference
useAuth(config)
React hook for managing authentication state.
Parameters:
config: AuthConfig object with JWT settings and database operations
Returns:
user: Current authenticated user or nullisAuthenticated: Boolean indicating if user is logged inisLoading: Boolean indicating if auth operation is in progresserror: Error message or nullregister(credentials): Function to register new userlogin(credentials): Function to login userloginWithWallet(walletAddress): Function to login with walletlogout(): Function to logout user
useWallet(config?)
React hook for managing wallet connection.
Parameters:
config: Optional WalletConfig object
Returns:
address: Connected wallet address or nullisConnected: Boolean indicating if wallet is connectedisConnecting: Boolean indicating if connection is in progresserror: Error message or nullconnect(): Function to connect walletdisconnect(): Function to disconnect walletsignMessage(message): Function to sign a message
Components
LoginForm
Form component for email/password authentication.
Props:
onLogin: Function called on login attemptonRegister: Function called on register attemptisLoading: Loading stateerror: Error message
WalletConnect
Component for wallet connection UI.
Props:
onConnect: Function called on connect attemptonDisconnect: Function called on disconnectaddress: Wallet addressisConnected: Connection stateisConnecting: Connecting stateerror: Error message
Database Integration
The library is designed to work with any database. You need to implement the following database operations in your AuthConfig:
createUser(userData): Create a new userfindUserByEmail(email): Find user by emailfindUserByWallet(walletAddress): Find user by wallet addressupdateUser(id, updates): Update user data
Security & Database Integration
Security Features
AuthWeb3 implements industry-standard security practices:
- Password Hashing: Uses bcryptjs with salt rounds for secure password storage
- JWT Tokens: Stateless authentication with configurable expiration
- Wallet Verification: Server-side signature validation for Web3 authentication
- Rate Limiting: Built-in protection against brute force attacks
- Input Validation: Comprehensive validation with customizable rules
- SQL Injection Protection: Parameterized queries in database operations
Database Compatibility
AuthWeb3 works with any database through configurable callbacks. Here are examples for popular databases:
Firebase Firestore
import { initializeApp } from 'firebase/app';
import { getFirestore, doc, setDoc, getDoc } from 'firebase/firestore';
const firebaseApp = initializeApp(firebaseConfig);
const db = getFirestore(firebaseApp);
const authConfig: AuthConfig = {
jwtSecret: process.env.JWT_SECRET!,
jwtExpiresIn: '7d',
database: {
createUser: async (userData) => {
const userRef = doc(db, 'users', Date.now().toString());
await setDoc(userRef, { ...userData, createdAt: new Date() });
return { id: userRef.id, ...userData, createdAt: new Date() };
},
findUserByEmail: async (email) => {
// Implement Firebase query
return null;
},
findUserByWallet: async (walletAddress) => {
// Implement Firebase query
return null;
},
updateUser: async (id, updates) => {
// Implement Firebase update
return { id, ...updates };
}
}
};MongoDB
import { MongoClient } from 'mongodb';
const client = new MongoClient(process.env.MONGODB_URI!);
const db = client.db('authweb3');
const authConfig: AuthConfig = {
jwtSecret: process.env.JWT_SECRET!,
jwtExpiresIn: '7d',
database: {
createUser: async (userData) => {
const result = await db.collection('users').insertOne({
...userData,
createdAt: new Date()
});
return { id: result.insertedId.toString(), ...userData, createdAt: new Date() };
},
findUserByEmail: async (email) => {
const user = await db.collection('users').findOne({ email });
return user ? { ...user, id: user._id.toString() } : null;
},
findUserByWallet: async (walletAddress) => {
const user = await db.collection('users').findOne({ walletAddress });
return user ? { ...user, id: user._id.toString() } : null;
},
updateUser: async (id, updates) => {
await db.collection('users').updateOne(
{ _id: new ObjectId(id) },
{ $set: updates }
);
return { id, ...updates };
}
}
};PostgreSQL
import { Pool } from 'pg';
const pool = new Pool({
connectionString: process.env.DATABASE_URL
});
const authConfig: AuthConfig = {
jwtSecret: process.env.JWT_SECRET!,
jwtExpiresIn: '7d',
database: {
createUser: async (userData) => {
const result = await pool.query(
'INSERT INTO users (email, password, wallet_address, created_at) VALUES ($1, $2, $3, $4) RETURNING id',
[userData.email, userData.password, userData.walletAddress, new Date()]
);
return { id: result.rows[0].id.toString(), ...userData, createdAt: new Date() };
},
findUserByEmail: async (email) => {
const result = await pool.query('SELECT * FROM users WHERE email = $1', [email]);
return result.rows[0] || null;
},
findUserByWallet: async (walletAddress) => {
const result = await pool.query('SELECT * FROM users WHERE wallet_address = $1', [walletAddress]);
return result.rows[0] || null;
},
updateUser: async (id, updates) => {
const setClause = Object.keys(updates).map((key, i) => `${key} = $${i + 2}`).join(', ');
const values = [...Object.values(updates), id];
await pool.query(`UPDATE users SET ${setClause} WHERE id = $${values.length}`, values);
return { id, ...updates };
}
}
};Environment Security
Always use environment variables for sensitive data:
# Required
JWT_SECRET=your-super-secure-random-jwt-secret-here
DATABASE_URL=your-database-connection-string
# Optional but recommended
JWT_EXPIRES_IN=7d
BCRYPT_ROUNDS=12
RATE_LIMIT_WINDOW=15
RATE_LIMIT_MAX_REQUESTS=100Additional Security Measures
- HTTPS Only: Always use HTTPS in production
- CORS Configuration: Restrict origins in production
- Session Management: Implement proper session handling
- Audit Logging: Log authentication attempts
- Two-Factor Authentication: Consider adding 2FA support
About Viainti
AuthWeb3 is developed and maintained by Viainti, a leading Web3 development company specializing in blockchain applications, DeFi protocols, and modern web technologies.
Our Expertise
- 🚀 Web3 Development: Smart contracts, DeFi, NFT platforms
- ⚛️ React/Next.js: Modern web applications and PWAs
- 🔐 Authentication Systems: Secure auth for Web3 and traditional apps
- 🎨 UI/UX Design: Professional interfaces for blockchain products
- 📱 Cross-platform: Web, mobile, and desktop applications
Connect with Viainti
- 🌐 Website: viainti.com
- 💼 LinkedIn: Viainti
- 🐙 GitHub: viainti
- 📧 Email: [email protected]
Services
- Custom Web3 application development
- Blockchain integration consulting
- Smart contract development and auditing
- DeFi protocol development
- NFT marketplace creation
- Authentication system implementation
Built with ❤️ by Viainti - Expert Web3 Development
License
MIT - see LICENSE file for details
