### sbKitClient Initialization Example Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/sbKitClient.md Initializes the sbKitClient with Supabase clients for server and middleware contexts, and custom options for authentication routes, redirect policies, password policies, and OAuth providers. This setup is typically done once in your application. ```typescript import { sbKitClient } from '@sb-kit/core'; import { createClient } from '@supabase/supabase-js'; // Initialize Supabase clients const serverClient = () => createClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.SUPABASE_SERVICE_ROLE_KEY! ); const middlewareClient = (req) => { // Implementation provided by you }; // Initialize sb-kit const sbKit = sbKitClient({ supabaseClients: { server: serverClient, middleware: middlewareClient, }, options: { authRoutes: { signIn: '/signin', signUp: '/signup', setPassword: '/set-password', forgotPassword: '/forgot-password', oauthCallback: '/api/auth/callback', }, redirectPolicy: { allowedHosts: ['localhost:3000', 'example.com'], blockedPaths: ['/api/auth/callback', '/admin'], defaultPathAfterAuth: '/dashboard', }, passwordPolicy: { minLength: 8, passwordRule: 'letters-digits', }, emailOtpLength: 6, oauthProviders: { github: { buttonText: 'Continue with GitHub' }, google: { buttonText: 'Continue with Google' }, }, }, }); // Use in middleware.ts export async function middleware(request: NextRequest) { return sbKit.routeGuard(request); } // Use components in page export default function SignInPage({ searchParams }) { return ( ); } ``` -------------------------------- ### Install sb-kit Dependencies (bun) Source: https://github.com/bytaesu/sb-kit/blob/main/apps/docs/content/docs/getting-started.mdx Use this command to initialize shadcn/ui and install sb-kit core and UI packages with bun. ```sh bunx shadcn@latest init bun add @supabase/supabase-js @supabase/ssr @sb-kit/core @sb-kit/ui ``` -------------------------------- ### Install sb-kit Dependencies (npm) Source: https://github.com/bytaesu/sb-kit/blob/main/apps/docs/content/docs/getting-started.mdx Use this command to initialize shadcn/ui and install sb-kit core and UI packages with npm. ```sh npx shadcn@latest init npm install @supabase/supabase-js @supabase/ssr @sb-kit/core @sb-kit/ui ``` -------------------------------- ### Install sb-kit Dependencies (yarn) Source: https://github.com/bytaesu/sb-kit/blob/main/apps/docs/content/docs/getting-started.mdx Use this command to initialize shadcn/ui and install sb-kit core and UI packages with yarn. ```sh yarn dlx shadcn@latest init yarn add @supabase/supabase-js @supabase/ssr @sb-kit/core @sb-kit/ui ``` -------------------------------- ### Install sb-kit Core and UI Packages Source: https://github.com/bytaesu/sb-kit/blob/main/README.md Install the necessary sb-kit packages using npm, pnpm, yarn, or bun. ```sh # npm npm i @sb-kit/core @sb-kit/ui # pnpm pnpm add @sb-kit/core @sb-kit/ui # yarn yarn add @sb-kit/core @sb-kit/ui # bun bun add @sb-kit/core @sb-kit/ui ``` -------------------------------- ### Install sb-kit Dependencies (pnpm) Source: https://github.com/bytaesu/sb-kit/blob/main/apps/docs/content/docs/getting-started.mdx Use this command to initialize shadcn/ui and install sb-kit core and UI packages with pnpm. ```sh pnpm dlx shadcn@latest init pnpm add @supabase/supabase-js @supabase/ssr @sb-kit/core @sb-kit/ui ``` -------------------------------- ### Complete Profile Card Example Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/ui-components.md A comprehensive example demonstrating the usage of all Card sub-components to create a profile card. ```typescript import { Card, CardHeader, CardContent, CardFooter, CardTitle } from '@sb-kit/ui/components/base/card'; import { Button } from '@sb-kit/ui/components/base/button'; export function ProfileCard() { return ( Profile Settings

User profile information here

); } ``` -------------------------------- ### Install sb-kit Core and UI Packages Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/README.md Install the core and UI packages for sb-kit using npm. Ensure your project meets the Node.js and Next.js version requirements. ```bash npm install @sb-kit/core @sb-kit/ui ``` -------------------------------- ### Sign In Server Action Example Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/server-actions.md Example of using the signInAction to authenticate a user. Handles form submission, calls the action, and manages loading and error states. Redirects on successful sign-in. ```typescript 'use client'; import { signInAction } from '@sb-kit/core/actions'; export function LoginForm() { const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setLoading(true); setError(null); const formData = new FormData(e.currentTarget); const result = await signInAction( formData.get('email') as string, formData.get('password') as string ); if (result.errorMessage) { setError(result.errorMessage); } else { // Redirect to dashboard window.location.href = '/dashboard'; } setLoading(false); }; return (
{error &&
{error}
}
); } ``` -------------------------------- ### Blocked Paths Configuration Example Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/safe-redirect.md Define path prefixes that are forbidden for redirection. Each path must start with `/` and matching is prefix-based. ```typescript blockedPaths: [ '/api/auth/callback', // OAuth callback itself '/api/admin', // Admin endpoints '/admin', // Admin pages '/internal', // Internal routes '/__next', // Next.js internals ] ``` -------------------------------- ### Password Policy Examples Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/configuration.md Illustrates different configurations for password policies, ranging from weak to strong requirements. ```typescript // Weak: Only 6 characters minimum { minLength: 6, passwordRule: 'no-requirement' } ``` ```typescript // Moderate: 8 characters with letters and digits { minLength: 8, passwordRule: 'letters-digits' } ``` ```typescript // Strong: 10 characters with mixed case, digits, and symbols { minLength: 10, passwordRule: 'lowercase-uppercase-letters-digits-symbols' } ``` -------------------------------- ### Usage Example Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/routeGuard.md Demonstrates how to integrate the routeGuard function into your Next.js middleware. ```APIDOC ## Usage Example ```typescript // middleware.ts import { NextRequest } from 'next/server'; import { sbKitClient } from '@sb-kit/core'; const sbKit = sbKitClient({ supabaseClients: { server: createServerClient, middleware: createMiddlewareClient, }, options: { routeGuardPolicy: { onlyPublic: ['/signin', '/signup', '/forgot-password', '/public'], onlyPrivate: ['/dashboard', '/profile', '/settings'], }, }, }); export function middleware(request: NextRequest) { return sbKit.routeGuard(request); } export const config = { matcher: [ '/((?!api|_next/static|_next/image|favicon.ico).*)', ], }; ``` ``` -------------------------------- ### Get Safe Redirect Path - Success Example Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/safe-redirect.md Demonstrates a successful validation of a redirect URL, returning the safe path with query and hash. Assumes a valid `config` object is provided. ```typescript const url = new URL('https://example.com/dashboard?user=123#settings', window.location.origin); getSafeRedirectPath(url, config); // Returns: '/dashboard?user=123#settings' ``` -------------------------------- ### Create New Next.js App with sb-kit (bun) Source: https://github.com/bytaesu/sb-kit/blob/main/apps/docs/content/docs/getting-started.mdx Scaffolds a new Next.js project with Tailwind CSS, initializes shadcn/ui, and installs sb-kit dependencies using bun. ```sh npx create-next-app@latest myapp --tailwind --use-bun cd myapp bunx shadcn@latest init bun add @supabase/supabase-js @supabase/ssr @sb-kit/core @sb-kit/ui ``` -------------------------------- ### SignIn Component Usage Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/auth-components.md Example of how to integrate the SignIn component into a Next.js page. Ensure `sbKit` is imported from '@/lib/sb-kit'. ```typescript import { sbKit } from '@/lib/sb-kit'; export default function SignInPage({ searchParams }) { return ( ); } ``` -------------------------------- ### Create New Next.js App with sb-kit (npm) Source: https://github.com/bytaesu/sb-kit/blob/main/apps/docs/content/docs/getting-started.mdx Scaffolds a new Next.js project with Tailwind CSS, initializes shadcn/ui, and installs sb-kit dependencies using npm. ```sh npx create-next-app@latest myapp --tailwind --use-npm cd myapp npx shadcn@latest init npm install @supabase/supabase-js @supabase/ssr @sb-kit/core @sb-kit/ui ``` -------------------------------- ### Email Authentication Flow Example Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/hooks.md Demonstrates how to use the useEmailOtpFlow hook to manage an email OTP verification process. Requires the 'use client' directive. ```typescript 'use client'; import { useEmailOtpFlow } from '@sb-kit/core'; import { verifyOtpAction } from '@sb-kit/core/actions'; export function EmailAuthFlow() { const { userEmail, isVerificationStage, enterVerificationStage, exitVerificationStage } = useEmailOtpFlow(); const [code, setCode] = useState(''); const [error, setError] = useState(null); const handleEmailSubmit = async (email: string) => { // Send OTP via signUpAction enterVerificationStage(email); }; const handleOtpSubmit = async () => { const result = await verifyOtpAction(userEmail, code, 'signup'); if (result.errorMessage) { setError(result.errorMessage); } else { exitVerificationStage(); // Redirect or show success } }; if (isVerificationStage) { return (

Enter the code sent to {userEmail}

{error &&
{error}
} setCode(e.target.value)} placeholder="000000" maxLength={10} />
); } return (
{ if (e.target.value) { handleEmailSubmit(e.target.value); } }} placeholder="Enter your email" />
); } ``` -------------------------------- ### Example Usage of OAuthAction Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/server-actions.md Provides a complete example of how to use the OAuthAction function within a component to handle OAuth sign-in flows. ```typescript const handleOAuthSignIn = async (provider: OAuthProvider) => { setLoading(true); const result = await OAuthAction( provider, '/dashboard', // Redirect after auth '/api/auth/callback' // Your callback route ); if (result.errorMessage) { setError(result.errorMessage); } else if (result.data) { // Redirect to OAuth provider window.location.href = result.data; } setLoading(false); }; ``` -------------------------------- ### Create New Next.js App with sb-kit (pnpm) Source: https://github.com/bytaesu/sb-kit/blob/main/apps/docs/content/docs/getting-started.mdx Scaffolds a new Next.js project with Tailwind CSS, initializes shadcn/ui, and installs sb-kit dependencies using pnpm. ```sh npx create-next-app@latest myapp --tailwind --use-pnpm cd myapp pnpm dlx shadcn@latest init pnpm add @supabase/supabase-js @supabase/ssr @sb-kit/core @sb-kit/ui ``` -------------------------------- ### Create New Next.js App with sb-kit (yarn) Source: https://github.com/bytaesu/sb-kit/blob/main/apps/docs/content/docs/getting-started.mdx Scaffolds a new Next.js project with Tailwind CSS, initializes shadcn/ui, and installs sb-kit dependencies using yarn. ```sh npx create-next-app@latest myapp --tailwind --use-yarn cd myapp yarn dlx shadcn@latest init yarn add @supabase/supabase-js @supabase/ssr @sb-kit/core @sb-kit/ui ``` -------------------------------- ### Customizing redirectPolicy Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/configuration.md Example demonstrating how to configure the redirect policy for sb-kit. This involves setting allowed hosts, defining paths that should be blocked for redirects, and specifying a default path to redirect to after successful authentication. ```typescript const sbKit = sbKitClient({ supabaseClients: { /* ... */ }, options: { redirectPolicy: { allowedHosts: [ 'localhost:3000', 'localhost:5173', // Vite dev server 'example.com', 'www.example.com', 'app.example.com', ], blockedPaths: [ '/api/auth/callback', '/api/admin', '/internal', ], defaultPathAfterAuth: '/dashboard', }, }, }); ``` -------------------------------- ### Query Parameter Format Example Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/hooks.md Illustrates the expected URL-encoded format for the redirect_url query parameter and its decoded equivalent. ```text /signin?redirect_url=%2Fdashboard%2Fprofile → decoded: /signin?redirect_url=/dashboard/profile ``` -------------------------------- ### Example Configuration Validation Error Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/errors.md This error message is thrown immediately during sbKitClient() initialization when configuration options are invalid. It lists the specific validation failures. ```typescript Error: [sb-kit] Invalid SbKitOptions: - authRoutes.signIn: String must start with "/" - passwordPolicy.minLength: Number must be at least 6 ``` -------------------------------- ### Allowed Hosts Configuration Example Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/safe-redirect.md Specify hostnames that are permitted for redirection. Ensure the port is included if used in the URL, as `localhost:3000` will not match `localhost:5173`. ```typescript allowedHosts: [ 'localhost:3000', // Local development 'example.com', // Production 'www.example.com', // With www 'app.example.com', // Subdomain 'staging.example.com', // Staging '192.168.1.1:8080', // IP address with port ] ``` -------------------------------- ### Catching SB Kit Initialization Errors Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/configuration.md This snippet demonstrates how to wrap the SB Kit client initialization in a try-catch block to handle potential configuration validation errors. It logs the error message and provides an example of the detailed error output indicating which configuration options are invalid. ```typescript try { const sbKit = sbKitClient({ /* ... */ }); } catch (error) { // Error thrown if config is invalid console.error(error.message); // [sb-kit] Invalid SbKitOptions: // - authRoutes.signIn: String must start with "/" // - redirectPolicy.minLength: Number must be at least 6 } ``` -------------------------------- ### Example Usage of verifyOtpAction Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/server-actions.md Demonstrates how to use the verifyOtpAction within an asynchronous function to handle OTP verification and subsequent navigation based on the result and OTP type. ```typescript const handleVerifyOtp = async ( email: string, otp: string, type: 'signup' | 'recovery' ) => { const result = await verifyOtpAction(email, otp, type); if (result.errorMessage) { setError(result.errorMessage); } else { if (type === 'signup') { router.push('/dashboard'); } else { router.push('/set-password'); } } }; ``` -------------------------------- ### Custom Auth Wrapper Example Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/auth-components.md Demonstrates how to customize the authentication wrapper by providing a custom header. This allows for branding and unique UI elements at the top of authentication forms. ```typescript export function CustomAuthWrapper({ children }) { return (

My App

} > {children}
); } ``` -------------------------------- ### OAuth Provider Configuration Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/auth-components.md Configure OAuth providers for the SignIn component. This example shows how to enable GitHub and Google sign-in with custom button text. ```typescript options: { oauthProviders: { github: { buttonText: 'Continue with GitHub' }, google: { buttonText: 'Sign in with Google' }, } } ``` -------------------------------- ### Next.js Middleware with Route Guard Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/routeGuard.md This example demonstrates how to integrate the sbKit routeGuard into your Next.js middleware. Ensure you have configured your Supabase clients and route policies. ```typescript import { NextRequest } from 'next/server'; import { sbKitClient } from '@sb-kit/core'; const sbKit = sbKitClient({ supabaseClients: { server: createServerClient, middleware: createMiddlewareClient, }, options: { routeGuardPolicy: { onlyPublic: ['/signin', '/signup', '/forgot-password', '/public'], onlyPrivate: ['/dashboard', '/profile', '/settings'], }, }, }); export function middleware(request: NextRequest) { return sbKit.routeGuard(request); } export const config = { matcher: [ '/((?!api|_next/static|_next/image|favicon.ico).*)', ], }; ``` -------------------------------- ### Usage Example: Server-side OAuth Callback Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/safe-redirect.md Shows how to use `getSafeRedirectPath` on the server-side after an OAuth callback to ensure the redirect URL is safe before proceeding. Requires importing the function and having `sbKitConfig` available. ```typescript import { getSafeRedirectPath } from '@sb-kit/core'; // Server-side after OAuth callback const redirectUrlString = request.query.redirect_url; const redirectUrl = new URL(redirectUrlString, 'https://example.com'); const safePath = getSafeRedirectPath(redirectUrl, sbKitConfig); // safePath is guaranteed to be safe return NextResponse.redirect(new URL(safePath, request.url)); ``` -------------------------------- ### OAuthAction Return Value Examples Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/server-actions.md Illustrates the possible return structures for OAuthAction, including success and various failure scenarios. ```typescript // Success { data: "https://github.com/login/oauth/authorize?", errorMessage: null } ``` ```typescript // Failure (invalid request) { data: null, errorMessage: "Invalid request. Please try again." } ``` ```typescript // Failure (provider error) { data: null, errorMessage: "OAuth provider error message" } ``` ```typescript // Failure (missing callback URL) { data: null, errorMessage: "Something went wrong. Please refresh the page and try again." } ``` -------------------------------- ### Configure Route Guard Policy in SB Kit Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/configuration.md Example of setting up the routeGuardPolicy within the SB Kit client options to manage public and private access to application routes. ```typescript const sbKit = sbKitClient({ supabaseClients: { /* ... */ }, options: { routeGuardPolicy: { onlyPublic: [ '/signin', '/signup', '/forgot-password', '/pricing', // Marketing page '/blog', // Public blog ], onlyPrivate: [ '/dashboard', '/profile', '/settings', '/account', ], }, }, }); ``` -------------------------------- ### Route Protection Configuration Examples Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/README.md Illustrates how routes are protected by default and how custom policies can be applied. Public-only routes redirect authenticated users, while private-only routes redirect unauthenticated users. ```typescript // These routes are public-only (redirect authenticated users): /signin, /signup, /forgot-password // These routes are private-only (redirect unauthenticated users): /set-password // Custom routes via routeGuardPolicy: onlyPublic: ['/pricing', '/blog'] onlyPrivate: ['/dashboard', '/profile'] ``` -------------------------------- ### Customizing authRoutes Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/configuration.md Example of how to override the default authentication route paths when initializing sb-kit. This allows you to use custom URLs for sign-in, sign-up, password management, and OAuth callbacks. ```typescript const sbKit = sbKitClient({ supabaseClients: { /* ... */ }, options: { authRoutes: { signIn: '/auth/login', signUp: '/auth/register', setPassword: '/auth/change-password', forgotPassword: '/auth/reset', oauthCallback: '/auth/oauth-callback', }, }, }); ``` -------------------------------- ### Input Component Usage Example Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/ui-components.md Demonstrates how to use the Input component within a React form for email input, including state management for the input value and error display. ```typescript import { Input } from '@sb-kit/ui/components/base/input'; export function LoginForm() { const [email, setEmail] = useState(''); const [error, setError] = useState(false); return ( <> setEmail(e.target.value)} aria-invalid={error} /> {error &&

Invalid email

} ); } ``` -------------------------------- ### Get Safe Redirect Path - Failure Example Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/safe-redirect.md Illustrates a failed validation scenario where the redirect URL is deemed unsafe (e.g., invalid host or blocked path), returning the configured default path. Assumes a valid `config` object is provided. ```typescript const url = new URL('https://evil.com/steal', window.location.origin); getSafeRedirectPath(url, config); // Returns: '/' (or defaultPathAfterAuth from config) ``` -------------------------------- ### Usage Example in OAuth Callback Handler Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/safe-redirect.md Shows a practical implementation of getSafeRedirectPathFromParam within an OAuth callback handler. It demonstrates how to extract the redirect URL parameter, obtain the request origin, and use the function to get a safe redirect path before performing the redirection. ```typescript import { getSafeRedirectPathFromParam } from '@sb-kit/core'; // In OAuth callback handler async function callbackHandler(request: Request, sbKitConfig: SbKitConfig) { const url = new URL(request.url); const redirectUrlParam = url.searchParams.get('redirect_url'); const origin = getOrigin(request, url); // Safely parse and validate the redirect parameter const safePath = getSafeRedirectPathFromParam( redirectUrlParam, origin, sbKitConfig ); return NextResponse.redirect(new URL(safePath, origin)); } ``` -------------------------------- ### SetPassword Component Usage Example Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/auth-components.md Example of how to integrate the SetPassword component within an application page, utilizing AuthWrapper for context. ```typescript // app/set-password/page.tsx import { sbKit } from '@/lib/sb-kit'; export default function SetPasswordPage() { return ( ); } ``` -------------------------------- ### Create Authentication Pages Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/README.md Set up the sign-in page using SB-Kit's AuthWrapper and SignIn components. This provides a pre-built UI for user authentication, simplifying the process of creating sign-in and sign-up interfaces. ```typescript // app/signin/page.tsx import { sbKit } from '@/lib/sb-kit'; export default function SignInPage({ searchParams }) { return ( ); } ``` -------------------------------- ### Implement Sign Up Page Source: https://github.com/bytaesu/sb-kit/blob/main/apps/docs/content/docs/getting-started.mdx Use the sbKit.components.SignUp component for your sign-up page. This component handles the user registration process. ```typescript import { sbKit } from '@/lib/supabase/sb-kit'; const SignUp = sbKit.components.SignUp; const Page = () => { return ; }; export default Page; ``` -------------------------------- ### sbKitClient Initialization Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/INDEX.md Initializes the SB Kit client with provided configuration. ```APIDOC ## sbKitClient ### Description Initializes the SB Kit client. This is the main entry point for using the library's functionalities. ### Signature `sbKitClient(init: SbKitClientInit): SbKitClient` ### Parameters - **init** (SbKitClientInit) - Required - The initialization configuration object for the SB Kit client. ``` -------------------------------- ### Set Up Auth Layout Source: https://github.com/bytaesu/sb-kit/blob/main/apps/docs/content/docs/getting-started.mdx Use sbKit.components.AuthWrapper to provide a base authentication UI and the SonnerToaster provider for your application's authentication layout. ```typescript import { sbKit } from '@/lib/supabase/sb-kit'; type Props = { children: React.ReactNode; }; const AuthWrapper = sbKit.components.AuthWrapper; const Layout = ({ children }: Props) => { return {children}; }; export default Layout; ``` -------------------------------- ### PasswordPolicy Example Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/types.md An example of a PasswordPolicy array, demonstrating rules for minimum length, presence of letters, and presence of numbers. This structure is used by password components and server actions for validation. ```typescript [ { regexSource: '.{8,}', message: 'Password must be at least 8 characters long.' }, { regexSource: '[a-zA-Z]', message: 'Password must contain at least one letter.' }, { regexSource: '[0-9]', message: 'Password must contain at least one number.' } ] ``` -------------------------------- ### CardTitle Usage Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/ui-components.md Example of using the CardTitle component for headings. ```typescript My Card Title ``` -------------------------------- ### Initialize sb-kit Client Source: https://github.com/bytaesu/sb-kit/blob/main/apps/docs/content/docs/getting-started.mdx Initialize the sb-kit client by providing Supabase clients for server and middleware environments. This is the first step to using sb-kit's features. ```typescript import { sbKitClient } from '@sb-kit/core'; import { middlewareClient } from './client/middleware'; import { serverClient } from './client/server'; export const sbKit = sbKitClient({ supabaseClients: { server: serverClient, middleware: middlewareClient, }, }); ``` -------------------------------- ### Initialize SB-Kit Client Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/README.md Initialize the sb-kit client with Supabase clients and configuration options. Ensure to provide valid Supabase client creation functions and desired options for authentication, redirection, password policies, and OAuth providers. ```typescript // lib/sb-kit.ts import { sbKitClient } from '@sb-kit/core'; export const sbKit = sbKitClient({ supabaseClients: { server: createServerClient, middleware: createMiddlewareClient, }, options: { authRoutes: { /* ... */ }, redirectPolicy: { /* ... */ }, passwordPolicy: { /* ... */ }, oauthProviders: { /* ... */ }, }, }); ``` -------------------------------- ### AuthRoutes Type Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/types.md Defines all authentication page route paths. All paths must start with a '/'. ```typescript type AuthRoutes = { signIn: string; signUp: string; setPassword: string; forgotPassword: string; oauthCallback: string; }; ``` -------------------------------- ### sbKitClient Initialization Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/sbKitClient.md Initializes the SbKitClient with Supabase client factories and optional configuration. This function is the entry point for setting up authentication features. ```APIDOC ## sbKitClient ### Description Initializes and returns a configured SbKitClient instance, setting up authentication routes, server/middleware handlers, and React components. ### Function Signature ```typescript function sbKitClient({ supabaseClients, options }: SbKitClientInit): SbKitClient ``` ### Parameters #### `supabaseClients` - **Type**: `{ server: ServerClientFactory; middleware: MiddlewareClientFactory }` - **Required**: Yes - **Description**: Supabase client factories for server and middleware contexts. - **`server`** (`() => Promise`) - Required - Async function that returns the server-side Supabase client. - **`middleware`** (`(req: NextRequest) => Promise<{ supabaseResponse: NextResponse; user: User | null; error: AuthError | null }>`) - Required - Async function that handles middleware authentication and returns response with user state. #### `options` - **Type**: `SbKitOptions` - **Required**: No - **Default**: `{}` - **Description**: Configuration object to override default auth routes, redirect policy, password policy, OTP length, and OAuth providers. ### Return Type - **Type**: `SbKitClient` - **Description**: An object containing `routeGuard`, `callbackHandler`, and authentication `components`. ### Properties of `SbKitClient` #### `routeGuard` - **Description**: Middleware function that enforces route-level access control based on authentication state. Use in `middleware.ts` to protect routes. - **Type**: `(request: NextRequest) => Promise` #### `callbackHandler` - **Description**: Handles OAuth callback requests after third-party authentication. Use in `/api/auth/callback` route handler. - **Type**: `(request: Request) => Promise` #### `components` - **Description**: Object containing pre-configured React components for authentication pages. - **`SignIn`**: Sign-in form component (requires `searchParams` prop). - **`SignUp`**: Sign-up form component. - **`SetPassword`**: Component for authenticated users to set a new password. - **`ForgotPassword`**: Component for password recovery requests. - **`AuthWrapper`**: Layout wrapper component providing consistent styling and mounting the Sonner toaster. ``` -------------------------------- ### AuthForm with Separator Components Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/ui-components.md Example of integrating SeparatorWithText within a form to visually separate action buttons. ```typescript import { Separator, SeparatorWithText } from '@sb-kit/ui/components/base/separator'; export function AuthForm() { return ( <> or ); } ``` -------------------------------- ### SignUp Component Usage Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/auth-components.md Demonstrates how to integrate the SignUp component within an AuthWrapper in a Next.js page. Ensure sbKit is imported correctly. ```typescript import { sbKit } from '@/lib/sb-kit'; export default function SignUpPage() { return ( ); } ``` -------------------------------- ### Sonner Toast Notification Setup Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/ui-components.md Integrate SonnerToaster and use the toast function to display notifications within your application. ```typescript import { SonnerToaster } from '@sb-kit/ui/components/base/sonner'; import { toast } from 'sonner'; export function App() { return ( <> ); } ``` -------------------------------- ### Usage Example: cn Utility Function Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/ui-components.md Demonstrates how to use the 'cn' utility function to combine class names conditionally. ```typescript import { cn } from '@sb-kit/ui/lib/utils'; const buttonClass = cn( 'px-4 py-2 rounded', isActive && 'bg-blue-500', className ); ``` -------------------------------- ### Prevent Open Redirect to Attacker Site Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/safe-redirect.md This example demonstrates how the function prevents redirection to an attacker-controlled site by returning the `defaultPathAfterAuth`. ```typescript // Attempt to redirect to attacker's site const maliciousUrl = new URL('https://attacker.com/phish', 'https://example.com'); getSafeRedirectPath(maliciousUrl, config); // Returns defaultPathAfterAuth (not attacker.com) ``` -------------------------------- ### Implement Sign In Page Source: https://github.com/bytaesu/sb-kit/blob/main/apps/docs/content/docs/getting-started.mdx Use the sbKit.components.SignIn component for your sign-in page. This component handles the authentication flow using server actions and accepts search parameters. ```typescript import type { SearchParams } from 'next/dist/server/request/search-params'; import { sbKit } from '@/lib/supabase/sb-kit'; type Props = { searchParams: Promise; }; const SignIn = sbKit.components.SignIn; const Page = ({ searchParams }: Props) => { return ; }; export default Page; ``` -------------------------------- ### authRoutes Type Definition Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/configuration.md Defines the structure for configuring authentication-related route paths within sb-kit. Ensure all paths start with '/'. ```typescript type authRoutes = { signIn: string; signUp: string; setPassword: string; forgotPassword: string; oauthCallback: string; }; ``` -------------------------------- ### Full SB Kit Client Configuration Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/configuration.md Configure the SB Kit client with various options including authentication routes, redirect policies, password requirements, email OTP length, OAuth providers, and route guard policies. Ensure all necessary Supabase client creators are imported. ```typescript import { sbKitClient } from '@sb-kit/core'; const sbKit = sbKitClient({ supabaseClients: { server: createServerClient, middleware: createMiddlewareClient, }, options: { // Auth route paths authRoutes: { signIn: '/login', signUp: '/register', setPassword: '/profile/change-password', forgotPassword: '/reset-password', oauthCallback: '/api/auth/callback', }, // Redirect safety rules redirectPolicy: { allowedHosts: [ 'localhost:3000', 'localhost:5173', 'example.com', 'www.example.com', 'app.example.com', ], blockedPaths: [ '/api/auth/callback', '/api/admin', '/admin', '/.well-known', ], defaultPathAfterAuth: '/dashboard', }, // Password requirements passwordPolicy: { minLength: 12, passwordRule: 'lowercase-uppercase-letters-digits-symbols', }, // Email OTP settings emailOtpLength: 6, // OAuth providers oauthProviders: { github: { buttonText: 'Continue with GitHub' }, google: { buttonText: 'Sign in with Google' }, microsoft: { buttonText: 'Sign in with Microsoft' }, }, // Route access control routeGuardPolicy: { onlyPublic: [ '/login', '/register', '/reset-password', '/pricing', '/documentation', ], onlyPrivate: [ '/dashboard', '/profile', '/settings', '/account', '/billing', ], }, }, }); ``` -------------------------------- ### SB-Kit Client Initialization Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/MANIFEST.txt The main factory function for initializing the SB-Kit client. It allows for component configuration. ```APIDOC ## sbKitClient ### Description Initializes the SB-Kit client with provided configuration. ### Signature `sbKitClient(config: SbKitConfig)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **config** (SbKitConfig) - Required - The configuration object for the SB-Kit client. - **authRoutes** (AuthRoutes) - Required - Defines the paths for authentication-related routes. - **redirectPolicy** (RedirectPolicy) - Optional - Specifies the policy for handling redirects. - **passwordPolicy** (PasswordPolicy) - Optional - Defines the requirements for user passwords. - **emailOtpLength** (number) - Optional - The length of the OTP for email verification. - **oauthProviders** (object) - Optional - Configuration for OAuth providers. - **routeGuardPolicy** (array) - Optional - Policy for route guarding. ### Response #### Success Response (SbKitClient) Returns an instance of the SB-Kit client. ### Request Example ```json { "config": { "authRoutes": { "login": "/login", "register": "/register", "forgotPassword": "/forgot-password", "resetPassword": "/reset-password", "verifyEmail": "/verify-email" }, "redirectPolicy": "KEEP_ORIGINAL", "passwordPolicy": { "minLength": 8, "requireDigit": true }, "emailOtpLength": 6, "oauthProviders": { "google": { "clientId": "YOUR_GOOGLE_CLIENT_ID", "clientSecret": "YOUR_GOOGLE_CLIENT_SECRET" } }, "routeGuardPolicy": ["authenticated", "unauthenticated"] } } ``` ### Response Example ```json { "clientInstance": "" } ``` ``` -------------------------------- ### Implement OAuth Callback Handler Source: https://github.com/bytaesu/sb-kit/blob/main/apps/docs/content/docs/getting-started.mdx Use sbKit.callbackHandler to manage OAuth callbacks. This handler should be exported as the GET request handler for your callback route. ```typescript import { sbKit } from '@/lib/supabase/sb-kit'; const callbackHandler = sbKit.callbackHandler; export { callbackHandler as GET }; ``` -------------------------------- ### signUpAction Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/INDEX.md Registers a new user with the provided email and password. ```APIDOC ## signUpAction ### Description Creates a new user account with the provided email and password. ### Signature `signUpAction(email: string, password: string): Promise>` ### Parameters - **email** (string) - Required - The desired email address for the new account. - **password** (string) - Required - The desired password for the new account. ``` -------------------------------- ### SbKitClientInit Type Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/types.md Initialization parameter object for sbKitClient(). It requires Supabase clients for server and middleware, and optionally accepts configuration overrides. ```typescript type SbKitClientInit = { supabaseClients: { server: ServerClientFactory; middleware: MiddlewareClientFactory; }; options?: SbKitOptions; }; ``` -------------------------------- ### signUpAction Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/server-actions.md Creates a new user account using an email address and password. It handles input validation and interacts with Supabase Auth for user creation. ```APIDOC ## signUpAction ### Description Creates a new user account with email and password. This action validates the input and creates a user in Supabase Auth. ### Method Not applicable (Server Action) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (parameters are passed directly to the function) - **email** (string) - Required - Email address for the new account. Must be a valid RFC 5322 email format and non-empty. - **password** (string) - Required - Password for the new account (1-72 characters). ### Return - **data** (object | null) - Contains `{ userEmail: string }` on success, null on failure. - **errorMessage** (string | null) - `null` on success, or an error message string on failure (e.g., validation error, email already exists). ### Response Example ```json { "data": { "userEmail": "user@example.com" }, "errorMessage": null } ``` ```json { "data": null, "errorMessage": "Some of the data you entered is invalid. Please try again." } ``` ```json { "data": null, "errorMessage": "User already registered" } ``` ### Side Effects - Creates a new user in Supabase Auth. - May trigger email verification flow depending on Supabase configuration. ### Example ```typescript const result = await signUpAction('newuser@example.com', 'SecurePass123'); if (result.errorMessage) { console.error('Sign-up failed:', result.errorMessage); } else { console.log('Account created for:', result.data.userEmail); } ``` ``` -------------------------------- ### Initialize sbKitClient with Supabase Clients Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/README.md Initialize the sbKitClient by providing factory functions for Supabase clients for server and middleware environments. This allows sb-kit to manage authentication state across different contexts. ```typescript const sbKit = sbKitClient({ supabaseClients: { server: () => createServerClient(), // Async factory middleware: (req) => createMiddlewareClient(req), // Async factory }, options: { /* config */ }, }); ``` -------------------------------- ### forgotPasswordAction TypeScript Example Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/server-actions.md Use this action to initiate a password reset flow. It sends a recovery email to the specified address. Ensure the email is valid and the user exists. ```typescript const handleForgotPassword = async (email: string) => { const result = await forgotPasswordAction(email); if (result.errorMessage) { setError(result.errorMessage); } else { toast.success(`Recovery email sent to ${result.data.userEmail}`); setEmail(''); } }; ``` -------------------------------- ### Sign Up User with Email and Password Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/server-actions.md Creates a new user account using an email address and password. It validates inputs and interacts with Supabase Auth. Handles potential validation errors or existing user conflicts. ```typescript function signUpAction(email: string, password: string): Promise> ``` ```typescript // Success { data: { userEmail: "user@example.com" }, errorMessage: null } // Failure (validation error) { data: null, errorMessage: "Some of the data you entered is invalid. Please try again." } // Failure (email already exists) { data: null, errorMessage: "User already registered" } // From Supabase ``` ```typescript const result = await signUpAction('newuser@example.com', 'SecurePass123'); if (result.errorMessage) { console.error('Sign-up failed:', result.errorMessage); } else { console.log('Account created for:', result.data.userEmail); // Typically redirect to verify email page or sign-in } ``` -------------------------------- ### Import Paths for SB Kit UI Components Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/ui-components.md Shows individual import paths for various UI components and the 'cn' utility function from the '@sb-kit/ui' package. All components are fully typed and support TypeScript. ```typescript import { Button } from '@sb-kit/ui/components/base/button'; import { Input } from '@sb-kit/ui/components/base/input'; import { Card, CardHeader, CardContent, CardFooter, CardTitle } from '@sb-kit/ui/components/base/card'; import { Spinner } from '@sb-kit/ui/components/base/spinner'; import { Label } from '@sb-kit/ui/components/base/label'; import { Separator, SeparatorWithText } from '@sb-kit/ui/components/base/separator'; import { InputOTP } from '@sb-kit/ui/components/base/input-otp'; import { Form } from '@sb-kit/ui/components/base/form'; import { SonnerToaster } from '@sb-kit/ui/components/base/sonner'; import { cn } from '@sb-kit/ui/lib/utils'; ``` -------------------------------- ### Interface for Existing Supabase Client Utilities Source: https://github.com/bytaesu/sb-kit/blob/main/apps/docs/content/docs/getting-started.mdx Define the expected shape for server-side and middleware Supabase client utility functions if you are integrating with an existing Supabase client setup. ```typescript import type { NextRequest, NextResponse } from 'next/server'; import type { AuthError, SupabaseClient, User } from '@supabase/supabase-js'; /** * Server-side Supabase client */ async function serverClient(): Promise { // return your server client } /** * Middleware Supabase client */ async function middlewareClient(request: NextRequest): Promise<{ supabaseResponse: NextResponse; user: User | null; error: AuthError | null; }> { // return your middleware client } ``` -------------------------------- ### UI Components in sb-kit Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/README.md List of available UI components provided by the `@sb-kit/ui` package. These can be used to build user interfaces for authentication flows. ```typescript Button, Input, Card, Label, Spinner, Separator, InputOTP, Form ``` -------------------------------- ### setPasswordAction TypeScript Example Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/server-actions.md Use this action to update the password for the currently authenticated user. It requires the current password for verification and enforces length constraints. This action also signs out other active sessions. ```typescript const handleSetPassword = async (oldPassword: string, newPassword: string) => { const result = await setPasswordAction(oldPassword, newPassword); if (result.errorMessage) { setError(result.errorMessage); } else { toast.success('Password updated successfully'); // Optionally redirect } }; ``` -------------------------------- ### Integrate sb-kit Hooks with Components Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/hooks.md Demonstrates how to use the `useRedirectUrl` and `useEmailOtpFlow` hooks within a React component, integrating with sb-kit's `AuthWrapper` and `SignIn` components. ```typescript 'use client'; import { sbKitClient } from '@sb-kit/core'; import { useRedirectUrl, useEmailOtpFlow } from '@sb-kit/core'; const sbKit = sbKitClient({ /* ... */ }); export function AuthPage() { const redirectUrl = useRedirectUrl(); const emailFlow = useEmailOtpFlow(); return ( ); } ``` -------------------------------- ### Usage Example of useRedirectUrl Hook Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/api-reference/hooks.md Demonstrates how to use the useRedirectUrl hook within a client component to handle form submissions and redirects. It shows how to integrate the hook with Next.js router and authentication actions. ```typescript 'use client'; import { useRedirectUrl } from '@sb-kit/core'; import { signInAction } from '@sb-kit/core/actions'; import { useRouter } from 'next/navigation'; export function SignInForm() { const router = useRouter(); const redirectUrl = useRedirectUrl(); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [error, setError] = useState(null); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); const result = await signInAction(email, password); if (result.errorMessage) { setError(result.errorMessage); } else { // Redirect to original requested page or dashboard router.push(redirectUrl || '/dashboard'); } }; return (
{error &&

{error}

} setEmail(e.target.value)} type="email" required /> setPassword(e.target.value)} type="password" required />
); } ``` -------------------------------- ### SignUp Component Source: https://github.com/bytaesu/sb-kit/blob/main/_autodocs/INDEX.md A React component that renders the sign-up form. ```APIDOC ## SignUp Component ### Description Renders the user interface for the sign-up form. ### Usage ```jsx import { sbKitClient } from '@sb-kit/core'; const { components } = sbKitClient({ /* init options */ }); function SignUpPage() { return ; } ``` ```