Package Exports
- lightning-auth-and-payment
- lightning-auth-and-payment/dev
- lightning-auth-and-payment/nextjs
Readme
โก Lightning Auth & Payment
The complete Lightning Network authentication and payment solution for modern web applications
Build Lightning Network-powered applications with ease. From simple single-page shops to complex eCommerce platforms, Lightning Auth & Payment provides everything you need for Lightning Network integration.
๐ Quick Start
For AI Agents (Cursor, etc.)
Use our AI Setup Guide - copy and paste a single prompt to automatically configure everything.
Manual Installation
npm install lightning-auth-and-paymentโก Super Quick Setup (5 minutes)
- Install the library:
npm install lightning-auth-and-payment- Create your API routes (copy-paste ready):
# Create the directory structure
mkdir -p src/app/api/auth/{lnurl,callback,status,logout}
mkdir -p src/app/api/userCopy the route files from the examples above - each route is only 15-25 lines!
Add environment variables:
SESSION_SECRET=your-super-secret-session-key-here
NEXT_PUBLIC_APP_URL=https://localhost:3443- Start development:
npm run dev:lightningThat's it! Your Lightning authentication is ready. ๐
๐ฏ Core Features
โ Lightning Authentication
- LNURL-auth protocol - Industry standard Lightning authentication
- QR Code generation - Works with any Lightning wallet
- Session management - Secure JWT-based sessions
- Wallet compatibility - Alby, Phoenix, Breez, Zeus, and more
โ Lightning Payments
- BTCPay Server integration - Real Lightning invoices
- Automatic polling - Payment status detection
- QR Code payments - Mobile wallet support
- Success handling - User-friendly payment confirmation
โ Development Experience
- Local HTTPS server - SSL certificates for wallet compatibility
- TypeScript support - Full type safety
- React components - Ready-to-use UI components
- Hot reload - Fast development iteration
๐ ๏ธ Development Server
The library includes a built-in development server for local HTTPS development with Lightning authentication support.
Quick Start with Development Server
# Install the library
npm install lightning-auth-and-payment
# Create a simple development script
echo 'import { LightningDevServer } from "lightning-auth-and-payment/dev";
const server = new LightningDevServer();
server.start();' > dev-server.mjs
# Run the development server
node dev-server.mjsAdvanced Configuration
import { LightningDevServer } from 'lightning-auth-and-payment/dev';
const devServer = new LightningDevServer({
nextPort: 3000, // Next.js development server port
httpsPort: 3443, // HTTPS proxy port
certsDir: 'certs', // SSL certificates directory
projectRoot: process.cwd(),
verbose: true, // Enable detailed logging
});
await devServer.start();Features
- ๐ Automatic SSL certificates - Uses mkcert for trusted local certificates
- ๐ Hot reload support - Works with Next.js development server
- ๐ฑ Mobile wallet compatibility - HTTPS required for Lightning wallets
- ๐ CORS handling - Pre-configured for Lightning wallet requests
- โก Lightning-ready - Optimized for Lightning Network development
Package.json Integration
{
"scripts": {
"dev": "next dev",
"dev:lightning": "node scripts/dev-server.mjs",
"dev:https": "node scripts/dev-server.mjs"
}
}๐ฆ What's Included
๐ Authentication
import { LightningAuth, useAuth } from 'lightning-auth-and-payment';
// Server-side authentication
const auth = new LightningAuth({
sessionSecret: process.env.SESSION_SECRET!,
lnurlStore: new MemoryLnurlStore(),
});
// Client-side authentication
const { isAuthenticated, login, logout, user } = useAuth();๐ณ Payments
import { BTCPayPaymentModal, createBTCPayService } from 'lightning-auth-and-payment';
// Payment modal component
<BTCPayPaymentModal
isOpen={showPayment}
onClose={() => setShowPayment(false)}
amount={1000}
description="Purchase item"
onPaymentSuccess={() => console.log('Payment successful!')}
autoCloseDelay={3000}
successMessage="Payment confirmed!"
/>
// BTCPay service
const btcpayService = createBTCPayService();
const invoice = await btcpayService.createInvoice({
amount: 1000,
currency: 'SATS',
description: 'Purchase item',
});๐จ UI Components
import {
AuthHeader,
BTCPayPaymentModal,
Button,
Card
} from 'lightning-auth-and-payment';
// Pre-built components with Lightning Network styling
<AuthHeader />
<Button onClick={handlePayment}>Buy Now</Button>
<Card>Your content here</Card>๐ ๏ธ Environment Setup
Create .env.local:
# Session Configuration
SESSION_SECRET=your-super-secret-session-key-here-make-it-long-and-random
SESSION_COOKIE_DOMAIN=localhost
# BTCPay Server Configuration (required for payments)
BTCPAY_HOST=https://your-btcpay-server.com
BTCPAY_STORE_ID=your-store-id
BTCPAY_API_KEY=your-api-key
BTCPAY_WEBHOOK_SECRET=your-webhook-secret
# Application Configuration
NEXT_PUBLIC_APP_URL=https://localhost:3443
NODE_ENV=development๐๏ธ API Routes
The library provides complete API route utilities that eliminate boilerplate code:
โจ Simplified Authentication Routes
// /api/auth/lnurl/route.ts - LNURL generation
import { NextRequest, NextResponse } from 'next/server';
import { handleLnurlRequest, getAuthCorsHeaders } from 'lightning-auth-and-payment';
import { lnurlStore } from '@/lib/lnurl-store';
export async function GET(request: NextRequest) {
const result = await handleLnurlRequest(lnurlStore, request);
const response = NextResponse.json(result);
// Apply CORS headers
const corsHeaders = getAuthCorsHeaders();
Object.entries(corsHeaders).forEach(([key, value]) => {
response.headers.set(key, value);
});
return response;
}// /api/auth/callback/route.ts - Authentication callback
import { NextRequest, NextResponse } from 'next/server';
import { handleAuthCallbackRequest, getAuthCorsHeaders } from 'lightning-auth-and-payment';
import { lnurlStore } from '@/lib/lnurl-store';
import { db } from '@/lib/db';
export async function GET(request: NextRequest) {
const result = await handleAuthCallbackRequest(lnurlStore, db, request);
const response = NextResponse.json(result);
// Apply CORS headers
const corsHeaders = getAuthCorsHeaders();
Object.entries(corsHeaders).forEach(([key, value]) => {
response.headers.set(key, value);
});
return response;
}// /api/auth/status/route.ts - Authentication status
import { NextRequest, NextResponse } from 'next/server';
import { handleAuthStatusRequest } from 'lightning-auth-and-payment';
import { lnurlStore } from '@/lib/lnurl-store';
import { cookies } from 'next/headers';
export async function GET(request: NextRequest) {
const result = await handleAuthStatusRequest(lnurlStore, request);
// Handle cookie setting if login was completed
if (result.setCookie) {
const cookieStore = await cookies();
cookieStore.set(result.setCookie.name, result.setCookie.value, result.setCookie.config);
}
const { setCookie, ...responseData } = result;
return NextResponse.json(responseData, result.statusCode ? { status: result.statusCode } : {});
}// /api/user/route.ts - User data
import { NextResponse } from 'next/server';
import { handleUserRequest } from 'lightning-auth-and-payment';
import { db } from '@/lib/db';
import { cookies } from 'next/headers';
export async function GET() {
const cookieStore = await cookies();
const sessionToken = cookieStore.get('session')?.value;
const result = await handleUserRequest(db, sessionToken);
return NextResponse.json(result, result.statusCode ? { status: result.statusCode } : {});
}// /api/auth/logout/route.ts - Logout
import { NextResponse } from 'next/server';
import { handleLogoutRequest, getAuthCorsHeaders } from 'lightning-auth-and-payment';
export async function POST() {
const result = handleLogoutRequest();
const response = NextResponse.json(result);
// Clear session cookie
response.cookies.set(result.clearCookie.name, result.clearCookie.value, result.clearCookie.config);
// Apply CORS headers
const corsHeaders = getAuthCorsHeaders();
Object.entries(corsHeaders).forEach(([key, value]) => {
response.headers.set(key, value);
});
return response;
}๐ฏ Benefits of New API Route Utilities
- โ Eliminates 200+ lines of boilerplate per project
- โ Consistent authentication logic across all endpoints
- โ Automatic CORS handling for wallet compatibility
- โ Built-in error handling and status codes
- โ Cookie management with proper configuration
- โ TypeScript support with full type safety
- โ Easy to customize and extend
๐ณ Payment Routes
// Payment routes use BTCPay utilities
import {
handleBTCPayInvoiceCreation,
handleBTCPayInvoiceStatus,
handleBTCPayWebhook
} from 'lightning-auth-and-payment';๐ง Development Server
Start the Lightning development server with HTTPS support:
npm run dev:lightningThis provides:
- โ HTTPS with trusted SSL certificates
- โ Wallet-compatible LNURL endpoints
- โ Hot reload and debugging
- โ Automatic certificate management
๐ฑ Wallet Compatibility
Desktop Wallets
- Alby - Browser extension (recommended for development)
- Phoenix - Desktop Lightning wallet
- Breez - Mobile/desktop Lightning wallet
Mobile Wallets
- Phoenix - iOS/Android Lightning wallet
- Breez - Mobile Lightning wallet
- Zeus - Advanced Lightning wallet
- Wallet of Satoshi - Simple Lightning wallet
๐จ UI Components
Authentication Components
import { AuthHeader, useAuth } from 'lightning-auth-and-payment';
function MyApp() {
const { isAuthenticated, login, logout } = useAuth();
return (
<AuthHeader
onLogin={login}
onLogout={logout}
isAuthenticated={isAuthenticated}
/>
);
}Payment Components
import { BTCPayPaymentModal } from 'lightning-auth-and-payment';
function PaymentButton() {
const [showPayment, setShowPayment] = useState(false);
return (
<BTCPayPaymentModal
isOpen={showPayment}
onClose={() => setShowPayment(false)}
amount={1000}
description="Purchase item"
onPaymentSuccess={() => {
// Handle successful payment
setShowPayment(false);
}}
autoCloseDelay={3000}
successMessage="Payment confirmed!"
/>
);
}Utility Components
import {
Button,
Card,
Badge,
Dialog
} from 'lightning-auth-and-payment';
// Pre-styled components with Lightning Network theming
<Button variant="primary">Lightning Button</Button>
<Card>Lightning Card</Card>
<Badge variant="success">Success</Badge>๐ Hooks
Authentication Hooks
import {
useAuth,
useLightningAuth,
useSession
} from 'lightning-auth-and-payment';
// Enhanced authentication with all features
const { isAuthenticated, login, logout, user, isLoading } = useAuth();
// Basic Lightning authentication
const { lnurl, showModal, login, closeModal } = useLightningAuth();
// Session management
const { session, refreshSession } = useSession();Payment Hooks
import {
useBTCPayPayment,
useLightningPayment
} from 'lightning-auth-and-payment';
// BTCPay Server payments
const {
paymentState,
createInvoice,
copyBolt11
} = useBTCPayPayment();
// Basic Lightning payments
const {
createPayment,
paymentStatus,
resetPayment
} = useLightningPayment();Utility Hooks
import {
useCopyToClipboard,
useCountdown,
useDebounce,
useLocalStorage
} from 'lightning-auth-and-payment';
// Copy to clipboard
const { copied, copy } = useCopyToClipboard();
// Countdown timer
const { timeLeft, isExpired } = useCountdown(targetDate);
// Debounced values
const debouncedValue = useDebounce(value, 500);
// Local storage
const [storedValue, setStoredValue] = useLocalStorage('key', defaultValue);๐ช E-Commerce Features
import {
ECommerceManager,
OrderManager,
ProductManager
} from 'lightning-auth-and-payment';
// E-commerce management
const ecommerce = new ECommerceManager();
const orders = new OrderManager();
const products = new ProductManager();๐งช Testing
import {
createTestAuth,
createTestStore,
mockUser,
mockInvoice
} from 'lightning-auth-and-payment/testing';
// Test utilities
const testAuth = createTestAuth();
const testStore = createTestStore();
const user = mockUser();
const invoice = mockInvoice();๐ Examples
Check out the examples directory for complete implementations:
- Next.js App Router - Modern Next.js 13+ with App Router
- Express.js - Traditional Express.js server
- E-commerce - Complete shopping cart implementation
๐ค Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
๐ License
MIT License - see LICENSE for details.
๐ Support
- Documentation: AI Setup Guide
- Issues: GitHub Issues
- Discussions: GitHub Discussions
๐ฏ Roadmap
- WebLN integration for browser wallets
- Lightning Address support
- Multi-currency support
- Advanced payment flows
- Mobile app templates
Built with โก for the Lightning Network