### Run Development Server for App Source: https://mf2.dev/docs/apps/app Starts the development server for the 'app' package using Turbo. Ensure Turbo is installed and configured. ```bash turbo dev --filter=app ``` -------------------------------- ### Start the Development Server Source: https://mf2.dev/docs/setup/installation Run this command to start all applications in parallel. Environment variables should be configured in `.env.local`. ```bash bun run dev ``` -------------------------------- ### Install a Skill Source: https://mf2.dev/docs/skills Use this command to add a new skill to your project. Replace `` with the skill's repository and `` with the specific skill you want to install. ```bash bunx skills add --skill ``` -------------------------------- ### Install Convex Skill Source: https://mf2.dev/docs/skills Install the Convex skill for Convex functions, schema, real-time patterns, and security. ```bash bunx skills add waynesutton/convexskills --skill convex ``` -------------------------------- ### Install AI SDK Skill Source: https://mf2.dev/docs/skills Install the Vercel AI SDK skill for streaming, tools, agents, and provider integration. ```bash bunx skills add vercel/ai --skill ai-sdk ``` -------------------------------- ### Run Development Server with Turbo Source: https://mf2.dev/docs/apps/docs Use this command to start the development server for the docs application using Turbo. ```bash turbo dev --filter=docs ``` -------------------------------- ### Install Next.js Best Practices Skill Source: https://mf2.dev/docs/skills Install the Next.js best practices skill to cover 23+ topics like RSC boundaries, async patterns, metadata, and fonts. ```bash bunx skills add vercel-labs/next-skills --skill next-best-practices ``` -------------------------------- ### Start Development Mode Source: https://mf2.dev/docs/commands Use 'bun run dev' to start all applications in development mode. For a single application, use 'turbo dev --filter='. ```bash bun run dev ``` ```bash turbo dev --filter=app ``` -------------------------------- ### Start Convex Backend Source: https://mf2.dev/docs/commands Initiates the Convex backend in development mode. This is separate from the main application development server. ```bash bunx convex dev ``` -------------------------------- ### Install Convex Best Practices Skill Source: https://mf2.dev/docs/skills Install the Convex best practices skill for production Convex patterns, including query patterns, validation, and error handling. ```bash bunx skills add waynesutton/convexskills --skill convex-best-practices ``` -------------------------------- ### Install Frontend Design Skill Source: https://mf2.dev/docs/skills Install the frontend design skill for distinctive UI direction, including typography, color, motion, and layout. ```bash bunx skills add anthropics/skills --skill frontend-design ``` -------------------------------- ### Run Development Server with Mint CLI Source: https://mf2.dev/docs/apps/docs Alternatively, use the Mint CLI to start the development server on a specific port. ```bash mint dev --port 3004 ``` -------------------------------- ### Verify Tool Installations Source: https://mf2.dev/docs/setup/prerequisites Check that all required development tools are installed and accessible by running their version commands. ```bash bun --version node --version git --version stripe --version mint --version ``` -------------------------------- ### Run Storybook Development Server Source: https://mf2.dev/docs/apps/storybook Use this command to start the Storybook development server. The preview will be available at localhost:6006. ```bash turbo dev --filter=storybook ``` -------------------------------- ### Turbo Filtering Examples Source: https://mf2.dev/docs/commands Demonstrates how to use the '--filter' flag with Turbo to run tasks for specific applications or packages. Appending '...' includes dependencies. ```bash turbo dev --filter=app ``` ```bash turbo build --filter=web ``` ```bash turbo test --filter=backend ``` ```bash turbo build --filter=app... ``` -------------------------------- ### Start Expo Mobile App Directly Source: https://mf2.dev/docs/apps/mobile Navigate to the mobile app directory and start the Expo development server directly. This is an alternative to using Turbo. ```bash cd apps/mobile && bunx expo start ``` -------------------------------- ### Run Development Server for Web App Source: https://mf2.dev/docs/apps/web Starts the development server for the 'web' application using Turbo. Ensure the theme is not applied for this command. ```bash turbo dev --filter=web ``` -------------------------------- ### Scaffold a New mf² Project Source: https://mf2.dev/docs/setup/installation Use this command to create a new mf² application. Navigate into the created directory and install dependencies. ```bash bunx create-mf2-app my-app cd my-app bun install ``` -------------------------------- ### Install Tailwind Design System Skill Source: https://mf2.dev/docs/skills Install the Tailwind v4 design system skill for tokens, variants, and OKLCH colors. ```bash bunx skills add wshobson/agents --skill tailwind-design-system ``` -------------------------------- ### Run Email Development Server Source: https://mf2.dev/docs/apps/email Start the development server for the email application using Turbo. Ensure the 'email' filter is applied. ```bash turbo dev --filter=email ``` -------------------------------- ### Run Mobile App with Turbo Source: https://mf2.dev/docs/apps/mobile Use this command to start the mobile app development server via Turbo. Ensure Turbo is set up in your project. ```bash turbo dev:mobile ``` -------------------------------- ### Send Welcome Email Source: https://mf2.dev/docs/apps/email Send a welcome email to a user using the '@repo/email' package. This example demonstrates importing a React Email template and passing props to it. ```typescript import { sendEmail } from "@repo/email"; import Welcome from "@repo/email/templates/welcome"; await sendEmail({ to: "user@example.com", subject: "Welcome aboard", react: Welcome({ name: "Jane" }), }); ``` -------------------------------- ### Setup Convex Stripe Component Source: https://mf2.dev/docs/packages/payments Register the Stripe component in your Convex configuration and configure webhook routes. ```APIDOC ## Setup Register the component in `convex/convex.config.ts` and configure webhook routes in `convex/http.ts`: ```ts title="packages/backend/convex/convex.config.ts" theme={null} import { defineApp } from "convex/server"; import stripe from "@convex-dev/stripe/convex.config.js"; const app = defineApp(); app.use(stripe); export default app; ``` ```ts title="packages/backend/convex/http.ts" theme={null} import { registerRoutes } from "@convex-dev/stripe"; registerRoutes(http, components.stripe, { webhookPath: "/stripe/webhook", }); ``` ``` -------------------------------- ### Install Convex Rate Limiter Component Source: https://mf2.dev/docs/packages/rate-limit Command to add the Convex Rate Limiter component to your project dependencies. ```bash bun add @convex-dev/rate-limiter ``` -------------------------------- ### Start a Specific App Source: https://mf2.dev/docs/setup/installation To run a single application, use the `--filter` flag followed by the app name. Available apps include `app`, `web`, `api`, `docs`, `email`, and `storybook`. ```bash bun run dev --filter=app ``` -------------------------------- ### Run API Development Server Source: https://mf2.dev/docs/apps/api Starts the development server for the API application using Turbo. This command is useful for local development and testing of API functionalities. ```bash turbo dev --filter=api ``` -------------------------------- ### Authenticate Stripe CLI Source: https://mf2.dev/docs/setup/prerequisites Log in to your Stripe account using the Stripe CLI after installation. ```bash stripe login ``` -------------------------------- ### Example Imports from Packages Source: https://mf2.dev/docs/structure Demonstrates how to import modules from different packages within the monorepo, including UI components and authentication utilities. Note the different import path for native components. ```typescript import { auth } from "@repo/auth"; import { Button } from "@repo/design-system/components/ui/button"; import { analytics } from "@repo/analytics"; // Mobile equivalents import { Button } from "@repo/design-system-native/components/ui/button"; ``` -------------------------------- ### Import and Use UI Components Source: https://mf2.dev/docs/packages/design-system Import and use various UI components like Button, Card, and Input from the design system package. This example demonstrates a settings form. ```tsx import { Button } from "@repo/design-system/components/ui/button"; import { Card, CardContent, CardHeader, CardTitle } from "@repo/design-system/components/ui/card"; import { Input } from "@repo/design-system/components/ui/input"; export function SettingsForm() { return ( Settings ); } ``` -------------------------------- ### Fetch and Display a Blog Post Source: https://mf2.dev/docs/packages/cms Fetches a blog post using `fetchBlogPost` and displays its title, publication date, and content. Ensure the `@repo/cms` package is installed and configured. ```tsx import { fetchBlogPost } from "@repo/cms"; export default async function BlogPost({ params }: { params: { slug: string } }) { const post = await fetchBlogPost(params.slug); return (

{post.title}

{post.content}
); } ``` -------------------------------- ### Get Web Search Tool Source: https://mf2.dev/docs/packages/ai Retrieves a web search tool powered by Perplexity. Requires the `PERPLEXITY_API_KEY` environment variable. Imports `getSearchTool` from `@repo/ai/tools/search`. ```typescript import { getSearchTool } from "@repo/ai/tools/search"; const search = getSearchTool(); ``` -------------------------------- ### Server Component Page Example Source: https://mf2.dev/docs/colocation A Server Component page that fetches data and passes it to a Client Component for rendering interactive UI. Keep 'use client' directives at the leaf level. ```tsx import { StatsCard } from "./_components/stats-card"; export default async function DashboardPage() { const stats = await getStats(); // Server: fetch data return ; // Client: render interactive UI } ``` -------------------------------- ### Add New Environment Variable Source: https://mf2.dev/docs/setup/env Example of adding a new secret and an optional client variable to the environment schema. Remember to update `.env` and `.env.example` files. ```typescript import { createEnv } from '@t3-oss/env-nextjs'; import { z } from 'zod'; export const env = createEnv({ server: { MY_NEW_SECRET: z.string().min(1), }, client: { NEXT_PUBLIC_MY_VALUE: z.string().optional(), }, runtimeEnv: { MY_NEW_SECRET: process.env.MY_NEW_SECRET, NEXT_PUBLIC_MY_VALUE: process.env.NEXT_PUBLIC_MY_VALUE, }, }); ``` -------------------------------- ### Registering Convex Components in convex.config.ts Source: https://mf2.dev/docs/components This snippet shows how to import and register pre-installed Convex Components in your `convex.config.ts` file. Ensure you have installed the necessary packages via npm. ```typescript import { defineApp } from "convex/server"; import actionRetrier from "@convex-dev/action-retrier/convex.config.js"; import migrations from "@convex-dev/migrations/convex.config.js"; import resend from "@convex-dev/resend/convex.config.js"; import stripe from "@convex-dev/stripe/convex.config.js"; import workflow from "@convex-dev/workflow/convex.config.js"; const app = defineApp(); app.use(actionRetrier); app.use(migrations); app.use(resend); app.use(stripe); app.use(workflow); export default app; ``` -------------------------------- ### Add a Button Story to Storybook Source: https://mf2.dev/docs/apps/storybook Create `.stories.tsx` files in `apps/storybook/stories` to define stories for your components. This example shows how to create a story for the Button component. ```typescript import type { Meta, StoryObj } from "@storybook/react"; import { Button } from "@repo/design-system/components/ui/button"; const meta: Meta = { title: "Components/Button", component: Button, }; export default meta; export const Default: StoryObj = { args: { children: "Click me", variant: "default" }, }; ``` -------------------------------- ### React Email Template Source: https://mf2.dev/docs/packages/email Define email templates as React components using React Email. This example shows a simple welcome email template. ```tsx import { Html, Head, Body, Text } from "@react-email/components"; export default function WelcomeEmail({ name }: { name: string }) { return ( Welcome, {name}! Your account is ready. ); } ``` -------------------------------- ### Create mf² App Source: https://mf2.dev/docs/index Use this command to bootstrap a new mf² application. It initializes the monorepo structure and sets up the necessary configurations. ```bash bunx create-mf2-app ``` -------------------------------- ### Deploy Convex to Production Source: https://mf2.dev/docs/commands Deploys the Convex backend to the production environment. Ensure all configurations are correct before deployment. ```bash bunx convex deploy ``` -------------------------------- ### Enable Bundle Analysis Source: https://mf2.dev/docs/packages/next-config Run the build command with the ANALYZE=true environment variable to generate a bundle analysis report. ```bash ANALYZE=true bun run build ``` -------------------------------- ### Get Webhook Portal URL Source: https://mf2.dev/docs/packages/webhooks Use the `getPortalUrl` function to obtain a URL for a self-service UI where customers can manage their webhook endpoints. ```APIDOC ## getPortalUrl ### Description Generates a URL for the webhook management portal, allowing customers to manage their endpoints. ### Method Signature `getPortalUrl({ appId: string }): Promise` ### Parameters #### Arguments - **appId** (string) - Required - The identifier for the application. ### Request Example ```ts const portalUrl = await getPortalUrl({ appId: userId }); return Response.json({ url: portalUrl }); ``` ``` -------------------------------- ### Get Webhook Portal URL Source: https://mf2.dev/docs/packages/webhooks Retrieve the URL for the webhook management portal. This is useful for providing customers with a self-service UI to manage their endpoints. ```typescript import { getPortalUrl } from "@repo/webhooks"; const portalUrl = await getPortalUrl({ appId: userId }); return Response.json({ url: portalUrl }); ``` -------------------------------- ### Environment Variable Management Source: https://mf2.dev/docs/commands Commands for initializing, checking, and syncing environment variables. 'env:init' creates local and production environment files from a template. 'env:check' validates required keys. 'env:push' syncs to Vercel and Convex. ```bash bun run env:init ``` ```bash bun run env:check ``` ```bash bun run env:push ``` -------------------------------- ### Configuring Upstash Rate Limiter with Different Windows Source: https://mf2.dev/docs/packages/rate-limit Demonstrates how to configure the `slidingWindow` function with different rate limits and time periods for specific routes like authentication. ```typescript const authLimiter = createRateLimiter({ limiter: slidingWindow(5, "15 m"), prefix: "auth", }); ``` -------------------------------- ### Get Feature Flag (Server-Side) Source: https://mf2.dev/docs/packages/feature-flags Use `getFlag` to retrieve the boolean state of a feature flag on the server. Ensure the feature flag package is imported. ```tsx import { getFlag } from "@repo/feature-flags"; const showNewEditor = await getFlag("new-editor"); ``` -------------------------------- ### Build and Test Commands Source: https://mf2.dev/docs/commands Execute 'bun run build' to build all applications, which includes running tests. 'bun run test' runs all tests using Vitest. 'bun run analyze' performs bundle analysis. ```bash bun run build ``` ```bash bun run test ``` ```bash bun run analyze ``` -------------------------------- ### Set up Stripe Local Webhook Listener Source: https://mf2.dev/docs/setup/env Run this command to forward local Stripe webhooks to your development server. The CLI will output the signing secret needed for STRIPE_WEBHOOK_SECRET. ```bash stripe listen --forward-to localhost:3000/api/webhook/stripe ``` -------------------------------- ### Create a New MDX Documentation Page Source: https://mf2.dev/docs/apps/docs Add an MDX file to the `apps/docs` directory. The file name determines the URL slug, and frontmatter metadata like 'title' and 'description' are supported. ```mdx --- title: 'Hello World' description: 'A new documentation page.' --- ``` -------------------------------- ### Configure Convex Backend Environment Variable Source: https://mf2.dev/docs/setup/env Set the Convex deployment URL. This is automatically generated and written to .env.local when running `bunx convex dev`. ```bash NEXT_PUBLIC_CONVEX_URL="https://your-project.convex.cloud" ``` -------------------------------- ### Directory Structure for Colocation Source: https://mf2.dev/docs/colocation Illustrates the recommended folder structure for colocating route-specific components and shared logic within the App Router. ```tree apps/app/src/app/ ├── dashboard/ │ ├── page.tsx │ ├── layout.tsx │ └── _components/ # Dashboard-specific components │ ├── stats-card.tsx │ └── recent-activity.tsx ├── settings/ │ ├── page.tsx │ └── _components/ # Settings-specific components │ └── settings-form.tsx └── (auth)/ ├── login/ │ ├── page.tsx │ └── _components/ # Login-specific components │ └── login-form.tsx ├── register/ │ ├── page.tsx │ └── _components/ # Register-specific components │ └── register-form.tsx └── _components/ # Shared across all auth routes └── social-buttons.tsx ``` -------------------------------- ### Import Components in Convex Functions Source: https://mf2.dev/docs/components Import the generated `components` object in your Convex functions to access installed components. This object provides a sandboxed interface to component functionalities. ```typescript import { components } from "./_generated/api"; ``` -------------------------------- ### Configure Clerk Authentication Environment Variables Source: https://mf2.dev/docs/setup/env Add these variables to your environment for Clerk authentication. Obtain keys from the Clerk Dashboard. ```bash NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY="pk_test_..." CLERK_SECRET_KEY="sk_test_..." ``` -------------------------------- ### Get Feature Flag (Client-Side) Source: https://mf2.dev/docs/packages/feature-flags Use the `useFlag` hook to access the state of a feature flag within client-side components. This hook requires the component to be marked with 'use client'. ```tsx "use client"; import { useFlag } from "@repo/feature-flags"; const showBeta = useFlag("beta-features"); ``` -------------------------------- ### Configure PostHog Analytics Source: https://mf2.dev/docs/setup/env Set NEXT_PUBLIC_POSTHOG_KEY and NEXT_PUBLIC_POSTHOG_HOST for PostHog analytics integration. ```bash NEXT_PUBLIC_POSTHOG_KEY="phc_..." NEXT_PUBLIC_POSTHOG_HOST="https://app.posthog.com" ``` -------------------------------- ### Configure BetterStack Observability Source: https://mf2.dev/docs/setup/env Set BETTERSTACK_API_KEY and BETTERSTACK_URL for BetterStack observability. ```bash BETTERSTACK_API_KEY="..." BETTERSTACK_URL="..." ``` -------------------------------- ### Integrate Live Collaboration Features Source: https://mf2.dev/docs/packages/collaboration Wrap collaborative pages with the CollaborationProvider and include components like AvatarStack and LiveCursors. Ensure you have the necessary imports from @repo/collaboration. ```tsx import { LiveCursors, AvatarStack, usePresence } from "@repo/collaboration"; import { CollaborationProvider } from "@repo/collaboration"; // Wrap collaborative pages with the provider ``` -------------------------------- ### Configure Vercel AI Gateway Source: https://mf2.dev/docs/setup/env Set AI_GATEWAY_API_KEY and AI_GATEWAY_URL for Vercel AI Gateway integration. ```bash AI_GATEWAY_API_KEY="..." AI_GATEWAY_URL="..." ``` -------------------------------- ### Get Current User in Convex Mutation Source: https://mf2.dev/docs/packages/convex Use this helper function within Convex mutations to retrieve the current authenticated user's identity. This ensures that all actions are performed with the correct user context. ```ts import { getCurrentUserOrThrow } from "../auth/users"; export const send = mutation({ args: { body: v.string() }, handler: async (ctx, args) => { const user = await getCurrentUserOrThrow(ctx); await ctx.db.insert("messages", { body: args.body, userId: user._id }); }, }); ``` -------------------------------- ### Create a Chat Agent with Tools Source: https://mf2.dev/docs/packages/ai Defines a chat agent with a weather tool. Requires importing `createChatAgent`, `tool`, and `z` from `@repo/ai/agent`. ```typescript import { createChatAgent, tool, z } from "@repo/ai/agent"; const agent = createChatAgent(token, { weather: tool({ description: "Get the weather for a location", parameters: z.object({ city: z.string() }), execute: async ({ city }) => `72°F in ${city}`, }), }); ``` -------------------------------- ### Configure Stripe Payments Environment Variables Source: https://mf2.dev/docs/setup/env Add these variables for Stripe payment integration. Obtain keys from the Stripe Dashboard. ```bash STRIPE_SECRET_KEY="sk_test_..." STRIPE_WEBHOOK_SECRET="whsec_..." ``` -------------------------------- ### Add New shadcn/ui Components Source: https://mf2.dev/docs/packages/design-system Use the shadcn CLI to add new components to the shared design system package. Specify the component name and the target directory. ```bash bunx shadcn@latest add calendar -c packages/design-system ``` -------------------------------- ### Build Single App with Turbo Source: https://mf2.dev/docs/commands Use 'turbo build --filter=' to build a specific application within the monorepo. This is useful for targeted builds. ```bash turbo build --filter=app ``` -------------------------------- ### Route Grouping for URL Organization Source: https://mf2.dev/docs/colocation Demonstrates how to use parenthesized folder names to create route groups, organizing related routes without affecting the URL structure. ```tree apps/app/src/app/ ├── (auth)/ # /login, /register — no "(auth)" in URL │ ├── login/ │ └── register/ ├── (app)/ # /dashboard, /settings — authenticated routes │ ├── dashboard/ │ └── settings/ └── layout.tsx # Root layout wraps everything ``` -------------------------------- ### Configure Svix Webhooks Source: https://mf2.dev/docs/setup/env Set the SVIX_TOKEN for Svix webhook integration. ```bash SVIX_TOKEN="..." ``` -------------------------------- ### Configure HTTP Router for Webhooks Source: https://mf2.dev/docs/packages/backend Sets up an HTTP router to handle incoming webhooks, specifically for Clerk. This file should be located at `convex/http.ts`. ```typescript import { httpRouter } from "convex/server"; const http = httpRouter(); http.route({ path: "/clerk", method: "POST", handler: clerkWebhook, }); ``` -------------------------------- ### Create a RAG Pipeline Source: https://mf2.dev/docs/packages/ai Builds a retrieval-augmented generation (RAG) pipeline with specified stages and a retriever. Requires importing `createPipeline` from `@repo/ai/rag`. ```typescript import { createPipeline } from "@repo/ai/rag"; const pipeline = createPipeline({ stages: ["rewrite", "stepback"], retriever: myRetriever, }); const results = await pipeline.run("How does auth work?"); ``` -------------------------------- ### Import Pre-configured Model Constants Source: https://mf2.dev/docs/packages/ai Imports constants for various AI models and chat models from `@repo/ai/models`. Includes models like Claude Sonnet, Gemini Flash, GPT-4o, etc. ```typescript import { CLAUDE_SONNET, GEMINI_FLASH, CHAT_MODELS } from "@repo/ai/models"; ``` -------------------------------- ### Import Base Next.js Configuration Source: https://mf2.dev/docs/packages/next-config Import the default Next.js configuration from the `@repo/next-config` package to use as a base for your application. ```typescript import { config } from "@repo/next-config"; export default config; ``` -------------------------------- ### Configure Resend Email Service Source: https://mf2.dev/docs/setup/env Set the RESEND_TOKEN and RESEND_FROM environment variables to enable email functionality with Resend. ```bash RESEND_TOKEN="re_..." RESEND_FROM="noreply@yourdomain.com" ``` -------------------------------- ### Configure BaseHub CMS Source: https://mf2.dev/docs/setup/env Set the BASEHUB_TOKEN for BaseHub CMS integration. ```bash BASEHUB_TOKEN="bshb_..." ``` -------------------------------- ### Initialize Client-Side Observability Source: https://mf2.dev/docs/packages/observability Call this function to set up error tracking and logging for the client application. Ensure it's called early in the application lifecycle. ```typescript import { initClientObservability } from "@repo/observability/client"; initClientObservability(); ``` -------------------------------- ### Initialize Server-Side Observability Source: https://mf2.dev/docs/packages/observability Call this function to set up error tracking and logging for the server application. Ensure it's called early in the application lifecycle. ```typescript import { initServerObservability } from "@repo/observability/server"; initServerObservability(); ``` -------------------------------- ### Configure Stripe Webhook Source: https://mf2.dev/docs/packages/payments Instructions for setting up the Stripe webhook endpoint in the Stripe dashboard and configuring the signing secret in Convex environment variables. ```APIDOC ## Configure the webhook in Stripe 1. Go to **Developers > Webhooks** in the [Stripe dashboard](https://dashboard.stripe.com/webhooks) and click **Add endpoint**. 2. Set the endpoint URL to `https://.convex.site/stripe/webhook`. 3. Select these events: `checkout.session.completed`, `customer.created`, `customer.updated`, `customer.subscription.created`, `customer.subscription.updated`, `customer.subscription.deleted`, `payment_intent.succeeded`, `payment_intent.payment_failed`, `invoice.created`, `invoice.finalized`, `invoice.paid`, `invoice.payment_failed`. 4. Copy the **Signing secret** (starts with `whsec_`) and set it as `STRIPE_WEBHOOK_SECRET` in your [Convex dashboard](https://dashboard.convex.dev) environment variables. ``` -------------------------------- ### Run Code Quality Checks and Fixes Source: https://mf2.dev/docs/packages/formatting Use these commands to check for linting and formatting issues or to automatically fix them. These commands are typically executed via npm or bun scripts. ```bash bun run check # lint and format check ``` ```bash bun run fix # auto-fix issues ``` -------------------------------- ### Link Vercel Projects Before Pushing Env Vars Source: https://mf2.dev/docs/setup/env Before syncing environment variables with `env:push`, link each application to its respective Vercel project using the `vercel link` command. ```bash cd apps/app && vercel link && cd ../.. cd apps/web && vercel link && cd ../.. ``` -------------------------------- ### Enable real-time notification delivery Source: https://mf2.dev/docs/packages/notifications Wrap your application with `NotificationProvider` and provide the `userId` to enable real-time notification delivery. This should be done at the root of your application. ```tsx import { NotificationProvider } from "@repo/notifications"; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` -------------------------------- ### Configure Google Analytics Source: https://mf2.dev/docs/setup/env Set the NEXT_PUBLIC_GA_MEASUREMENT_ID for Google Analytics integration. ```bash NEXT_PUBLIC_GA_MEASUREMENT_ID="G-..." ``` -------------------------------- ### Create a Subscription Checkout Session Source: https://mf2.dev/docs/packages/payments Create a Stripe checkout session for a new subscription. Supports one-time purchases by using `mode: "payment"`. ```APIDOC ## Create a checkout ```ts title="packages/backend/convex/stripe/index.ts" theme={null} import { StripeSubscriptions } from "@convex-dev/stripe"; import { components } from "../_generated/api"; const stripeClient = new StripeSubscriptions(components.stripe, {}); export const createSubscriptionCheckout = action({ args: { priceId: v.string() }, handler: async (ctx, args) => { const identity = await ctx.auth.getUserIdentity(); if (!identity) throw new Error("Not authenticated"); const customer = await stripeClient.getOrCreateCustomer(ctx, { userId: identity.subject, email: identity.email, name: identity.name, }); return stripeClient.createCheckoutSession(ctx, { priceId: args.priceId, customerId: customer.customerId, mode: "subscription", successUrl: `${getAppUrl()}/settings/billing?success=true`, cancelUrl: `${getAppUrl()}/settings/billing?canceled=true`, subscriptionMetadata: { userId: identity.subject }, }); }, }); ``` Use `mode: "payment"` for one-time purchases instead of subscriptions. ``` -------------------------------- ### Import Stripe Agent Toolkit Source: https://mf2.dev/docs/packages/payments Import the Stripe Agent Toolkit for AI-powered payment operations. This is typically used in backend Convex functions. ```typescript import { paymentsAgentToolkit } from "@repo/payments/ai"; ``` -------------------------------- ### Configure Secure HTTP Headers with Nosecone Source: https://mf2.dev/docs/packages/security Utilize `withSecureHeaders` to automatically set security headers like Content-Security-Policy and X-Frame-Options. Customize directives for Content-Security-Policy as needed. ```typescript import { withSecureHeaders } from "@repo/security"; export default withSecureHeaders({ contentSecurityPolicy: { directives: { defaultSrc: ["'self'"], scriptSrc: ["'self'", "'unsafe-inline'"], }, }, }); ``` -------------------------------- ### Colocating Non-Component Files Source: https://mf2.dev/docs/colocation Shows how to colocate route-specific files like validation schemas and custom hooks within the same route folder for better organization. ```tree apps/app/src/app/settings/ ├── page.tsx ├── _components/ │ └── settings-form.tsx ├── _lib/ │ └── schema.ts # Zod schema for settings form └── _hooks/ └── use-settings.ts # Hook for settings state ``` -------------------------------- ### Create Subscription Checkout Session Source: https://mf2.dev/docs/packages/payments Create a checkout session for a subscription using the Stripe component. Requires user authentication and a valid price ID. Use `mode: "payment"` for one-time purchases. ```typescript import { StripeSubscriptions } from "@convex-dev/stripe"; import { components } from "../_generated/api"; const stripeClient = new StripeSubscriptions(components.stripe, {}); export const createSubscriptionCheckout = action({ args: { priceId: v.string() }, handler: async (ctx, args) => { const identity = await ctx.auth.getUserIdentity(); if (!identity) throw new Error("Not authenticated"); const customer = await stripeClient.getOrCreateCustomer(ctx, { userId: identity.subject, email: identity.email, name: identity.name, }); return stripeClient.createCheckoutSession(ctx, { priceId: args.priceId, customerId: customer.customerId, mode: "subscription", successUrl: `${getAppUrl()}/settings/billing?success=true`, cancelUrl: `${getAppUrl()}/settings/billing?canceled=true`, subscriptionMetadata: { userId: identity.subject }, }); }, }); ``` -------------------------------- ### Implement Route-Specific Rate Limiting Source: https://mf2.dev/docs/packages/security Create a rate limiter instance using `rateLimit` for specific routes. Protect a request by calling `limiter.protect(request)` and check `decision.isDenied()` to return a 429 response if limits are exceeded. ```typescript import { rateLimit } from "@repo/security"; const limiter = rateLimit({ max: 5, window: "15m", }); export async function POST(request: Request) { const decision = await limiter.protect(request); if (decision.isDenied()) { return new Response("Too many requests", { status: 429 }); } // Handle request } ``` -------------------------------- ### Configure Knock Notifications Source: https://mf2.dev/docs/setup/env Set various Knock API keys and channel IDs for notification integration. ```bash KNOCK_API_KEY="..." KNOCK_SECRET_API_KEY="..." KNOCK_FEED_CHANNEL_ID="..." NEXT_PUBLIC_KNOCK_API_KEY="..." NEXT_PUBLIC_KNOCK_FEED_CHANNEL_ID="..." ``` -------------------------------- ### Create Stripe Customer Portal Session Source: https://mf2.dev/docs/packages/payments Generate a URL to the Stripe customer portal for managing billing details. Requires a customer ID. ```typescript const { url } = await stripeClient.createCustomerPortalSession(ctx, { customerId: customer.customerId, returnUrl: `${getAppUrl()}/settings/billing`, }); ``` -------------------------------- ### Apply Global Security Rules with Middleware Source: https://mf2.dev/docs/packages/security Use the `secure` function to apply global rate limiting and bot protection rules to your application. Configure rate limits by specifying `max` requests and `window` duration. ```typescript import { secure } from "@repo/security"; export default secure({ rateLimit: { max: 100, window: "1m", }, botProtection: true, }); ``` -------------------------------- ### Configure Locale Middleware Source: https://mf2.dev/docs/packages/i18n Set up the `i18nMiddleware` to handle locale detection and routing for your application. Configure the default locale and the list of supported locales. ```typescript import { i18nMiddleware } from "@repo/internationalization"; export default i18nMiddleware({ defaultLocale: "en", locales: ["en", "es", "fr", "de", "ja"], }); ``` -------------------------------- ### Configure Liveblocks Collaboration Source: https://mf2.dev/docs/setup/env Set the LIVEBLOCKS_SECRET for Liveblocks collaboration features. ```bash LIVEBLOCKS_SECRET="sk_..." ``` -------------------------------- ### Configure Arcjet Security Source: https://mf2.dev/docs/setup/env Set the ARCJET_KEY for Arcjet security integration. ```bash ARCJET_KEY="ajkey_..." ``` -------------------------------- ### Extend Base TypeScript Config for Libraries Source: https://mf2.dev/docs/packages/typescript-config Extend the base preset for library packages. Configure 'outDir' and include TypeScript files, excluding node_modules. ```json { "extends": "@repo/typescript-config/base.json", "compilerOptions": { "outDir": "dist" }, "include": ["**/*.ts"], "exclude": ["node_modules"] } ``` -------------------------------- ### Code Quality Checks Source: https://mf2.dev/docs/commands Run 'bun run check' for linting and formatting checks using Ultracite (Biome). Use 'bun run fix' to automatically resolve linting and formatting issues. 'bun run convex-lint' specifically lints Convex functions using ESLint. ```bash bun run check ``` ```bash bun run fix ``` ```bash bun run convex-lint ``` -------------------------------- ### Wrap App with AnalyticsProvider Source: https://mf2.dev/docs/packages/analytics Wrap your application with the AnalyticsProvider to enable analytics functionality. This should be done at the root of your application. ```tsx import { AnalyticsProvider } from "@repo/analytics"; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` -------------------------------- ### Direct Use of Upstash Redis Client Source: https://mf2.dev/docs/packages/rate-limit Shows how to access the configured Upstash Redis client directly from the `@repo/rate-limit` package for general caching or other Redis operations. ```typescript import { redis } from "@repo/rate-limit"; await redis.set("key", "value", { ex: 60 }); const value = await redis.get("key"); ``` -------------------------------- ### Add Page to Navigation in docs.json Source: https://mf2.dev/docs/apps/docs Configure the site navigation by adding page slugs to the `pages` array within the desired group in `docs.json`. ```json "navigation": { "groups": [ { "group": "Getting Started", "pages": ["hello-world"] } ] } ```