### Install Dependencies (Bash) Source: https://github.com/makerkit/nextjs-saas-starter-kit-lite/wiki/Installation Installs all project dependencies using PNPM. Ensure you have PNPM installed globally before running this command. ```bash pnpm install ``` -------------------------------- ### Start Supabase (Bash) Source: https://github.com/makerkit/nextjs-saas-starter-kit-lite/wiki/Installation Starts the Supabase services using PNPM. This command requires a running Docker daemon and makes Supabase accessible locally. ```bash pnpm run supabase:start ``` -------------------------------- ### Start Development Server (Bash) Source: https://github.com/makerkit/nextjs-saas-starter-kit-lite/wiki/Installation Starts the Next.js development server. The application will then be accessible at http://localhost:3000. ```bash pnpm run dev ``` -------------------------------- ### Clone Repository (Bash) Source: https://github.com/makerkit/nextjs-saas-starter-kit-lite/wiki/Installation Clones the Next.js SaaS Starter Kit Lite repository from GitHub. This is the first step to get the project files onto your local machine. ```bash git clone https://github.com/makerkit/next-supabase-saas-kit-lite.git ``` -------------------------------- ### Format Code (Bash) Source: https://github.com/makerkit/nextjs-saas-starter-kit-lite/wiki/Installation Formats the project's code according to predefined style guidelines. This command helps maintain code consistency. ```bash pnpm run format:fix ``` -------------------------------- ### Supabase CLI Commands (Bash) Source: https://github.com/makerkit/nextjs-saas-starter-kit-lite/wiki/Installation A collection of common Supabase CLI commands executed via PNPM filters. These include creating migrations, linking to a Supabase project, and pushing database changes. ```bash # Create new migration pnpm --filter web supabase migration new # Link to Supabase project pnpm --filter web supabase db link # Push migrations pnpm --filter web supabase db push ``` -------------------------------- ### Push Supabase Database Migration (Bash) Source: https://github.com/makerkit/nextjs-saas-starter-kit-lite/blob/main/README.md This command pushes local database migration changes to your Supabase project. Ensure you have pnpm installed and are in the correct project directory. ```bash pnpm --filter web supabase db push ``` -------------------------------- ### Reset Supabase (Bash) Source: https://github.com/makerkit/nextjs-saas-starter-kit-lite/wiki/Installation Resets the Supabase server to its initial state. This is useful for clearing data and configurations. ```bash pnpm run supabase:web:reset ``` -------------------------------- ### Stop Supabase (Bash) Source: https://github.com/makerkit/nextjs-saas-starter-kit-lite/wiki/Installation Stops the Supabase server. Use this command to gracefully shut down Supabase services when not needed. ```bash pnpm run supabase:web:stop ``` -------------------------------- ### Initialize Server-Side i18n for Server Components Source: https://context7.com/makerkit/nextjs-saas-starter-kit-lite/llms.txt Demonstrates how to initialize the i18n instance for server-side rendering and React Server Components. It uses `initializeServerI18n` with dynamic import of translation files. The example shows how to fetch translations and use the `t` function to translate strings in a server component. ```typescript import { initializeServerI18n } from '@kit/i18n/server'; // i18n configuration const i18nSettings = { lng: 'en', fallbackLng: 'en', supportedLngs: ['en', 'es', 'fr'], ns: ['common', 'auth', 'account'], defaultNS: 'common' }; // Initialize in a server component async function getI18n(language: string) { const i18n = await initializeServerI18n( { ...i18nSettings, lng: language }, async (lang, namespace) => { // Dynamic import of translation files return import(`./locales/${lang}/${namespace}.json`); } ); return i18n; } // Usage in a Server Component export default async function Page() { const i18n = await getI18n('en'); return (

{i18n.t('common:welcome')}

{i18n.t('auth:signInPrompt')}

); } ``` -------------------------------- ### Install Shadcn UI Component - Bash Source: https://github.com/makerkit/nextjs-saas-starter-kit-lite/blob/main/packages/ui/README.md Installs a Shadcn UI component into the @kit/ui package. This command requires the shadcn-ui CLI to be installed globally or via npx. It takes the component name as an argument and specifies the target directory. ```bash npx shadcn@latest add -c packages/ui ``` ```bash npx shadcn-ui@latest add button -c packages/ui ``` -------------------------------- ### Create Consistent Dashboard Layouts with Page Components Source: https://context7.com/makerkit/nextjs-saas-starter-kit-lite/llms.txt Provides pre-built page layout components for creating consistent dashboard interfaces. It utilizes `PageHeader` and `PageBody` for structure, and `Card` components for displaying key metrics or information. This example showcases a simple dashboard with user and revenue statistics. ```tsx import { PageBody, PageHeader } from '@kit/ui/page'; import { Card, CardHeader, CardTitle, CardContent } from '@kit/ui/card'; export default function DashboardPage() { return ( <>
Total Users

1,234

Revenue

$45,231

); } ``` -------------------------------- ### Install @kit/supabase Package Source: https://github.com/makerkit/nextjs-saas-starter-kit-lite/blob/main/packages/supabase/README.md This JSON snippet demonstrates how to add the `@kit/supabase` package as a dependency in your application's package.json file. This is a prerequisite for using the Supabase client and utilities provided by the package. ```json { "name": "my-app", "dependencies": { "@kit/supabase": "*" } } ``` -------------------------------- ### Get Supabase Server Client for Server Components and API Routes Source: https://context7.com/makerkit/nextjs-saas-starter-kit-lite/llms.txt Generates a Supabase client for server components and API routes, enabling secure session handling through automatic cookie management. It allows fetching user claims and interacting with the database on the server. ```typescript import { getSupabaseServerClient } from '@kit/supabase/server-client'; // In a Server Component or API Route export async function GET() { const client = getSupabaseServerClient(); // Get the current user's JWT claims const { data, error } = await client.auth.getClaims(); if (data?.claims) { // User is authenticated const userId = data.claims.sub; // Fetch user's account data const { data: account } = await client .from('accounts') .select('*') .eq('id', userId) .single(); return Response.json({ account }); } return Response.json({ error: 'Unauthorized' }, { status: 401 }); } ``` -------------------------------- ### Get Supabase Browser Client for Typed Database Access Source: https://context7.com/makerkit/nextjs-saas-starter-kit-lite/llms.txt Creates a Supabase client for browser/client components. It automatically handles cookies and provides type safety for your database schema, ensuring robust data interactions. ```typescript import { getSupabaseBrowserClient } from '@kit/supabase/browser-client'; import { Database } from '@kit/supabase/database'; // Get a typed Supabase client for browser usage const client = getSupabaseBrowserClient(); // Query data from your database const { data, error } = await client .from('accounts') .select('id, name, picture_url') .eq('id', userId) .single(); // Sign in with email and password const { data: authData, error: authError } = await client.auth.signInWithPassword({ email: 'user@example.com', password: 'securepassword123' }); // Sign out the user await client.auth.signOut(); ``` -------------------------------- ### Lint Code (Bash) Source: https://github.com/makerkit/nextjs-saas-starter-kit-lite/wiki/Installation Lints the project's code to identify potential errors and style issues. This command helps improve code quality. ```bash pnpm run lint ``` -------------------------------- ### Typecheck Code (Bash) Source: https://github.com/makerkit/nextjs-saas-starter-kit-lite/wiki/Installation Validates the TypeScript code for type errors. This command ensures type safety within the application. ```bash pnpm run typecheck ``` -------------------------------- ### Get Supabase Server Admin Client for Privileged Operations Source: https://context7.com/makerkit/nextjs-saas-starter-kit-lite/llms.txt Provides an admin Supabase client using the service role key for server-side operations that bypass Row Level Security (RLS). Use this with caution for administrative tasks like user deletion. ```typescript import { getSupabaseServerAdminClient } from '@kit/supabase/server-admin-client'; // Server-side admin operations (use with caution) async function deleteUserAccount(userId: string) { const adminClient = getSupabaseServerAdminClient(); // Delete user's account (bypasses RLS) const { error: accountError } = await adminClient .from('accounts') .delete() .eq('id', userId); if (accountError) { throw new Error(`Failed to delete account: ${accountError.message}`); } // Delete the auth user const { error: authError } = await adminClient.auth.admin.deleteUser(userId); if (authError) { throw new Error(`Failed to delete auth user: ${authError.message}`); } return { success: true }; } ``` -------------------------------- ### Get Authenticated User with useUser Hook (TypeScript) Source: https://context7.com/makerkit/nextjs-saas-starter-kit-lite/llms.txt The `useUser` hook retrieves the current authenticated user's JWT claims, leveraging React Query for caching. It simplifies displaying user-specific information and handling loading or error states. This hook requires the '@kit/supabase/hooks/use-user' package. ```typescript import { useUser } from '@kit/supabase/hooks/use-user'; function ProfileComponent() { const { data: user, isLoading, error } = useUser(); if (isLoading) { return
Loading...
; } if (error || !user) { return
Please sign in to view your profile
; } return (

Welcome, {user.email}

User ID: {user.sub}

Role: {user.role}

); } ``` -------------------------------- ### Cached User Authentication for Server Components (TypeScript) Source: https://context7.com/makerkit/nextjs-saas-starter-kit-lite/llms.txt The `requireUserInServerComponent` function provides a cached mechanism for verifying user authentication within React Server Components. This prevents redundant database calls within the same request lifecycle, improving performance. It automatically handles redirection if the user is not authenticated. Usage is straightforward, awaiting the function to get the user object. ```typescript import { requireUserInServerComponent } from '~/lib/server/require-user-in-server-component'; // In a Server Component export default async function DashboardPage() { // Automatically redirects if not authenticated const user = await requireUserInServerComponent(); // Fetch user-specific data const dashboardData = await fetchDashboardData(user.id); return (

Welcome back, {user.email}

); } // Can be called multiple times in the same request without extra DB calls async function DashboardHeader() { const user = await requireUserInServerComponent(); // Cached result return
Logged in as: {user.email}
; } ``` -------------------------------- ### Supabase CLI Commands - PNPM Source: https://github.com/makerkit/nextjs-saas-starter-kit-lite/blob/main/README.md A collection of common Supabase CLI commands executed via PNPM for managing migrations, linking to projects, and pushing database changes. ```bash # Create new migration pnpm --filter web supabase migration new # Link to Supabase project pnpm --filter web supabase link # Push migrations pnpm --filter web supabase db push ``` -------------------------------- ### Define Application Paths for Navigation (TypeScript) Source: https://context7.com/makerkit/nextjs-saas-starter-kit-lite/llms.txt Centralizes all application routes for consistent navigation. It defines paths for authentication flows (sign-in, sign-up, password reset) and application-specific routes (home, settings). ```typescript // config/paths.config.ts const pathsConfig = { auth: { signIn: '/auth/sign-in', signUp: '/auth/sign-up', verifyMfa: '/auth/verify', callback: '/auth/callback', passwordReset: '/auth/password-reset', passwordUpdate: '/update-password' }, app: { home: '/home', profileSettings: '/home/settings' } }; export default pathsConfig; ``` -------------------------------- ### Generate Magic Link for User Login (HTML/Go Template) Source: https://github.com/makerkit/nextjs-saas-starter-kit-lite/blob/main/apps/web/supabase/templates/magic-link.html This snippet demonstrates how to generate a magic link for user authentication within an HTML template. It uses Go template syntax to embed dynamic data like SiteURL, TokenHash, and RedirectTo. The link is presented in both clickable and copy-paste formats. ```go-template

Your sign in link to Makerkit

Login to Makerkit

=================

Follow this link to login

Login to Makerkit

or copy and paste this URL into your browser:

{{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=magiclink&callback={{ .RedirectTo }}

Makerkit ``` -------------------------------- ### Configure Authentication Providers and Captcha (TypeScript) Source: https://context7.com/makerkit/nextjs-saas-starter-kit-lite/llms.txt Sets up authentication configurations, including optional Cloudflare Turnstile captcha and display of terms checkbox. It also enables or disables password and magic link authentication, and defines OAuth providers. Dependencies include environment variables. ```typescript // config/auth.config.ts import { z } from 'zod'; const authConfig = { // Cloudflare Turnstile captcha (optional) captchaTokenSiteKey: process.env.NEXT_PUBLIC_CAPTCHA_SITE_KEY, // Show terms checkbox on sign-up displayTermsCheckbox: process.env.NEXT_PUBLIC_DISPLAY_TERMS_AND_CONDITIONS_CHECKBOX === 'true', providers: { // Enable email/password auth password: process.env.NEXT_PUBLIC_AUTH_PASSWORD === 'true', // Enable magic link auth magicLink: process.env.NEXT_PUBLIC_AUTH_MAGIC_LINK === 'true', // OAuth providers (must be enabled in Supabase dashboard) oAuth: ['google', 'github'] as const } }; export default authConfig; ``` -------------------------------- ### Configure App Settings with Zod Validation (TypeScript) Source: https://context7.com/makerkit/nextjs-saas-starter-kit-lite/llms.txt Defines type-safe application configuration using Zod for validation. It parses environment variables to set application name, title, URL, locale, theme, and production status. Dependencies include 'zod'. ```typescript // config/app.config.ts import { z } from 'zod'; const AppConfigSchema = z.object({ name: z.string().min(1), title: z.string().min(1), description: z.string(), url: z.string().url(), locale: z.string().default('en'), theme: z.enum(['light', 'dark', 'system']), production: z.boolean(), themeColor: z.string(), themeColorDark: z.string() }); const appConfig = AppConfigSchema.parse({ name: process.env.NEXT_PUBLIC_PRODUCT_NAME, title: process.env.NEXT_PUBLIC_SITE_TITLE, description: process.env.NEXT_PUBLIC_SITE_DESCRIPTION, url: process.env.NEXT_PUBLIC_SITE_URL, locale: process.env.NEXT_PUBLIC_DEFAULT_LOCALE, theme: process.env.NEXT_PUBLIC_DEFAULT_THEME_MODE, themeColor: process.env.NEXT_PUBLIC_THEME_COLOR, themeColorDark: process.env.NEXT_PUBLIC_THEME_COLOR_DARK, production: process.env.NODE_ENV === 'production' }); export default appConfig; ``` -------------------------------- ### Email Confirmation URL Generation (Go Template) Source: https://github.com/makerkit/nextjs-saas-starter-kit-lite/blob/main/apps/web/supabase/templates/confirm-email.html This Go template snippet demonstrates how to construct the confirmation URL for user emails. It includes the site URL, a token hash, the email type, and a redirect callback URL. ```go-template [Login to Makerkit]({{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=email&callback={{ .RedirectTo }}) or copy and paste this URL into your browser: [{{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=email&callback={{ .RedirectTo }}]({{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=email&callback={{ .RedirectTo }}) ``` -------------------------------- ### Create Supabase Middleware Client for Session Validation Source: https://context7.com/makerkit/nextjs-saas-starter-kit-lite/llms.txt Creates a Supabase client specifically for Next.js middleware. It facilitates session validation and route protection by inspecting authentication claims and managing redirects. ```typescript import { NextRequest, NextResponse } from 'next/server'; import { createMiddlewareClient } from '@kit/supabase/middleware-client'; export async function middleware(request: NextRequest) { const response = NextResponse.next(); const supabase = createMiddlewareClient(request, response); // Verify user session const { data } = await supabase.auth.getClaims(); // Protect routes under /home/* if (request.nextUrl.pathname.startsWith('/home')) { if (!data?.claims) { // Redirect to sign-in with return URL const signInUrl = new URL('/auth/sign-in', request.url); signInUrl.searchParams.set('next', request.nextUrl.pathname); return NextResponse.redirect(signInUrl); } } // Redirect authenticated users away from auth pages if (request.nextUrl.pathname.startsWith('/auth') && data?.claims) { return NextResponse.redirect(new URL('/home', request.url)); } return response; } ``` -------------------------------- ### Client-Side Translation with Trans Component Source: https://context7.com/makerkit/nextjs-saas-starter-kit-lite/llms.txt Shows how to use the `Trans` component for client-side translations with interpolation support. This component allows for simple translations, translations with fallbacks, and translations with dynamic values passed via the `values` prop. The interpolation syntax in translation files is `{{key}}`. ```tsx import { Trans } from '@kit/ui/trans'; function WelcomeMessage({ userName }: { userName: string }) { return (
{/* Simple translation */}

{/* With fallback */}

{/* With interpolation (in translation file: "Hello, {{name}}!") */}

); } ``` -------------------------------- ### OAuth Callback Service for API Routes (TypeScript) Source: https://context7.com/makerkit/nextjs-saas-starter-kit-lite/llms.txt A service for handling OAuth callbacks and token verification within Next.js API routes. It abstracts the logic for exchanging authorization codes for session tokens and verifying token hashes for email-based authentication. ```typescript import { redirect } from 'next/navigation'; import type { NextRequest } from 'next/server'; import { createAuthCallbackService } from '@kit/supabase/auth'; import { getSupabaseServerClient } from '@kit/supabase/server-client'; // OAuth callback handler export async function GET(request: NextRequest) { const service = createAuthCallbackService(getSupabaseServerClient()); const { nextPath } = await service.exchangeCodeForSession(request, { redirectPath: '/home', errorPath: '/auth/callback/error' }); return redirect(nextPath); } // Email verification callback (magic link or email confirmation) export async function GET(request: NextRequest) { const service = createAuthCallbackService(getSupabaseServerClient()); const redirectUrl = await service.verifyTokenHash(request, { redirectPath: '/home', errorPath: '/auth/callback/error' }); return redirect(redirectUrl.toString()); } ``` -------------------------------- ### Sign-In Methods Container Component (TypeScript/React) Source: https://context7.com/makerkit/nextjs-saas-starter-kit-lite/llms.txt The `SignInMethodsContainer` is a pre-built React component designed to render various sign-in options for a SaaS application. It supports password-based, magic link, and OAuth providers. Configuration for paths and providers is passed via props, allowing for easy integration into custom sign-in pages. This component simplifies the UI implementation of authentication flows. ```tsx import { SignInMethodsContainer } from '@kit/auth/sign-in'; import authConfig from '~/config/auth.config'; import pathsConfig from '~/config/paths.config'; export default function SignInPage() { return (

Sign In

); } ``` -------------------------------- ### Use Generated Database Types for Accounts (TypeScript) Source: https://context7.com/makerkit/nextjs-saas-starter-kit-lite/llms.txt Demonstrates how to use generated TypeScript types for interacting with the 'accounts' database table. It defines types for reading, inserting, and updating account data, providing type safety for database operations. Dependencies include '@kit/supabase/database'. ```typescript // TypeScript usage with generated types import { Database } from '@kit/supabase/database'; type Account = Database['public']['Tables']['accounts']['Row']; type AccountInsert = Database['public']['Tables']['accounts']['Insert']; type AccountUpdate = Database['public']['Tables']['accounts']['Update']; // Example: Update account const updateData: AccountUpdate = { name: 'New Name', picture_url: 'https://example.com/avatar.png', updated_at: new Date().toISOString() }; ``` -------------------------------- ### Access Supabase Client with useSupabase Hook (TypeScript) Source: https://context7.com/makerkit/nextjs-saas-starter-kit-lite/llms.txt The `useSupabase` hook provides memoized access to the Supabase browser client within React components. It simplifies data fetching and file uploads by abstracting direct Supabase client interactions. Dependencies include the '@kit/supabase/hooks/use-supabase' package. ```typescript import { useSupabase } from '@kit/supabase/hooks/use-supabase'; function MyComponent() { const client = useSupabase(); async function fetchData() { const { data, error } = await client .from('accounts') .select('*') .limit(10); if (error) { console.error('Query failed:', error); return; } return data; } async function uploadFile(file: File, accountId: string) { const { data, error } = await client.storage .from('account_image') .upload(`${accountId}.png`, file, { upsert: true }); return { data, error }; } return
...
; } ``` -------------------------------- ### Zod Schemas for Authentication Form Validation (TypeScript) Source: https://context7.com/makerkit/nextjs-saas-starter-kit-lite/llms.txt Provides Zod schemas for validating email and password fields in sign-in and sign-up forms. The sign-up schema includes an additional field for password confirmation and supports configurable password requirements. ```typescript import { z } from 'zod'; import { PasswordSignInSchema } from '@kit/auth/sign-in'; import { PasswordSignUpSchema } from '@kit/auth/sign-up'; // Sign-in validation const signInData = { email: 'user@example.com', password: 'mypassword123' }; const signInResult = PasswordSignInSchema.safeParse(signInData); if (!signInResult.success) { console.error('Validation errors:', signInResult.error.flatten()); } // Sign-up validation (includes password confirmation) const signUpData = { email: 'newuser@example.com', password: 'SecurePass123!', repeatPassword: 'SecurePass123!' }; const signUpResult = PasswordSignUpSchema.safeParse(signUpData); if (!signUpResult.success) { // Handle validation errors like: // - Passwords don't match // - Missing special characters (if required) // - Missing numbers (if required) // - Missing uppercase (if required) console.error('Sign up validation failed:', signUpResult.error.issues); } ``` -------------------------------- ### Set Runtime to Edge (TypeScript) Source: https://github.com/makerkit/nextjs-saas-starter-kit-lite/blob/main/README.md This configuration snippet sets the runtime environment for a Next.js application to 'edge'. This is often required for deployment on platforms like Cloudflare Workers. It should be placed in the root layout file. ```typescript export const runtime = 'edge'; ``` -------------------------------- ### Build Validated Forms with React Hook Form and Zod Source: https://context7.com/makerkit/nextjs-saas-starter-kit-lite/llms.txt Demonstrates how to create forms with validation using `react-hook-form` and `zod`. It includes input fields for name, email, and an optional bio, along with a submit button. This component is designed for client-side rendering. ```tsx 'use client'; import { useForm } from 'react-hook-form'; import { zodResolver } from '@hookform/resolvers/zod'; import { z } from 'zod'; import { Form, FormField, FormItem, FormLabel, FormControl, FormDescription, FormMessage } from '@kit/ui/form'; import { Input } from '@kit/ui/input'; import { Button } from '@kit/ui/button'; const ProfileSchema = z.object({ name: z.string().min(2, 'Name must be at least 2 characters'), email: z.string().email('Invalid email address'), bio: z.string().max(200).optional() }); type ProfileFormData = z.infer; function ProfileForm({ onSubmit }: { onSubmit: (data: ProfileFormData) => void }) { const form = useForm({ resolver: zodResolver(ProfileSchema), defaultValues: { name: '', email: '', bio: '' } }); return (
( Display Name This is your public display name. )} /> ( Email )} /> ); } ``` -------------------------------- ### Enhance Server Actions with Auth, Captcha, and Validation (TypeScript) Source: https://context7.com/makerkit/nextjs-saas-starter-kit-lite/llms.txt The `enhanceAction` utility wraps server actions to automatically handle authentication, reCAPTCHA verification, and Zod schema validation. It simplifies the process of creating secure and robust server-side logic by abstracting common middleware. Dependencies include 'zod' for schema definition and '@kit/next/actions' for the enhancement function. ```typescript 'use server'; import { z } from 'zod'; import { enhanceAction } from '@kit/next/actions'; // Define your schema const UpdateProfileSchema = z.object({ name: z.string().min(1).max(255), bio: z.string().max(500).optional() }); // Create an enhanced action with auth and validation export const updateProfileAction = enhanceAction( async (data, user) => { // `user` is guaranteed to be authenticated (JwtPayload) // `data` is validated against the schema const { name, bio } = data; // Perform your database update const client = getSupabaseServerClient(); const { error } = await client .from('accounts') .update({ name, bio }) .eq('id', user.id); if (error) { throw new Error('Failed to update profile'); } return { success: true }; }, { auth: true, // Require authentication (default: true) schema: UpdateProfileSchema, captcha: false // Require captcha token (default: false) } ); // Action without authentication requirement export const publicAction = enhanceAction( async (data) => { return { message: 'This is a public action', data }; }, { auth: false, schema: z.object({ email: z.string().email() }) } ); // Action with captcha protection const ContactFormSchema = z.object({ email: z.string().email(), message: z.string().min(10), captchaToken: z.string() }); export const submitContactForm = enhanceAction( async (data, user) => { // captchaToken is automatically verified before this runs return { success: true }; }, { auth: false, captcha: true, schema: ContactFormSchema } ); ``` -------------------------------- ### Define Accounts Database Table with RLS (SQL) Source: https://context7.com/makerkit/nextjs-saas-starter-kit-lite/llms.txt Defines the 'accounts' table in the database with columns for user information, timestamps, and references to authentication users. It enables Row Level Security (RLS) to restrict data access based on user authentication. Dependencies include 'uuid-ossp' extension for UUID generation. ```sql -- Accounts table definition CREATE TABLE public.accounts ( id UUID PRIMARY KEY DEFAULT extensions.uuid_generate_v4(), name VARCHAR(255) NOT NULL, email VARCHAR(320) UNIQUE, picture_url VARCHAR(1000), public_data JSONB DEFAULT '{}'::JSONB NOT NULL, created_at TIMESTAMP WITH TIME ZONE, updated_at TIMESTAMP WITH TIME ZONE, created_by UUID REFERENCES auth.users, updated_by UUID REFERENCES auth.users ); -- Enable Row Level Security ALTER TABLE public.accounts ENABLE ROW LEVEL SECURITY; -- Users can only read their own account CREATE POLICY accounts_read ON public.accounts FOR SELECT TO authenticated USING ((SELECT auth.uid()) = id); -- Users can only update their own account CREATE POLICY accounts_update ON public.accounts FOR UPDATE TO authenticated USING ((SELECT auth.uid()) = id) WITH CHECK ((SELECT auth.uid()) = id); ``` -------------------------------- ### Fetch User Account Data with usePersonalAccountData Hook (TypeScript) Source: https://context7.com/makerkit/nextjs-saas-starter-kit-lite/llms.txt The `usePersonalAccountData` hook fetches and caches the current user's account data from the database using React Query. It simplifies displaying account-specific information like profile pictures and names. This hook requires the '@kit/accounts/hooks' package. ```typescript import { usePersonalAccountData } from '@kit/accounts/hooks'; function AccountSettings({ userId }: { userId: string }) { const { data: account, isLoading, error } = usePersonalAccountData(userId); if (isLoading) return
Loading account...
; if (error) return
Error loading account
; return (
{account?.name

{account?.name}

); } ``` -------------------------------- ### Button UI Component (TypeScript/TSX) Source: https://context7.com/makerkit/nextjs-saas-starter-kit-lite/llms.txt A versatile Button component for React applications, built using class-variance-authority for easy styling variations. It supports multiple variants, sizes, and can render as other HTML elements. ```tsx import { Button } from '@kit/ui/button'; function ActionButtons() { return (
{/* Default primary button */} {/* Destructive action */} {/* Secondary button */} {/* Outline button */} {/* Ghost button (minimal styling) */} {/* Link style button */} {/* Different sizes */} {/* As child - render as another element */}
); } ``` -------------------------------- ### Verify User Authentication and MFA Status (TypeScript) Source: https://context7.com/makerkit/nextjs-saas-starter-kit-lite/llms.txt The `requireUser` function is a server-side utility designed to verify if a user is authenticated and has completed Multi-Factor Authentication (MFA). It takes a Supabase client instance and returns either an error object with redirection information or the authenticated user data. This is crucial for protecting sensitive server-side operations. ```typescript import { requireUser } from '@kit/supabase/require-user'; import { getSupabaseServerClient } from '@kit/supabase/server-client'; async function protectedServerFunction() { const client = getSupabaseServerClient(); const result = await requireUser(client); if (result.error) { // Handle authentication errors if (result.error.message === 'Authentication required') { // User is not logged in return { redirect: result.redirectTo }; // '/auth/sign-in' } if (result.error.message === 'Multi-factor authentication required') { // User needs to complete MFA return { redirect: result.redirectTo }; // '/auth/verify' } } // User is authenticated and MFA verified const user = result.data; console.log('Authenticated user:', user.email, user.id); return { user }; } ``` -------------------------------- ### Listen to Auth Changes with useAuthChangeListener Hook (TypeScript) Source: https://context7.com/makerkit/nextjs-saas-starter-kit-lite/llms.txt The `useAuthChangeListener` hook subscribes to Supabase authentication state changes, enabling automatic redirects and event handling. It accepts configuration for application paths and an `onEvent` callback for custom logic. This hook is part of '@kit/supabase/hooks/use-auth-change-listener'. ```typescript import { useAuthChangeListener } from '@kit/supabase/hooks/use-auth-change-listener'; function AuthProvider({ children }: { children: React.ReactNode }) { useAuthChangeListener({ appHomePath: '/home', privatePathPrefixes: ['/home', '/settings', '/dashboard'], onEvent: (event, session) => { if (event === 'SIGNED_IN') { console.log('User signed in:', session?.user?.email); } if (event === 'SIGNED_OUT') { console.log('User signed out'); } if (event === 'TOKEN_REFRESHED') { console.log('Session refreshed'); } } }); return <>{children}; } ``` -------------------------------- ### Email Confirmation HTML Styling Source: https://github.com/makerkit/nextjs-saas-starter-kit-lite/blob/main/apps/web/supabase/templates/confirm-email.html This CSS styles the body of the email confirmation page, setting the background color, margins, font family, and text color for a clean and consistent appearance. ```css body { background-color: #fff; margin: auto; font-family: sans-serif; color: #484848; } ``` -------------------------------- ### Update Account Data with useUpdateAccountData Hook (TypeScript) Source: https://context7.com/makerkit/nextjs-saas-starter-kit-lite/llms.txt The `useUpdateAccountData` hook facilitates updating account data using React Query mutations. It also includes `useRevalidatePersonalAccountDataQuery` to refresh cached data after an update. This hook is part of the '@kit/accounts/hooks' package and handles form submissions and error logging. ```typescript import { useUpdateAccountData } from '@kit/accounts/hooks'; import { useRevalidatePersonalAccountDataQuery } from '@kit/accounts/hooks'; function EditProfileForm({ accountId }: { accountId: string }) { const updateAccount = useUpdateAccountData(accountId); const revalidate = useRevalidatePersonalAccountDataQuery(); async function handleSubmit(formData: { name: string; picture_url?: string }) { try { await updateAccount.mutateAsync({ name: formData.name, picture_url: formData.picture_url, updated_at: new Date().toISOString() }); // Revalidate the cached account data await revalidate(accountId); console.log('Profile updated successfully'); } catch (error) { console.error('Failed to update profile:', error); } } return (
{ e.preventDefault(); handleSubmit({ name: 'New Name' }); }}>
); } ``` -------------------------------- ### Enhance Next.js Server Action with Options Source: https://github.com/makerkit/nextjs-saas-starter-kit-lite/blob/main/packages/next/README.md The `enhanceAction` function wraps a Next.js Server Action to add functionality like schema validation, captcha enforcement, and exception capturing. It takes the action function and an options object as arguments. The options can include `captcha`, `schema`, and `captureException`. Data is automatically parsed and validated against the schema, and the user is authenticated. ```typescript import { enhanceAction } from '@kit/next/actions'; import { z } from 'zod'; export const myServerAction = enhanceAction(async (data, user) => { // 'data' is typed according to the schema // 'user' is the authenticated user object // If 'captcha' is true, 'captchaToken' must be provided in the body. return { success: true }; }, { captcha: true, schema: z.object({ id: z.number() }), captureException: true }); // Example of calling the enhanced action: // const result = await myServerAction({ id: 1 }); // or with captcha token: // const result = await myServerAction({ id: 1, captchaToken: 'captchaToken' }); ``` -------------------------------- ### Password Reset Link Generation (Markdown) Source: https://github.com/makerkit/nextjs-saas-starter-kit-lite/blob/main/apps/web/supabase/templates/reset-password.html Generates a password reset link using Markdown syntax. It includes a button that links to a confirmation URL and a fallback plain text URL. This is commonly used in email templates for password recovery. ```markdown [Reset Password]({{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=recovery&next={{ .RedirectTo }}) or copy and paste this URL into your browser: [{{ .ConfirmationURL }}]({{ .ConfirmationURL }}) ``` -------------------------------- ### Enhance Next.js Route Handler with Options Source: https://github.com/makerkit/nextjs-saas-starter-kit-lite/blob/main/packages/next/README.md The `enhanceRouteHandler` function wraps a Next.js API Route Handler to provide similar enhancements to `enhanceAction`, including schema validation, captcha enforcement, and exception capturing. It accepts the route handler function and an options object. Captcha tokens are expected in the `x-captcha-token` header. ```typescript import { enhanceRouteHandler } from '@kit/next/routes'; import { z } from 'zod'; export const POST = enhanceRouteHandler(({ request, body, user }) => { // 'body' is typed according to the schema // 'user' is the authenticated user object // 'request' is the raw request object // If 'captcha' is true, 'x-captcha-token' header must be provided. return new Response(JSON.stringify({ message: 'Success' }), { status: 200 }); }, { captcha: true, captureException: true, schema: z.object({ id: z.number() }) }); // Example of calling the enhanced route handler (e.g., via fetch): // fetch('/api/your-route', { // method: 'POST', // headers: { // 'Content-Type': 'application/json', // 'x-captcha-token': 'yourCaptchaToken' // }, // body: JSON.stringify({ id: 1 }) // }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.