@insforge/nextjs 1.0.8-dev.3 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,380 +1,380 @@
1
- # @insforge/nextjs
2
-
3
- **Zero-configuration authentication for Next.js** using Insforge backend. Get production-ready auth in 5 minutes.
4
-
5
- ## Why @insforge/nextjs?
6
-
7
- ✅ **Built-in Auth Pages** - Backend-hosted UI, no React code needed
8
- ✅ **5-Minute Setup** - Provider + API route + callback + middleware = done
9
- ✅ **Full SSR Support** - Works with Next.js App Router and Server Components
10
- ✅ **Auto OAuth** - 11 providers configured from backend automatically
11
- ✅ **TypeScript First** - Complete type safety out of the box
12
-
13
- **Need custom UI?** Scroll to [Customization](#customization) for custom components and styling.
14
-
15
- ## Installation
16
-
17
- ```bash
18
- npm install @insforge/nextjs
19
- ```
20
-
21
- ---
22
-
23
- ## Quick Start
24
-
25
- ### 1. Setup Provider
26
-
27
- Wrap your app with `InsforgeProvider` in the root layout:
28
-
29
- ```tsx
30
- // app/layout.tsx
31
- import { InsforgeProvider } from '@insforge/nextjs';
32
-
33
- export default function RootLayout({ children }: { children: React.ReactNode }) {
34
- return (
35
- <html lang="en">
36
- <body>
37
- <InsforgeProvider
38
- baseUrl={process.env.NEXT_PUBLIC_INSFORGE_BASE_URL!}
39
- afterSignInUrl="/dashboard"
40
- >
41
- {children}
42
- </InsforgeProvider>
43
- </body>
44
- </html>
45
- );
46
- }
47
- ```
48
-
49
- > **Zero Configuration**: Styles are automatically injected via Emotion CSS-in-JS. No CSS imports needed!
50
-
51
- ### 2. Create API Route
52
-
53
- Create an API route to sync tokens to HTTP-only cookies (enables SSR):
54
-
55
- ```tsx
56
- // app/api/auth/route.ts
57
- import { createAuthRouteHandlers } from '@insforge/nextjs/api';
58
-
59
- const handlers = createAuthRouteHandlers({
60
- baseUrl: process.env.INSFORGE_BASE_URL || process.env.NEXT_PUBLIC_INSFORGE_BASE_URL!,
61
- cookieName: 'insforge_token',
62
- });
63
-
64
- export const POST = handlers.POST;
65
- export const GET = handlers.GET;
66
- export const DELETE = handlers.DELETE;
67
- ```
68
-
69
- **What it does:**
70
-
71
- - `POST /api/auth` - Syncs localStorage token to HTTP-only cookie
72
- - `GET /api/auth` - Retrieves user data server-side
73
- - `DELETE /api/auth` - Clears auth cookie on sign out
74
-
75
- ### 3. Setup Middleware
76
-
77
- Protect routes with middleware:
78
-
79
- ```ts
80
- // middleware.ts
81
- import { InsforgeMiddleware } from '@insforge/nextjs/middleware';
82
-
83
- export default InsforgeMiddleware({
84
- baseUrl: process.env.INSFORGE_BASE_URL!,
85
- publicRoutes: ['/auth/callback', '/'],
86
- cookieName: 'insforge_token',
87
- });
88
-
89
- export const config = {
90
- matcher: [
91
- '/((?!api|_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
92
- ],
93
- };
94
- ```
95
-
96
- **What it does:**
97
-
98
- - Redirects unauthenticated users to backend auth pages
99
- - Verifies tokens server-side
100
- - Allows public routes without auth
101
-
102
- ### 4. Use Hooks & Components
103
-
104
- ```tsx
105
- // app/page.tsx
106
- import { SignedIn, SignedOut, UserButton } from '@insforge/nextjs';
107
-
108
- export default function Home() {
109
- return (
110
- <div>
111
- <SignedOut>
112
- <a href="/sign-in">Sign In</a>
113
- </SignedOut>
114
-
115
- <SignedIn>
116
- <UserButton afterSignOutUrl="/" />
117
- <h1>Welcome back!</h1>
118
- </SignedIn>
119
- </div>
120
- );
121
- }
122
- ```
123
-
124
- **Available Hooks:**
125
-
126
- ```tsx
127
- import { useAuth, useUser } from '@insforge/nextjs';
128
-
129
- function Component() {
130
- const { signIn, signUp, signOut, isSignedIn, isLoaded } = useAuth();
131
- const { user, updateUser } = useUser();
132
-
133
- return <div>Email: {user?.email}</div>;
134
- }
135
- ```
136
-
137
- **That's it!** 🎉 Your app now has production-ready authentication.
138
-
139
- ---
140
-
141
- ## How It Works
142
-
143
- ```
144
- 1. User clicks "Sign In" → Middleware redirects to backend auth page
145
-
146
- 2. User signs in on backend (https://your-project.insforge.app/auth/sign-in)
147
-
148
- 3. Backend redirects: yourapp.com?access_token=xxx&user_id=xxx...
149
-
150
- 4. SDK auto-detects URL parameters:
151
- - Stores token in localStorage
152
- - Provider automatically reloads auth state
153
- - Token syncs to HTTP-only cookie (via API route)
154
-
155
- 5. User sees dashboard with authenticated state
156
- ```
157
-
158
- **Two-Storage Architecture:**
159
-
160
- - **localStorage**: Client-side token access (hooks, components, SDK)
161
- - **HTTP-only cookie**: Server-side token access (middleware, SSR)
162
-
163
- ---
164
-
165
- ## Customization
166
-
167
- ### Custom Auth Pages
168
-
169
- Want custom branding? Create custom auth pages instead of using built-in pages:
170
-
171
- ```tsx
172
- // app/sign-in/page.tsx
173
- 'use client';
174
-
175
- import { SignIn } from '@insforge/nextjs';
176
- import { useRouter } from 'next/navigation';
177
-
178
- export default function SignInPage() {
179
- const router = useRouter();
180
-
181
- return (
182
- <div className="min-h-screen flex items-center justify-center bg-gray-50">
183
- <SignIn
184
- afterSignInUrl="/dashboard"
185
- onSuccess={(user) => {
186
- console.log('Signed in:', user);
187
- router.push('/dashboard');
188
- }}
189
- />
190
- </div>
191
- );
192
- }
193
- ```
194
-
195
- **Additional Auth Components:**
196
-
197
- ```tsx
198
- // Password reset flow
199
- import { ForgotPassword, ResetPassword, VerifyEmail } from '@insforge/nextjs';
200
-
201
- // app/forgot-password/page.tsx
202
- <ForgotPassword backToSignInUrl="/sign-in" />
203
-
204
- // app/reset-password/page.tsx (with token from URL)
205
- <ResetPassword token={token} backToSignInUrl="/sign-in" />
206
-
207
- // app/verify-email/page.tsx (with token from URL)
208
- <VerifyEmail token={token} />
209
- ```
210
-
211
- **Available Atomic Components:**
212
-
213
- - `AuthContainer` - Main form container
214
- - `AuthHeader` - Title and subtitle
215
- - `AuthFormField` - Standard input field
216
- - `AuthPasswordField` - Password field with visibility toggle
217
- - `AuthPasswordStrengthIndicator` - Password requirement checklist
218
- - `AuthSubmitButton` - Submit button with loading states
219
- - `AuthErrorBanner` - Error message display
220
- - `AuthDivider` - Visual separator
221
- - `AuthOAuthProviders` - OAuth provider buttons grid
222
- - `AuthOAuthButton` - Individual OAuth button
223
- - `AuthVerificationCodeInput` - OTP/2FA code input
224
- - `AuthLink` - Navigation link
225
- - `AuthBranding` - Insforge branding footer
226
-
227
- ### Server-Side Usage
228
-
229
- Access auth data in Server Components, API Routes, and Server Actions using the `auth()` helper:
230
-
231
- #### Using in Server Components
232
-
233
- ```tsx
234
- // app/dashboard/page.tsx (Server Component)
235
- import { auth } from '@insforge/nextjs/server';
236
-
237
- export default async function Dashboard() {
238
- const { userId, user } = await auth();
239
-
240
- if (!userId) {
241
- return <div>Not authenticated</div>;
242
- }
243
-
244
- return <div>Welcome, {user?.email}!</div>;
245
- }
246
- ```
247
-
248
- #### Using in API Routes
249
-
250
- ```tsx
251
- // app/api/posts/route.ts
252
- import { auth, createServerClient } from '@insforge/nextjs/server';
253
- import { NextResponse } from 'next/server';
254
-
255
- export async function GET() {
256
- const { userId, token } = await auth();
257
-
258
- if (!userId || !token) {
259
- return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
260
- }
261
-
262
- // Option 1: Use auth info directly
263
- return NextResponse.json({ userId, message: 'Authenticated!' });
264
-
265
- // Option 2: Use createServerClient for database operations
266
- const insforge = await createServerClient({
267
- baseUrl: process.env.INSFORGE_BASE_URL!,
268
- });
269
-
270
- if (!insforge) {
271
- return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
272
- }
273
-
274
- const result = await insforge.database.from('posts').select();
275
- return NextResponse.json(result.data);
276
- }
277
- ```
278
-
279
- #### Using in Server Actions
280
-
281
- ```tsx
282
- 'use server';
283
-
284
- import { auth } from '@insforge/nextjs/server';
285
- import { revalidatePath } from 'next/cache';
286
-
287
- export async function createPost(formData: FormData) {
288
- const { userId } = await auth();
289
-
290
- if (!userId) {
291
- throw new Error('Not authenticated');
292
- }
293
-
294
- // Create post with userId
295
- const title = formData.get('title');
296
- // ... insert into database
297
-
298
- revalidatePath('/posts');
299
- }
300
- ```
301
-
302
- ### Conditional Rendering
303
-
304
- ```tsx
305
- import { Protect } from '@insforge/nextjs';
306
-
307
- // Role-based access
308
- <Protect condition={(user) => user.role === 'admin'}>
309
- <AdminPanel />
310
- </Protect>
311
-
312
- // Custom logic
313
- <Protect condition={(user) => user.emailVerified}>
314
- <VerifiedUserFeature />
315
- </Protect>
316
- ```
317
-
318
- ### Auth Change Callback
319
-
320
- Track authentication events:
321
-
322
- ```tsx
323
- <InsforgeProvider
324
- baseUrl={baseUrl}
325
- onAuthChange={(user) => {
326
- if (user) {
327
- analytics.identify(user.id);
328
- } else {
329
- analytics.reset();
330
- }
331
- }}
332
- />
333
- ```
334
-
335
- ---
336
-
337
- ## Local Development
338
-
339
- During local development, backend typically runs on a different port:
340
-
341
- ```bash
342
- # .env.local
343
- NEXT_PUBLIC_INSFORGE_BASE_URL=http://localhost:7130
344
- INSFORGE_BASE_URL=http://localhost:7130
345
- ```
346
-
347
- ---
348
-
349
- ## TypeScript
350
-
351
- Full TypeScript support with exported types:
352
-
353
- ```tsx
354
- import type {
355
- InsforgeUser,
356
- InsforgeCallbackProps,
357
- SignInProps,
358
- SignUpProps,
359
- ForgotPasswordProps,
360
- ResetPasswordProps,
361
- VerifyEmailProps,
362
- SignInAppearance,
363
- SignUpAppearance,
364
- UserButtonProps,
365
- ProtectProps,
366
- OAuthProvider,
367
- } from '@insforge/nextjs';
368
- ```
369
-
370
- ---
371
-
372
- ## Support
373
-
374
- - **Documentation**: https://docs.insforge.dev
375
- - **GitHub Issues**: https://github.com/InsForge/InsForge/issues
376
- - **Discord Community**: https://discord.com/invite/DvBtaEc9Jz
377
-
378
- ## License
379
-
380
- MIT
1
+ # @insforge/nextjs
2
+
3
+ **Zero-configuration authentication for Next.js** using Insforge backend. Get production-ready auth in 5 minutes.
4
+
5
+ ## Why @insforge/nextjs?
6
+
7
+ ✅ **Built-in Auth Pages** - Backend-hosted UI, no React code needed
8
+ ✅ **5-Minute Setup** - Provider + API route + callback + middleware = done
9
+ ✅ **Full SSR Support** - Works with Next.js App Router and Server Components
10
+ ✅ **Auto OAuth** - 11 providers configured from backend automatically
11
+ ✅ **TypeScript First** - Complete type safety out of the box
12
+
13
+ **Need custom UI?** Scroll to [Customization](#customization) for custom components and styling.
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ npm install @insforge/nextjs
19
+ ```
20
+
21
+ ---
22
+
23
+ ## Quick Start
24
+
25
+ ### 1. Setup Provider
26
+
27
+ Wrap your app with `InsforgeProvider` in the root layout:
28
+
29
+ ```tsx
30
+ // app/layout.tsx
31
+ import { InsforgeProvider } from '@insforge/nextjs';
32
+
33
+ export default function RootLayout({ children }: { children: React.ReactNode }) {
34
+ return (
35
+ <html lang="en">
36
+ <body>
37
+ <InsforgeProvider
38
+ baseUrl={process.env.NEXT_PUBLIC_INSFORGE_BASE_URL!}
39
+ afterSignInUrl="/dashboard"
40
+ >
41
+ {children}
42
+ </InsforgeProvider>
43
+ </body>
44
+ </html>
45
+ );
46
+ }
47
+ ```
48
+
49
+ > **Zero Configuration**: Styles are automatically injected via Emotion CSS-in-JS. No CSS imports needed!
50
+
51
+ ### 2. Create API Route
52
+
53
+ Create an API route to sync tokens to HTTP-only cookies (enables SSR):
54
+
55
+ ```tsx
56
+ // app/api/auth/route.ts
57
+ import { createAuthRouteHandlers } from '@insforge/nextjs/api';
58
+
59
+ const handlers = createAuthRouteHandlers({
60
+ baseUrl: process.env.INSFORGE_BASE_URL || process.env.NEXT_PUBLIC_INSFORGE_BASE_URL!,
61
+ cookieName: 'insforge_token',
62
+ });
63
+
64
+ export const POST = handlers.POST;
65
+ export const GET = handlers.GET;
66
+ export const DELETE = handlers.DELETE;
67
+ ```
68
+
69
+ **What it does:**
70
+
71
+ - `POST /api/auth` - Syncs localStorage token to HTTP-only cookie
72
+ - `GET /api/auth` - Retrieves user data server-side
73
+ - `DELETE /api/auth` - Clears auth cookie on sign out
74
+
75
+ ### 3. Setup Middleware
76
+
77
+ Protect routes with middleware:
78
+
79
+ ```ts
80
+ // middleware.ts
81
+ import { InsforgeMiddleware } from '@insforge/nextjs/middleware';
82
+
83
+ export default InsforgeMiddleware({
84
+ baseUrl: process.env.INSFORGE_BASE_URL!,
85
+ publicRoutes: ['/auth/callback', '/'],
86
+ cookieName: 'insforge_token',
87
+ });
88
+
89
+ export const config = {
90
+ matcher: [
91
+ '/((?!api|_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
92
+ ],
93
+ };
94
+ ```
95
+
96
+ **What it does:**
97
+
98
+ - Redirects unauthenticated users to backend auth pages
99
+ - Verifies tokens server-side
100
+ - Allows public routes without auth
101
+
102
+ ### 4. Use Hooks & Components
103
+
104
+ ```tsx
105
+ // app/page.tsx
106
+ import { SignedIn, SignedOut, UserButton } from '@insforge/nextjs';
107
+
108
+ export default function Home() {
109
+ return (
110
+ <div>
111
+ <SignedOut>
112
+ <a href="/sign-in">Sign In</a>
113
+ </SignedOut>
114
+
115
+ <SignedIn>
116
+ <UserButton afterSignOutUrl="/" />
117
+ <h1>Welcome back!</h1>
118
+ </SignedIn>
119
+ </div>
120
+ );
121
+ }
122
+ ```
123
+
124
+ **Available Hooks:**
125
+
126
+ ```tsx
127
+ import { useAuth, useUser } from '@insforge/nextjs';
128
+
129
+ function Component() {
130
+ const { signIn, signUp, signOut, isSignedIn, isLoaded } = useAuth();
131
+ const { user, updateUser } = useUser();
132
+
133
+ return <div>Email: {user?.email}</div>;
134
+ }
135
+ ```
136
+
137
+ **That's it!** 🎉 Your app now has production-ready authentication.
138
+
139
+ ---
140
+
141
+ ## How It Works
142
+
143
+ ```
144
+ 1. User clicks "Sign In" → Middleware redirects to backend auth page
145
+
146
+ 2. User signs in on backend (https://your-project.insforge.app/auth/sign-in)
147
+
148
+ 3. Backend redirects: yourapp.com?access_token=xxx&user_id=xxx...
149
+
150
+ 4. SDK auto-detects URL parameters:
151
+ - Stores token in localStorage
152
+ - Provider automatically reloads auth state
153
+ - Token syncs to HTTP-only cookie (via API route)
154
+
155
+ 5. User sees dashboard with authenticated state
156
+ ```
157
+
158
+ **Two-Storage Architecture:**
159
+
160
+ - **localStorage**: Client-side token access (hooks, components, SDK)
161
+ - **HTTP-only cookie**: Server-side token access (middleware, SSR)
162
+
163
+ ---
164
+
165
+ ## Customization
166
+
167
+ ### Custom Auth Pages
168
+
169
+ Want custom branding? Create custom auth pages instead of using built-in pages:
170
+
171
+ ```tsx
172
+ // app/sign-in/page.tsx
173
+ 'use client';
174
+
175
+ import { SignIn } from '@insforge/nextjs';
176
+ import { useRouter } from 'next/navigation';
177
+
178
+ export default function SignInPage() {
179
+ const router = useRouter();
180
+
181
+ return (
182
+ <div className="min-h-screen flex items-center justify-center bg-gray-50">
183
+ <SignIn
184
+ afterSignInUrl="/dashboard"
185
+ onSuccess={(user) => {
186
+ console.log('Signed in:', user);
187
+ router.push('/dashboard');
188
+ }}
189
+ />
190
+ </div>
191
+ );
192
+ }
193
+ ```
194
+
195
+ **Additional Auth Components:**
196
+
197
+ ```tsx
198
+ // Password reset flow
199
+ import { ForgotPassword, ResetPassword, VerifyEmail } from '@insforge/nextjs';
200
+
201
+ // app/forgot-password/page.tsx
202
+ <ForgotPassword backToSignInUrl="/sign-in" />
203
+
204
+ // app/reset-password/page.tsx (with token from URL)
205
+ <ResetPassword token={token} backToSignInUrl="/sign-in" />
206
+
207
+ // app/verify-email/page.tsx (with token from URL)
208
+ <VerifyEmail token={token} />
209
+ ```
210
+
211
+ **Available Atomic Components:**
212
+
213
+ - `AuthContainer` - Main form container
214
+ - `AuthHeader` - Title and subtitle
215
+ - `AuthFormField` - Standard input field
216
+ - `AuthPasswordField` - Password field with visibility toggle
217
+ - `AuthPasswordStrengthIndicator` - Password requirement checklist
218
+ - `AuthSubmitButton` - Submit button with loading states
219
+ - `AuthErrorBanner` - Error message display
220
+ - `AuthDivider` - Visual separator
221
+ - `AuthOAuthProviders` - OAuth provider buttons grid
222
+ - `AuthOAuthButton` - Individual OAuth button
223
+ - `AuthVerificationCodeInput` - OTP/2FA code input
224
+ - `AuthLink` - Navigation link
225
+ - `AuthBranding` - Insforge branding footer
226
+
227
+ ### Server-Side Usage
228
+
229
+ Access auth data in Server Components, API Routes, and Server Actions using the `auth()` helper:
230
+
231
+ #### Using in Server Components
232
+
233
+ ```tsx
234
+ // app/dashboard/page.tsx (Server Component)
235
+ import { auth } from '@insforge/nextjs/server';
236
+
237
+ export default async function Dashboard() {
238
+ const { userId, user } = await auth();
239
+
240
+ if (!userId) {
241
+ return <div>Not authenticated</div>;
242
+ }
243
+
244
+ return <div>Welcome, {user?.email}!</div>;
245
+ }
246
+ ```
247
+
248
+ #### Using in API Routes
249
+
250
+ ```tsx
251
+ // app/api/posts/route.ts
252
+ import { auth, createServerClient } from '@insforge/nextjs/server';
253
+ import { NextResponse } from 'next/server';
254
+
255
+ export async function GET() {
256
+ const { userId, token } = await auth();
257
+
258
+ if (!userId || !token) {
259
+ return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
260
+ }
261
+
262
+ // Option 1: Use auth info directly
263
+ return NextResponse.json({ userId, message: 'Authenticated!' });
264
+
265
+ // Option 2: Use createServerClient for database operations
266
+ const insforge = await createServerClient({
267
+ baseUrl: process.env.INSFORGE_BASE_URL!,
268
+ });
269
+
270
+ if (!insforge) {
271
+ return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
272
+ }
273
+
274
+ const result = await insforge.database.from('posts').select();
275
+ return NextResponse.json(result.data);
276
+ }
277
+ ```
278
+
279
+ #### Using in Server Actions
280
+
281
+ ```tsx
282
+ 'use server';
283
+
284
+ import { auth } from '@insforge/nextjs/server';
285
+ import { revalidatePath } from 'next/cache';
286
+
287
+ export async function createPost(formData: FormData) {
288
+ const { userId } = await auth();
289
+
290
+ if (!userId) {
291
+ throw new Error('Not authenticated');
292
+ }
293
+
294
+ // Create post with userId
295
+ const title = formData.get('title');
296
+ // ... insert into database
297
+
298
+ revalidatePath('/posts');
299
+ }
300
+ ```
301
+
302
+ ### Conditional Rendering
303
+
304
+ ```tsx
305
+ import { Protect } from '@insforge/nextjs';
306
+
307
+ // Role-based access
308
+ <Protect condition={(user) => user.role === 'admin'}>
309
+ <AdminPanel />
310
+ </Protect>
311
+
312
+ // Custom logic
313
+ <Protect condition={(user) => user.emailVerified}>
314
+ <VerifiedUserFeature />
315
+ </Protect>
316
+ ```
317
+
318
+ ### Auth Change Callback
319
+
320
+ Track authentication events:
321
+
322
+ ```tsx
323
+ <InsforgeProvider
324
+ baseUrl={baseUrl}
325
+ onAuthChange={(user) => {
326
+ if (user) {
327
+ analytics.identify(user.id);
328
+ } else {
329
+ analytics.reset();
330
+ }
331
+ }}
332
+ />
333
+ ```
334
+
335
+ ---
336
+
337
+ ## Local Development
338
+
339
+ During local development, backend typically runs on a different port:
340
+
341
+ ```bash
342
+ # .env.local
343
+ NEXT_PUBLIC_INSFORGE_BASE_URL=http://localhost:7130
344
+ INSFORGE_BASE_URL=http://localhost:7130
345
+ ```
346
+
347
+ ---
348
+
349
+ ## TypeScript
350
+
351
+ Full TypeScript support with exported types:
352
+
353
+ ```tsx
354
+ import type {
355
+ InsforgeUser,
356
+ InsforgeCallbackProps,
357
+ SignInProps,
358
+ SignUpProps,
359
+ ForgotPasswordProps,
360
+ ResetPasswordProps,
361
+ VerifyEmailProps,
362
+ SignInAppearance,
363
+ SignUpAppearance,
364
+ UserButtonProps,
365
+ ProtectProps,
366
+ OAuthProvider,
367
+ } from '@insforge/nextjs';
368
+ ```
369
+
370
+ ---
371
+
372
+ ## Support
373
+
374
+ - **Documentation**: https://docs.insforge.dev
375
+ - **GitHub Issues**: https://github.com/InsForge/InsForge/issues
376
+ - **Discord Community**: https://discord.com/invite/DvBtaEc9Jz
377
+
378
+ ## License
379
+
380
+ MIT