Quick Start
Get started with BinoAuth in your application in just a few minutes. This guide shows you how to integrate authentication using our SDKs.
Choose Your Integration
Select the guide that matches your application type:
- React Application - For React SPAs
- Next.js Application - For Next.js full-stack apps
- Node.js API - For backend APIs
- Existing Authentication - Migrate from existing auth
React Integration
1. Install the SDK
npm install @binoauth/react2. Set Up the Provider
Wrap your app with the AuthProvider:
// app/layout.tsx or main.tsx
import { AuthProvider } from '@binoauth/react';
function App() {
return (
<AuthProvider
clientId="your-client-id"
issuer="http://localhost:8000"
redirectUri="http://localhost:3000/auth/callback"
scope="openid profile email"
>
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/auth/callback" element={<AuthCallback />} />
<Route path="/dashboard" element={<Dashboard />} />
</Routes>
</Router>
</AuthProvider>
);
}3. Create Auth Callback Page
// pages/auth/callback.tsx
import { AuthCallbackPage } from '@binoauth/react';
export function AuthCallback() {
return <AuthCallbackPage />;
}4. Add Login/Logout
// components/AuthButton.tsx
import { useAuth } from '@binoauth/react';
export function AuthButton() {
const { user, login, logout, loading } = useAuth();
if (loading) {
return <div>Loading...</div>;
}
if (user) {
return (
<div>
<span>Welcome, {user.name}!</span>
<button onClick={() => logout()}>
Logout
</button>
</div>
);
}
return (
<button onClick={() => login()}>
Login
</button>
);
}5. Protect Routes
// components/ProtectedRoute.tsx
import { ProtectedRoute } from '@binoauth/react';
// Usage
<Route
path="/dashboard"
element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
}
/>Next.js Integration
1. Install the SDK
npm install @binoauth/nextjs2. Configure Authentication
Create an auth configuration file:
// lib/auth.config.ts
export const authConfig = {
clientId: process.env.BINOAUTH_CLIENT_ID!,
clientSecret: process.env.BINOAUTH_CLIENT_SECRET!,
issuer: process.env.BINOAUTH_ISSUER!,
redirectUri: process.env.BINOAUTH_REDIRECT_URI!,
authSecret: process.env.AUTH_SECRET!,
scope: 'openid profile email',
};3. Add Environment Variables
# .env.local
BINOAUTH_CLIENT_ID=your-client-id
BINOAUTH_CLIENT_SECRET=your-client-secret
BINOAUTH_ISSUER=http://localhost:8000
BINOAUTH_REDIRECT_URI=http://localhost:3000/api/auth/callback
AUTH_SECRET=your-auth-secret4. Create API Routes
// app/api/auth/[...oauth]/route.ts
import { createAuth } from '@binoauth/nextjs';
import { authConfig } from '@/lib/auth.config';
const auth = createAuth(authConfig);
export const { GET, POST } = auth.handler;5. Add Middleware
// middleware.ts
import { createAuth } from '@binoauth/nextjs';
import { authConfig } from './lib/auth.config';
const auth = createAuth(authConfig);
export default auth.withAuth;
export const config = {
matcher: ['/dashboard/:path*', '/profile/:path*'],
};6. Use in Components
// app/components/UserProfile.tsx
import { useAuth } from '@binoauth/nextjs';
export function UserProfile() {
const { user, isLoading, isAuthenticated } = useAuth();
if (isLoading) return <p>Loading...</p>;
if (!isAuthenticated) return <p>Not authenticated</p>;
return (
<div>
<h1>Welcome, {user?.name}!</h1>
<img src={user?.picture} alt="Profile" />
<p>{user?.email}</p>
</div>
);
}7. Server-Side Usage
// app/dashboard/page.tsx
import { createAuth } from '@binoauth/nextjs';
import { authConfig } from '@/lib/auth.config';
import { redirect } from 'next/navigation';
const auth = createAuth(authConfig);
export default async function Dashboard() {
const user = await auth.getCurrentUser();
if (!user) {
redirect('/api/auth/login');
}
return (
<div>
<h1>Dashboard</h1>
<p>Welcome back, {user.name}!</p>
</div>
);
}Node.js Integration
1. Install the SDK
npm install binoauth2. Configure the Client
// config/auth.ts
import { BinoAuthOAuth } from 'binoauth';
export const authClient = new BinoAuthOAuth({
clientId: process.env.BINOAUTH_CLIENT_ID!,
clientSecret: process.env.BINOAUTH_CLIENT_SECRET!,
issuer: process.env.BINOAUTH_ISSUER!,
redirectUri: process.env.BINOAUTH_REDIRECT_URI!,
});3. Create Auth Routes
// routes/auth.ts
import express from 'express';
import { authClient } from '../config/auth';
const router = express.Router();
// Login endpoint
router.get('/login', async (req, res) => {
const { url, state } = await authClient.getAuthorizationUrl({
scopes: ['openid', 'profile', 'email'],
});
// Store state for validation
req.session.authState = state;
res.redirect(url);
});
// Callback endpoint
router.get('/callback', async (req, res) => {
try {
const { code, state } = req.query;
// Validate state
if (state !== req.session.authState) {
return res.status(400).send('Invalid state');
}
// Exchange code for tokens
const tokens = await authClient.exchangeCodeForTokens(code as string);
// Get user info
const user = await authClient.getUserInfo(tokens.access_token);
// Store session
req.session.user = user;
req.session.tokens = tokens;
res.redirect('/dashboard');
} catch (error) {
res.status(400).send('Authentication failed');
}
});
// Logout endpoint
router.post('/logout', (req, res) => {
req.session.destroy((err) => {
if (err) {
return res.status(500).send('Logout failed');
}
res.redirect('/');
});
});
export default router;4. Add Authentication Middleware
// middleware/auth.ts
import { Request, Response, NextFunction } from 'express';
import { authClient } from '../config/auth';
export async function requireAuth(req: Request, res: Response, next: NextFunction) {
const tokens = req.session?.tokens;
if (!tokens) {
return res.status(401).redirect('/auth/login');
}
try {
// Check if token is still valid
if (authClient.isTokenExpired(tokens.access_token)) {
// Try to refresh the token
const newTokens = await authClient.refreshTokens(tokens.refresh_token);
req.session.tokens = newTokens;
}
next();
} catch (error) {
// Token refresh failed, redirect to login
req.session.destroy(() => {
res.status(401).redirect('/auth/login');
});
}
}5. Protect API Routes
// routes/api.ts
import express from 'express';
import { requireAuth } from '../middleware/auth';
const router = express.Router();
router.get('/profile', requireAuth, (req, res) => {
res.json({
user: req.session.user,
message: 'This is a protected endpoint'
});
});
router.get('/dashboard', requireAuth, (req, res) => {
res.json({
user: req.session.user,
data: 'Protected dashboard data'
});
});
export default router;Testing Your Integration
1. Start Your Application
# React
npm start
# Next.js
npm run dev
# Node.js
npm run dev2. Test Authentication Flow
- Visit your application
- Click the login button
- You should be redirected to BinoAuth
- Log in with your credentials
- You should be redirected back to your app
- Verify you can access protected routes
3. Common Issues
Redirect URI Mismatch
Error: redirect_uri_mismatchSolution: Ensure the redirect URI in your app matches the one configured in BinoAuth.
Invalid Client
Error: invalid_clientSolution: Check your client ID and secret are correct.
CORS Issues
Error: CORS policy blockedSolution: Configure CORS in BinoAuth to allow your domain.
What’s Next?
Now that you have basic authentication working:
- Explore Authentication Methods - Add magic links, phone auth, etc.
- Customize User Experience - Brand your auth pages
- Add Security Features - Enable MFA, rate limiting
- API Integration - Use BinoAuth APIs directly
- Production Deployment - Deploy to production
Need Help?
- Check our Troubleshooting Guide
- View Examples for complete implementations
- Join our community discussions
Congratulations! You now have BinoAuth authentication working in your application. 🎉
Last updated on