Seedhe Auth Docs

← Back to Home

Getting Started

Seedhe Auth is a lightweight Node.js authentication library that provides OAuth integration, JWT authentication, and multiple database support for Express.js applications.

OAuth Integration

Google and GitHub OAuth authentication with easy setup

Multiple Databases

MongoDB, PostgreSQL, and in-memory storage support

Express.js Ready

Drop-in Express.js integration with middleware support

Installation

Install Seedhe Auth using npm or yarn:

Installation Command
1npm install seedhe-auth

Configuration

Set up your environment variables and basic configuration:

Environment Variables
1# Environment Variables
2PORT=5000
3JWT_SECRET=your_generated_jwt_secret
4
5# Database Configuration
6DB_TYPE="mongo" # or "postgres" or "memory"
7MONGO_URI=mongodb://localhost:27017/seedhe-auth
8POSTGRES_URI=postgresql://username:password@localhost:5432/seedhe-auth
9
10# OAuth Configuration
11GOOGLE_CLIENT_ID=your_google_client_id
12GOOGLE_CLIENT_SECRET=your_google_client_secret
13GOOGLE_CALLBACK_URL=http://localhost:5000/auth/google/callback
14
15GITHUB_CLIENT_ID=your_github_client_id
16GITHUB_CLIENT_SECRET=your_github_client_secret
17GITHUB_CALLBACK_URL=http://localhost:5000/auth/github/callback
Basic Express.js Setup
1import express from 'express';
2import cookieParser from 'cookie-parser';
3import { initAuth } from 'seedhe-auth';
4
5const app = express();
6
7// Middleware
8app.use(express.json());
9app.use(cookieParser());
10
11// Initialize Seedhe Auth
12const { authService, authRoutes } = await initAuth();
13
14// Use auth routes
15app.use('/auth', authRoutes);
16
17// Protected route example
18app.get('/api/profile', (req, res) => {
19  const token = req.cookies.token;
20  
21  if (!token) {
22    return res.status(401).json({ message: 'Not authenticated' });
23  }
24  
25  try {
26    const decoded = jwt.verify(token, process.env.JWT_SECRET);
27    res.json({
28      id: decoded.id,
29      provider: decoded.provider,
30      name: decoded.name,
31      email: decoded.email
32    });
33  } catch (error) {
34    res.status(403).json({ message: 'Invalid token' });
35  }
36});
37
38app.listen(5000, () => {
39  console.log('Server running on port 5000');
40});

OAuth Setup

Configure Google and GitHub OAuth providers:

OAuth Provider Configuration
1// Google OAuth Setup
2// 1. Go to Google Cloud Console
3// 2. Create a new project or select existing
4// 3. Enable Google+ API
5// 4. Create OAuth 2.0 credentials
6// 5. Add authorized redirect URIs:
7//    http://localhost:5000/auth/google/callback
8
9// GitHub OAuth Setup
10// 1. Go to GitHub Settings > Developer settings
11// 2. Create new OAuth App
12// 3. Set Authorization callback URL:
13//    http://localhost:5000/auth/github/callback
14
15// Environment variables
16GOOGLE_CLIENT_ID=your_google_client_id
17GOOGLE_CLIENT_SECRET=your_google_client_secret
18GOOGLE_CALLBACK_URL=http://localhost:5000/auth/google/callback
19
20GITHUB_CLIENT_ID=your_github_client_id
21GITHUB_CLIENT_SECRET=your_github_client_secret
22GITHUB_CALLBACK_URL=http://localhost:5000/auth/github/callback

API Reference

Available authentication endpoints and middleware:

Authentication Endpoints
1// Available Authentication Endpoints
2
3// Google OAuth
4GET  /auth/google          // Initiate Google OAuth
5GET  /auth/google/callback // Google OAuth callback
6
7// GitHub OAuth  
8GET  /auth/github          // Initiate GitHub OAuth
9GET  /auth/github/callback // GitHub OAuth callback
10
11// Logout
12POST /auth/logout          // Logout user
13
14// User Info
15GET  /auth/user           // Get current user info
16
17// Example usage:
18// Redirect to Google OAuth
19window.location.href = '/auth/google';
20
21// Redirect to GitHub OAuth  
22window.location.href = '/auth/github';
Middleware Usage
1import { authMiddleware } from 'seedhe-auth';
2
3// Protect routes with authentication
4app.get('/api/dashboard', authMiddleware, (req, res) => {
5  // req.user contains user information
6  res.json({
7    message: 'Welcome to dashboard',
8    user: req.user
9  });
10});
11
12// Optional: Custom authentication check
13app.get('/api/profile', (req, res) => {
14  const token = req.cookies.token;
15  
16  if (!token) {
17    return res.status(401).json({ message: 'Authentication required' });
18  }
19  
20  // Token validation logic here
21  // ...

Examples

Real-world examples and integration patterns:

Frontend Integration (React)
1// Frontend Integration Examples
2
3// React Component
4import { useEffect, useState } from 'react';
5
6function LoginButton() {
7  const [user, setUser] = useState(null);
8
9  useEffect(() => {
10    // Check if user is logged in
11    fetch('/auth/user')
12      .then(res => res.json())
13      .then(data => setUser(data))
14      .catch(() => setUser(null));
15  }, []);
16
17  const handleLogin = (provider) => {
18    window.location.href = `/auth/${provider}`;
19  };
20
21  const handleLogout = () => {
22    fetch('/auth/logout', { method: 'POST' })
23      .then(() => setUser(null));
24  };
25
26  return (
27    <div>
28      {user ? (
29        <div>
30          <p>Welcome, {user.name}!</p>
31          <button onClick={handleLogout}>Logout</button>
32        </div>
33      ) : (
34        <div>
35          <button onClick={() => handleLogin('google')}>
36            Login with Google
37          </button>
38          <button onClick={() => handleLogin('github')}>
39            Login with GitHub
40          </button>
41        </div>
42      )}
43    </div>
44  );
45}
Database Configuration
1// MongoDB Configuration
2DB_TYPE="mongo"
3MONGO_URI=mongodb://localhost:27017/seedhe-auth
4
5// PostgreSQL Configuration
6DB_TYPE="postgres"
7POSTGRES_URI=postgresql://username:password@localhost:5432/seedhe-auth
8
9// In-Memory Configuration (for development)
10DB_TYPE="memory"
11
12// Database connection is handled automatically
13// No additional setup required

Troubleshooting

Common issues and their solutions:

OAuth Callback Errors

Make sure your OAuth callback URLs match exactly in your provider settings.

  • Google: http://localhost:5000/auth/google/callback
  • GitHub: http://localhost:5000/auth/github/callback
Database Connection Issues

Ensure your database connection strings are correct and the database is running.

Error Handling Examples
1// Error Handling Examples
2
3// 1. Authentication Error Middleware
4app.use((err, req, res, next) => {
5  if (err.name === 'UnauthorizedError') {
6    return res.status(401).json({ 
7      message: 'Invalid token' 
8    });
9  }
10  next(err);
11});
12
13// 2. OAuth Error Handling
14app.get('/auth/google/callback', (req, res) => {
15  // Handle OAuth errors
16  if (req.query.error) {
17    return res.redirect('/login?error=oauth_error');
18  }
19  // ... rest of callback logic
20});
21
22// 3. Database Connection Error
23const { authService, authRoutes } = await initAuth().catch(err => {
24  console.error('Failed to initialize auth:', err);
25  process.exit(1);
26});