Skip to content

Commit 4b7e019

Browse files
committed
docs(react-sdk): add comprehensive React SDK documentation
1 parent 3df47db commit 4b7e019

9 files changed

Lines changed: 500 additions & 3 deletions

File tree

.github/scripts/generate-changelog-entry.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,9 @@ Rules:
4646
- If no PRs were merged, output: <Update label="${TODAY}" description="Week of ${WEEK_START}${TODAY}" tags={[]}>No significant changes this week.</Update>`;
4747

4848
const payload = JSON.stringify({
49-
model: "llama-3.1-70b-versatile",
49+
model: "llama-3.3-70b-versatile",
5050
messages: [{ role: "user", content: prompt }],
51-
max_tokens: 4096,
51+
max_tokens: 10000,
5252
temperature: 0.3,
5353
});
5454

mintlify/docs/docs.json

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@
5656
]
5757
},
5858
{
59-
"group": "SDK",
59+
"group": "TypeScript SDK",
6060
"pages": [
6161
"sdk/overview",
6262
"sdk/auth",
@@ -66,6 +66,18 @@
6666
"sdk/mail"
6767
]
6868
},
69+
{
70+
"group": "React SDK",
71+
"pages": [
72+
"react-sdk/overview",
73+
"react-sdk/ur-provider",
74+
"react-sdk/ur-auth",
75+
"react-sdk/ur-user-button",
76+
"react-sdk/routing",
77+
"react-sdk/hooks",
78+
"react-sdk/integration"
79+
]
80+
},
6981
{
7082
"group": "Security & Limits",
7183
"pages": [

mintlify/docs/react-sdk/hooks.mdx

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
---
2+
title: "React Hooks"
3+
description: "Interact with the urBackend SDK natively using React hooks."
4+
---
5+
6+
The `@urbackend/react` SDK exports several hooks to make it easy to access authentication state and perform database/storage operations within your components.
7+
8+
All hooks require your component to be mounted somewhere inside the `<UrProvider>`.
9+
10+
## `useUser()`
11+
12+
The easiest way to read the current authenticated user's profile and state.
13+
14+
```tsx
15+
import { useUser } from '@urbackend/react';
16+
17+
function UserProfile() {
18+
const { user, isAuthenticated, isLoading, isInitializing } = useUser();
19+
20+
if (isInitializing) return <div>Loading session...</div>;
21+
if (!isAuthenticated) return <div>Please log in</div>;
22+
23+
return (
24+
<div>
25+
<h1>Welcome, {user?.name}</h1>
26+
<p>Email: {user?.email}</p>
27+
</div>
28+
);
29+
}
30+
```
31+
32+
## `useAuth()`
33+
34+
Provides access to authentication methods like login, signup, and logout.
35+
36+
```tsx
37+
import { useAuth } from '@urbackend/react';
38+
39+
function CustomLoginForm() {
40+
const { login, logout, error, isLoading } = useAuth();
41+
42+
const handleLogin = async () => {
43+
await login('alice@example.com', 'password123');
44+
};
45+
46+
return (
47+
<div>
48+
<button onClick={handleLogin} disabled={isLoading}>
49+
Log In
50+
</button>
51+
<button onClick={logout}>Log Out</button>
52+
{error && <p style={{ color: 'red' }}>{error}</p>}
53+
</div>
54+
);
55+
}
56+
```
57+
58+
## `useDb()`
59+
60+
Provides direct access to the `urBackend` database client. Operations are automatically authenticated with the current user's session token for Row-Level Security (RLS).
61+
62+
```tsx
63+
import { useState, useEffect } from 'react';
64+
import { useDb } from '@urbackend/react';
65+
66+
function ProductList() {
67+
const db = useDb();
68+
const [products, setProducts] = useState([]);
69+
70+
useEffect(() => {
71+
async function fetchProducts() {
72+
// Automatically passes the user's token for RLS policies
73+
const data = await db.getAll('products', { limit: 10 });
74+
setProducts(data);
75+
}
76+
fetchProducts();
77+
}, [db]);
78+
79+
return (
80+
<ul>
81+
{products.map(p => <li key={p._id}>{p.name}</li>)}
82+
</ul>
83+
);
84+
}
85+
```
86+
87+
## `useStorage()`
88+
89+
Provides access to the Storage API for uploading and deleting files.
90+
91+
```tsx
92+
import { useStorage } from '@urbackend/react';
93+
94+
function Uploader() {
95+
const storage = useStorage();
96+
97+
const handleUpload = async (file: File) => {
98+
const result = await storage.upload(file, 'avatars');
99+
console.log("File available at:", result.url);
100+
};
101+
102+
return (
103+
<input
104+
type="file"
105+
onChange={(e) => handleUpload(e.target.files[0])}
106+
/>
107+
);
108+
}
109+
```
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
---
2+
title: "Full Integration Example"
3+
description: "See how all the pieces of the React SDK fit together in a complete application."
4+
---
5+
6+
Here is a complete, single-file example showing how to build an application with urBackend using `create-react-app` or `Vite`.
7+
8+
This example includes:
9+
1. The global `<UrProvider>`.
10+
2. A client-side router (using simple state for demonstration).
11+
3. A public Login page (`<GuestRoute>`) with the pre-built `<UrAuth>` UI.
12+
4. A secure Dashboard page (`<ProtectedRoute>`).
13+
5. A `<UrUserButton>` for the profile dropdown and logout.
14+
15+
## `App.tsx`
16+
17+
```tsx
18+
import { useState, useEffect } from 'react';
19+
import {
20+
UrProvider,
21+
UrAuth,
22+
ProtectedRoute,
23+
GuestRoute,
24+
UrUserButton,
25+
useUser
26+
} from '@urbackend/react';
27+
28+
// --- Components ---
29+
30+
function LoginPage({ navigate }: { navigate: (path: string) => void }) {
31+
return (
32+
// If they are already logged in, send them straight to the dashboard
33+
<GuestRoute fallback={<div>Loading...</div>} onRedirect={() => navigate('/dashboard')}>
34+
<div style={{ display: 'flex', height: '100vh', alignItems: 'center', justifyContent: 'center' }}>
35+
<UrAuth providers={['google', 'github']} />
36+
</div>
37+
</GuestRoute>
38+
);
39+
}
40+
41+
function Dashboard({ navigate }: { navigate: (path: string) => void }) {
42+
const { user } = useUser();
43+
44+
return (
45+
// If they are NOT logged in, kick them back to login
46+
<ProtectedRoute fallback={<div>Loading...</div>} onRedirect={() => navigate('/')}>
47+
48+
{/* Top right profile dropdown */}
49+
<UrUserButton
50+
onSettingsClick={() => alert('Opening Settings')}
51+
onProfileClick={() => alert('Opening Profile')}
52+
/>
53+
54+
<div style={{ padding: '40px', fontFamily: 'sans-serif' }}>
55+
<h1>Dashboard</h1>
56+
<p>Welcome back, {user?.name || user?.email}!</p>
57+
<p>Your user ID is: <code>{user?._id}</code></p>
58+
</div>
59+
60+
</ProtectedRoute>
61+
);
62+
}
63+
64+
// --- Main Router ---
65+
66+
function Router() {
67+
const [route, setRoute] = useState(window.location.pathname);
68+
69+
useEffect(() => {
70+
const handlePop = () => setRoute(window.location.pathname);
71+
window.addEventListener('popstate', handlePop);
72+
return () => window.removeEventListener('popstate', handlePop);
73+
}, []);
74+
75+
const navigate = (path: string) => {
76+
window.history.pushState({}, '', path);
77+
setRoute(path);
78+
};
79+
80+
if (route === '/dashboard') {
81+
return <Dashboard navigate={navigate} />;
82+
}
83+
84+
// Default route (Login)
85+
return <LoginPage navigate={navigate} />;
86+
}
87+
88+
// --- Root Entry Point ---
89+
90+
export default function App() {
91+
return (
92+
<UrProvider apiKey="pk_live_your_publishable_api_key">
93+
<Router />
94+
</UrProvider>
95+
);
96+
}
97+
```
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
---
2+
title: "React SDK Overview"
3+
description: "Build full-stack React applications in minutes with pre-built authentication UI, session management, and hooks."
4+
---
5+
6+
The `@urbackend/react` SDK provides everything you need to build secure, scalable React applications on top of urBackend. It handles the heavy lifting of session persistence, social logins, and routing out of the box.
7+
8+
## Features
9+
10+
- **Pre-built Auth UI**: A beautiful, customizable `<UrAuth />` component for login/signup (email/password & social).
11+
- **Session Management**: Automatically persists tokens to `localStorage` and handles silent background refreshes.
12+
- **Protected Routing**: Simple `<ProtectedRoute>` and `<GuestRoute>` wrappers to secure your pages.
13+
- **Customizable UI**: Includes `<UrUserButton />` for a ready-to-use profile dropdown.
14+
- **Powerful Hooks**: `useUser`, `useAuth`, `useDb`, and `useStorage` to interact with your backend data natively.
15+
16+
## Installation
17+
18+
Install the React SDK along with the core TypeScript SDK (which it uses under the hood):
19+
20+
```bash
21+
npm install @urbackend/react @urbackend/sdk
22+
```
23+
24+
## Setup (Create React App / Vite)
25+
26+
To get started, wrap your root application with the `<UrProvider>` and pass your project's Publishable API Key.
27+
28+
<Warning>
29+
**Always use your Publishable Key (`pk_live_...`) in the browser.** Never use your Secret Key (`sk_live_...`) on the frontend, as it grants full administrative access.
30+
</Warning>
31+
32+
```tsx src/main.tsx
33+
import React from 'react'
34+
import ReactDOM from 'react-dom/client'
35+
import App from './App'
36+
import { UrProvider } from '@urbackend/react'
37+
import './index.css'
38+
39+
// Initialize the UrBackend Provider
40+
ReactDOM.createRoot(document.getElementById('root')!).render(
41+
<React.StrictMode>
42+
<UrProvider apiKey="pk_live_your_publishable_api_key">
43+
<App />
44+
</UrProvider>
45+
</React.StrictMode>,
46+
)
47+
```
48+
49+
## Setup (Next.js App Router)
50+
51+
If you are using Next.js with the App Router, create a Client Component provider to wrap your application:
52+
53+
```tsx src/components/Providers.tsx
54+
"use client";
55+
56+
import { UrProvider } from '@urbackend/react';
57+
58+
export function Providers({ children }: { children: React.ReactNode }) {
59+
return (
60+
<UrProvider apiKey={process.env.NEXT_PUBLIC_URBACKEND_API_KEY!}>
61+
{children}
62+
</UrProvider>
63+
);
64+
}
65+
```
66+
67+
Then, wrap your layout:
68+
69+
```tsx src/app/layout.tsx
70+
import { Providers } from '../components/Providers';
71+
72+
export default function RootLayout({ children }: { children: React.ReactNode }) {
73+
return (
74+
<html lang="en">
75+
<body>
76+
<Providers>
77+
{children}
78+
</Providers>
79+
</body>
80+
</html>
81+
);
82+
}
83+
```
84+
85+
## Next Steps
86+
87+
Now that your provider is set up, you can start building your authentication flow and accessing your data.
88+
89+
<CardGroup cols={2}>
90+
<Card title="Authentication UI" icon="lock" href="/react-sdk/ur-auth">
91+
Add a login screen in one line of code.
92+
</Card>
93+
<Card title="Protect Routes" icon="shield-check" href="/react-sdk/routing">
94+
Secure your application pages.
95+
</Card>
96+
</CardGroup>

0 commit comments

Comments
 (0)