### Install QStash SDK Source: https://supastarter.dev/docs/nextjs/tasks/qstash Install the QStash SDK using pnpm. ```bash pnpm add --filter api @upstash/qstash ``` -------------------------------- ### Start Local Development Services Source: https://supastarter.dev/docs/nextjs/codebase/local-development Use this command to start PostgreSQL and MinIO S3 storage services locally using Docker Compose. Ensure Docker and Docker Compose are installed and running. ```bash docker compose up -d ``` -------------------------------- ### Install Uploadthing Packages Source: https://supastarter.dev/docs/nextjs/storage/uploadthing Install the necessary Uploadthing packages for your project using pnpm. ```bash pnpm --filter web add uploadthing @uploadthing/react ``` -------------------------------- ### Deploy API Service Build and Start Commands Source: https://supastarter.dev/docs/nextjs/deployment/standalone-api Commands to build and start the API service for deployment on platforms like Render. ```bash # Build the API service corepack enable; pnpm install --frozen-lockfile; pnpm --filter @repo/api-app build # Start the API service pnpm --filter @repo/api-app start ``` -------------------------------- ### Start Development Server Source: https://supastarter.dev/docs/nextjs/database/providers/railway Run this command to start your Next.js development server and verify that the application can connect to the Railway database. ```bash pnpm dev ``` -------------------------------- ### Start Docs Development Server Source: https://supastarter.dev/docs/nextjs/documentation Run this command to start the documentation development server. It typically runs on port 3001. ```bash pnpm --filter @repo/docs dev ``` -------------------------------- ### Example PostgreSQL Connection String Source: https://supastarter.dev/docs/nextjs/setup This is an example of a PostgreSQL connection string format. Ensure you replace the placeholders with your actual database credentials. ```bash postgresql://user:password@host:port/database ``` -------------------------------- ### Install Project Dependencies Source: https://supastarter.dev/docs/nextjs/setup Installs all project dependencies using pnpm. Ensure pnpm is installed globally before running this command. ```bash pnpm install ``` -------------------------------- ### Configure Environment Variables Source: https://supastarter.dev/docs/nextjs/setup Sets up the .env.local file by copying from the example and defining the DATABASE_URL. This is crucial for connecting to your database. ```bash # Database DATABASE_URL="YOUR_DATABASE_CONNECTION_STRING" ``` -------------------------------- ### Install PostHog JS Package Source: https://supastarter.dev/docs/nextjs/analytics/posthog Install the posthog-js package for the web application. ```bash pnpm add --filter web posthog-js ``` -------------------------------- ### Configure Nixpacks Build and Start Commands Source: https://supastarter.dev/docs/nextjs/deployment/railway Set the build command to generate and build the project, and the start command to run the application. These commands are specific to a monorepo structure using pnpm. ```bash pnpm --filter database generate && pnpm --filter web build ``` ```bash pnpm --filter web start ``` -------------------------------- ### Install Mixpanel Packages Source: https://supastarter.dev/docs/nextjs/analytics/mixpanel Install the Mixpanel browser package for frontend tracking and the types for Node.js if needed. Use pnpm for package management. ```bash pnpm add --filter web mixpanel-browser ``` ```bash pnpm add --filter web -D @types/mixpanel-node ``` -------------------------------- ### Start Mail Preview Server Source: https://supastarter.dev/docs/nextjs/mailing/overview Commands to start the development server for previewing email templates. This server runs on port 3003. ```bash pnpm --filter mail-preview dev # or pnpm dev # starts all dev servers ``` -------------------------------- ### Install Vercel Analytics Package Source: https://supastarter.dev/docs/nextjs/analytics/vercel Install the Vercel Analytics package for the web application using pnpm. ```bash pnpm add --filter web @vercel/analytics ``` -------------------------------- ### Install Package Globally Source: https://supastarter.dev/docs/nextjs/codebase/dependencies Use this command to install a package to the root of the monorepo, making it available to all packages. ```bash pnpm add -w ``` -------------------------------- ### Install Vemetric React Package Source: https://supastarter.dev/docs/nextjs/analytics/vemetric Install the Vemetric React package for your web application using pnpm. ```bash pnpm add --filter web @vemetric/react ``` -------------------------------- ### Start Queuebase Development Server Source: https://supastarter.dev/docs/nextjs/tasks/queuebase Run the Queuebase dev server in one terminal to manage local jobs and databases. ```bash npx queuebase dev ``` -------------------------------- ### Clone Supastarter Repository Source: https://supastarter.dev/docs/nextjs/setup Use this command to clone the Supastarter Next.js repository. This is part of the manual setup process if automatic setup fails. ```bash git clone https://github.com/supastarter/supastarter-nextjs.git ``` -------------------------------- ### Install Sentry SDK Source: https://supastarter.dev/docs/nextjs/monitoring/sentry Add the Sentry Next.js SDK to your web application using pnpm. ```bash pnpm --filter web add @sentry/nextjs ``` -------------------------------- ### Install Package to Specific Workspace Source: https://supastarter.dev/docs/nextjs/codebase/dependencies Use this command to install a package to a particular workspace within the monorepo. ```bash pnpm add --filter ``` -------------------------------- ### Next.js Instrumentation Setup Source: https://supastarter.dev/docs/nextjs/monitoring/sentry Set up Next.js instrumentation to capture errors and performance data for different runtimes. ```typescript import * as Sentry from "@sentry/nextjs"; export async function register() { if (process.env.NEXT_RUNTIME === "nodejs") { await import("./sentry.server.config"); } if (process.env.NEXT_RUNTIME === "edge") { await import("./sentry.edge.config"); } } export const onRequestError = Sentry.captureRequestError; ``` -------------------------------- ### Launch Supastarter SaaS App on Fly.io Source: https://supastarter.dev/docs/nextjs/deployment/flydotio Use this command to initiate the deployment of your Supastarter SaaS application to Fly.io. Ensure you have the Fly CLI installed and specify the Dockerfile for your SaaS app. ```bash fly launch --dockerfile apps/saas/Dockerfile ``` -------------------------------- ### LLM Prompt for Queuebase Setup Source: https://supastarter.dev/docs/nextjs/tasks/queuebase Use this prompt with coding agents to automatically set up Queuebase in a Supastarter monorepo. It outlines the necessary directory structure, package configurations, and code exports for jobs, clients, and handlers. ```markdown Set up Queuebase in this supastarter monorepo. Here are the steps: 1. Create a new `packages/jobs` directory with: - `packages/jobs/package.json`: name `@repo/jobs`, `private: true`, `version` `0.0.0`. Dependencies: `@queuebase/nextjs` (^2.1.0), `zod` (^3.22.2), `@repo/utils` (workspace:*). devDependencies: `@queuebase/cli` (^2.1.0), `@repo/tsconfig` (workspace:*), `@biomejs/biome` (match other packages). Set `main` to `./src/index.ts`, add `exports` for `"./"` → `./src/index.ts`, `"./client"` → `./src/client.ts`, and `"./handler"` → `./src/handler.ts`. Scripts: `"type-check": "tsc --noEmit"`. - `packages/jobs/tsconfig.json` extending `@repo/tsconfig/base.json`, including `**/*.ts`, excluding `dist`, `build`, `node_modules`. - `packages/jobs/src/index.ts`: export `jobs` from `createJobRouter` with at least one example job (`sendWelcomeEmail`) using `job()` from `@queuebase/nextjs`, Zod `input`, and a `handler`. Export `type JobRouter = typeof jobs`. - `packages/jobs/src/client.ts`: `createClient` with `callbackUrl` set to `` `${getBaseUrl()}/api/webhooks/queuebase` `` (import `getBaseUrl` from `@repo/utils`) so it matches `.basePath("/api").post("/webhooks/queuebase", ...)` in Hono. - `packages/jobs/src/handler.ts`: export `queuebaseWebhookHandler` as `createHandler(jobs)` from `@queuebase/nextjs/handler`. 2. If the repo lists workspace packages explicitly, add `packages/jobs` to `pnpm-workspace.yaml`. 3. Add `@repo/jobs` as a dependency (`workspace:*`) to `packages/api/package.json` (Hono webhook) and `apps/saas/package.json` (enqueue from the app), or whichever packages import `@repo/jobs` in your layout. 4. In the Hono API entry, use `.basePath("/api")`, import `queuebaseWebhookHandler` from `@repo/jobs/handler`, and register `.post("/webhooks/queuebase", (c) => queuebaseWebhookHandler(c.req.raw))` — same pattern as the payments webhook. Place this route before any catch-all `*` middleware that forwards to oRPC. 5. Add Queuebase env vars to `.env` / `.env.local` (see the docs): `QUEUEBASE_API_URL` and `QUEUEBASE_API_KEY` for production. Do not set a separate callback URL env — it is `` `${getBaseUrl()}/api/webhooks/queuebase` `` in the client. 6. Run `pnpm install` from the repository root. 7. Document that local development requires two terminals: `npx queuebase dev` in one, and `pnpm dev` (or the project dev command) in the other; production deploy uses `npx queuebase sync` after setting env vars on the host. ``` -------------------------------- ### Define Payment Plans in Configuration Source: https://supastarter.dev/docs/nextjs/payments/providers/polar Configure your subscription plans and their associated prices within the `packages/payments/config.ts` file. This setup allows for different billing intervals and currencies. ```javascript export const config = { plans: { plans: { pro: { recommended: true, prices: [ { type: "subscription", priceId: process.env.PRICE_ID_PRO_MONTHLY as string, interval: "month", amount: 29, currency: "USD", seatBased: true, trialPeriodDays: 7, }, { type: "subscription", priceId: process.env.PRICE_ID_PRO_YEARLY as string, interval: "year", amount: 290, currency: "USD", seatBased: true, trialPeriodDays: 7, }, ], }, }, }; ``` -------------------------------- ### Coolify Application Build Commands Source: https://supastarter.dev/docs/nextjs/deployment/coolify Configure these commands in Coolify for your Supastarter application. Ensure pnpm is available and lockfiles are used for consistent installations. ```bash pnpm install ``` ```bash corepack enable; pnpm install --frozen-lockfile; pnpm build ``` ```bash pnpm --filter web start ``` -------------------------------- ### Example task definition Source: https://supastarter.dev/docs/nextjs/tasks/trigger-dev Defines a simple 'test-task' that logs a message when executed. This task can be imported and triggered from other parts of the application. ```typescript import { task } from "@trigger.dev/sdk"; export const testTask = task({ id: "test-task", run: async () => { console.log("test task"); }, }); ``` -------------------------------- ### Mount new router in the API Source: https://supastarter.dev/docs/nextjs/api/define-endpoint Make the feature router available in the main API by mounting it in the root router. This example mounts the 'postsRouter' under the '/api' prefix. ```typescript // ... import { postsRouter } from "../modules/posts/router"; export const router = publicProcedure // Prefix for openapi .prefix("/api") .router({ // ... posts: postsRouter, }); ``` -------------------------------- ### Subscription and One-Time Purchase Plan Configuration Source: https://supastarter.dev/docs/nextjs/payments/plans Configures both subscription-based and one-time purchase plans with details like price IDs, amounts, currencies, and trial periods. Includes examples for monthly, yearly, and lifetime options. ```typescript import type { PaymentsConfig } from "./types"; export const config: PaymentsConfig = { billingAttachedTo: "user", requireActiveSubscription: false, plans: { pro: { recommended: true, prices: [ { type: "subscription", priceId: process.env.PRICE_ID_PRO_MONTHLY as string, interval: "month", amount: 29, currency: "USD", trialPeriodDays: 7, seatBased: true, }, { type: "subscription", priceId: process.env.PRICE_ID_PRO_YEARLY as string, interval: "year", amount: 290, currency: "USD", trialPeriodDays: 7, seatBased: true, }, ], }, lifetime: { prices: [ { type: "one-time", priceId: process.env.PRICE_ID_LIFETIME as string, amount: 799, currency: "USD", }, ], }, enterprise: { isEnterprise: true, }, }, }; ``` -------------------------------- ### Dockerfile for Supastarter API Source: https://supastarter.dev/docs/nextjs/deployment/standalone-api This Dockerfile defines the steps to build and run the Supastarter API as a Docker container. It includes stages for building, installing dependencies, and finally running the application. ```dockerfile FROM node:22-alpine AS base ENV PNPM_HOME="/pnpm" ENV PATH="$PNPM_HOME:$PATH" RUN corepack enable FROM base AS builder RUN apk add --no-cache libc6-compat RUN apk update WORKDIR /app RUN pnpm add -g turbo COPY . . RUN turbo prune @repo/api-app --docker FROM base AS installer RUN apk add --no-cache libc6-compat RUN apk update WORKDIR /app COPY .gitignore .gitignore COPY --from=builder /app/out/json/ . COPY --from=builder /app/out/pnpm-lock.yaml ./pnpm-lock.yaml RUN pnpm install COPY --from=builder /app/out/full/ . COPY turbo.json turbo.json RUN pnpm turbo run build --filter=@repo/api-app... FROM base AS runner WORKDIR /app RUN addgroup --system --gid 1001 nodejs RUN adduser --system --uid 1001 api USER api COPY --from=installer /app/apps/api/dist/index.js . USER api EXPOSE 3001 ENV PORT=3001 ENV HOSTNAME="0.0.0.0" CMD ["node", "/app/index.js"] ``` -------------------------------- ### Add Skeleton Component with shadcn/ui CLI Source: https://supastarter.dev/docs/nextjs/customization/styling Example of adding the 'skeleton' component to your project using the shadcn/ui CLI. This command targets the UI package and adds the specified component. ```bash pnpm --filter=ui shadcn add skeleton ``` -------------------------------- ### Local Development Environment Variables Source: https://supastarter.dev/docs/nextjs/codebase/local-development Configure these environment variables to connect to the local PostgreSQL database and MinIO S3 storage. These are essential for the application to function correctly in the local development setup. ```bash # Database DATABASE_URL="postgresql://postgres:postgres@localhost:5432/supastarter" # Storage (MinIO) S3_ACCESS_KEY_ID="minioadmin" S3_SECRET_ACCESS_KEY="minioadmin" S3_ENDPOINT="http://localhost:9000" S3_REGION="us-east-1" NEXT_PUBLIC_AVATARS_BUCKET_NAME="avatars" ``` -------------------------------- ### Initialize QStash Client Source: https://supastarter.dev/docs/nextjs/tasks/qstash Create a utility file to initialize the QStash client with your credentials. ```typescript import { Client as QStashClient } from "@upstash/qstash"; export const qstashClient = new QStashClient({ baseUrl: process.env.QSTASH_URL, token: process.env.QSTASH_TOKEN, }); ``` -------------------------------- ### Use AI Prompt to Generate Product Names Source: https://supastarter.dev/docs/nextjs/ai/prompts This example shows how to call the prompt generation function and use the resulting prompt with the `streamText` function to get AI-generated product names. The response is expected to be a JSON array. ```typescript const prompt = generateProductNamesPrompt("dog food"); const response = await streamText({ model: textModel, messages: [ { role: "user", content: prompt } ] }); ``` -------------------------------- ### Create a New Supastarter Project Source: https://supastarter.dev/docs/nextjs/setup Run this command to initialize a new Supastarter project. Replace 'my-awesome-project' with your desired project name. ```bash npx supastarter new my-awesome-project ``` -------------------------------- ### Initialize Git Repository and Add Upstream Source: https://supastarter.dev/docs/nextjs/setup Remove existing Git configuration, initialize a new repository, and add the Supastarter repository as an upstream remote. ```bash rm -rf .git git init git remote add upstream https://github.com/supastarter/supastarter-nextjs.git git add . git commit -m "Initial commit" ``` -------------------------------- ### Create a Turso Database Source: https://supastarter.dev/docs/nextjs/database/providers/turso Use the Turso CLI to create a new database instance. ```bash turso db create my-saas-db ``` -------------------------------- ### Configure Environment Variables Source: https://supastarter.dev/docs/nextjs/tasks/qstash Set up necessary QStash environment variables in your .env.local file. ```bash QSTASH_URL=https://qstash.upstash.io QSTASH_TOKEN=your_qstash_token_here QSTASH_CURRENT_SIGNING_KEY=your_current_signing_key_here QSTASH_NEXT_SIGNING_KEY=your_next_signing_key_here ``` -------------------------------- ### Configure .env.local for Neon Source: https://supastarter.dev/docs/nextjs/database/providers/neon Add both pooled and direct connection strings to your .env.local file. DATABASE_URL is for runtime, and DIRECT_URL is for migrations. ```bash DATABASE_URL="postgresql://user:password@ep-xxx-pooler.region.aws.neon.tech/neondb?sslmode=require" DIRECT_URL="postgresql://user:password@ep-xxx.region.aws.neon.tech/neondb?sslmode=require" ``` -------------------------------- ### Define GET endpoint to find a post by ID Source: https://supastarter.dev/docs/nextjs/api/define-endpoint Use this procedure to define a GET endpoint for retrieving a specific post using its ID. It follows OpenAPI best practices for path parameters. ```typescript import { z } from "zod"; import { PostSchema, publicProcedure } from "../../../orpc/procedures"; export const findPost = publicProcedure .route({ method: "GET", path: "/posts/{id}", tags: ["Posts"], summary: "Find post", description: "Find a post by id", }) .input( z.object({ id: z.string(), }), ) .output( z.object({ post: PostSchema, }), ) .handler(async ({ input }) => { const post = await findPost({ id: input.id, }); if (!post) { throw new ORPCError("NOT_FOUND", { message: "Post not found", }); } return { post }; }); ``` -------------------------------- ### Configure .env.local with Supabase URLs Source: https://supastarter.dev/docs/nextjs/database/providers/supabase Add both the pooler and direct connection strings to your .env.local file to manage database connections and migrations. ```bash DATABASE_URL="postgres://postgres.[project]:[password]@aws-0-[region].pooler.supabase.com:6543/postgres?pgbouncer=true" DIRECT_URL="postgresql://postgres:[password]@db.[project-ref].supabase.co:5432/postgres" ``` -------------------------------- ### Configure Turso Environment Variables Source: https://supastarter.dev/docs/nextjs/database/providers/turso Add your Turso database URL and authentication token to the .env.local file for application access. ```bash DATABASE_URL="libsql://your-db-name-your-org.turso.io" DATABASE_AUTH_TOKEN="your-auth-token" ``` -------------------------------- ### Create New Documentation Page Source: https://supastarter.dev/docs/nextjs/documentation Create a new .mdx file in the content directory to add a documentation page. Define 'title' and 'description' in the frontmatter. ```mdx --- title: Documentation description: Learn how to use our software --- Your content here ``` -------------------------------- ### Send Mail with Template Source: https://supastarter.dev/docs/nextjs/mailing/overview Example of how to send an email using a registered template and context data via the 'sendMail' function. ```typescript import { sendMail } from "mail"; await sendMail({ to: "tim@apple.com", template: "newMail", context: { name: "Tim Cook", }, }); ``` -------------------------------- ### Generate Prisma client Source: https://supastarter.dev/docs/nextjs/database/update-schema Re-generate the Prisma client after pushing schema changes. This command is also automatically run when starting the development server. ```bash pnpm --filter database generate ``` -------------------------------- ### Add endpoint to feature router Source: https://supastarter.dev/docs/nextjs/api/define-endpoint Integrate the newly defined endpoint procedure into the feature router. This example adds the 'listPosts' procedure to the 'postsRouter'. ```typescript import { listPosts } from "./procedures/list-posts"; export const postsRouter = { list: listPosts, }; ``` -------------------------------- ### Configure Uploadthing Environment Variable Source: https://supastarter.dev/docs/nextjs/storage/uploadthing Add your Uploadthing API token to your .env.local file. ```bash UPLOADTHING_TOKEN="your-uploadthing-token" ``` -------------------------------- ### Get Turso Database URL and Auth Token Source: https://supastarter.dev/docs/nextjs/database/providers/turso Retrieve the database connection URL and generate an authentication token using the Turso CLI. ```bash turso db show my-saas-db --url turso db tokens create my-saas-db ``` -------------------------------- ### Get Organization Data Client Side Source: https://supastarter.dev/docs/nextjs/organizations/use-organizations Fetches full organization data on the client side using the `authClient`. Requires an organization ID to be specified. ```typescript const { data, error } = await authClient.organization.getFullOrganization( { query: { organizationId: '1234lasjdfwlj34l', // replace with the organization id }, }, ); ``` -------------------------------- ### Create Supabase Project Source: https://supastarter.dev/docs/nextjs/recipes/supabase-setup Command to create a new Supabase project. This is the first step in integrating Supabase with your Supastarter application. ```bash npx supastarter new ``` -------------------------------- ### Get Translations in Server Components Source: https://supastarter.dev/docs/nextjs/internationalization Use the `getTranslations` method within server components to fetch translation functions. This is suitable for server-side rendering scenarios. ```tsx import { getTranslations } from "next-intl/server"; export default async function MyServerComponent() { const t = await getTranslations(); return
{t("hello")}
; } ``` -------------------------------- ### Access User and Session with useSession Hook Source: https://supastarter.dev/docs/nextjs/authentication/user-and-session Use the useSession hook to get the current user and session objects on the client-side. Both can be null if the user is not authenticated. ```tsx const { user, session } = useSession(); ``` -------------------------------- ### Add Translations for New Onboarding Step Source: https://supastarter.dev/docs/nextjs/customization/onboarding Include necessary translations for the new onboarding step in the application's translation files, typically in JSON format. ```json { "onboarding": { "step2": { "title": "Step 2 Title", "description": "Step 2 Description" // Add other translations } } } ``` -------------------------------- ### Create a new router file Source: https://supastarter.dev/docs/nextjs/api/define-endpoint Define a new router file to group related API endpoints. This example shows the basic structure for a 'posts' router. ```typescript export const postsRouter = { // your new endpoint will go here }; ``` -------------------------------- ### Set Supabase Environment Variables Source: https://supastarter.dev/docs/nextjs/recipes/supabase-setup Configure .env.local file with Supabase connection strings for transaction pooling and direct database access. Ensure placeholders are replaced with your project-specific values. ```bash # Connect to Supabase via connection pooling with Supavisor. DATABASE_URL="postgres://postgres.[your-supabase-project]:[password]@aws-0-[aws-region].pooler.supabase.com:6543/postgres?pgbouncer=true" # Direct connection to the database used by the Prisma CLI. DIRECT_URL="postgresql://postgres:password@db.[your-project-ref].supabase.co:5432/postgres" ``` -------------------------------- ### Get Session on Server with getSession Source: https://supastarter.dev/docs/nextjs/authentication/user-and-session Utilize the getSession function from the SaaS auth module to securely retrieve session data within server components (RSCs). ```tsx import { getSession } from "@auth/lib/server"; async function ServerComponent() { const session = await getSession(); return
User name: {JSON.stringify(session?.user.name)}
; } ``` -------------------------------- ### Build and Run Docker Image Locally Source: https://supastarter.dev/docs/nextjs/deployment/docker Build the Docker image for your Next.js app using the Dockerfile and then run the container locally. This is useful for testing the Docker deployment before pushing to a remote environment. Remember to map the ports and pass necessary environment variables. ```bash docker build -f apps/saas/Dockerfile . --no-cache -t supastarter-docker docker run -p 3000:3000 supastarter-docker ``` -------------------------------- ### Stop Local Development Services Source: https://supastarter.dev/docs/nextjs/codebase/local-development Use this command to stop the local development services (PostgreSQL and MinIO) started with Docker Compose. This command will stop the containers but not remove them. ```bash docker compose down ``` -------------------------------- ### Display UI for Specific Roles (Client-Side) Source: https://supastarter.dev/docs/nextjs/authentication/permissions Control client-side UI visibility based on user roles. This example shows content only if the user's role is 'admin'. ```tsx import { useSession } from "@auth/lib/client"; export function MyComponent() { const { session } = useSession(); if (session?.user.role !== 'admin') { return
This page is only accessible for admins
; } return
This page is only accessible for admins
; } ``` -------------------------------- ### Sync Jobs and Schedules to Production Source: https://supastarter.dev/docs/nextjs/tasks/queuebase Run 'npx queuebase sync' to synchronize your job types and schedules to the production environment before deploying your application. ```bash npx queuebase sync ``` -------------------------------- ### List Posts Endpoint Source: https://supastarter.dev/docs/nextjs/api/define-endpoint Defines a public GET endpoint to retrieve a list of posts, with optional limit and offset parameters. It also specifies the output schema for the response. ```APIDOC ## GET /posts ### Description Get all posts. ### Method GET ### Endpoint /posts ### Parameters #### Query Parameters - **limit** (number) - Optional - Maximum number of posts to return. - **offset** (number) - Optional - Number of posts to skip before starting to collect the result set. ### Response #### Success Response (200) - **posts** (array) - An array of post objects. ### Request Example { "limit": 10, "offset": 0 } ### Response Example { "posts": [ { "id": "clx3z2f7a000008l6f0z8z8z8", "title": "My First Post", "content": "This is the content of my first post.", "createdAt": "2024-01-01T12:00:00.000Z", "updatedAt": "2024-01-01T12:00:00.000Z", "authorId": "clx3z2f7a000008l6f0z8z8z8" } ] } ``` -------------------------------- ### Import shadcn/ui Components and Utilities Source: https://supastarter.dev/docs/nextjs/customization/styling Import UI components like Button and Card, as well as the 'cn' utility function for merging Tailwind classes, from the '@repo/ui' package after they have been added to your project. ```tsx import { Button } from "@repo/ui/components/button"; import { Card } from "@repo/ui/components/card"; import { cn } from "@repo/ui"; ``` -------------------------------- ### Create a React Email Template Source: https://supastarter.dev/docs/nextjs/mailing/overview Example of a React component used as an email template with internationalization support. It defines props for dynamic content and uses React Email components. ```tsx import { Link, Text } from "@react-email/components"; import { createTranslator } from "use-intl/core"; import type { BaseMailProps } from "../types"; import PrimaryButton from "./components/PrimaryButton"; import Wrapper from "./components/Wrapper"; export function MagicLink({ url, name, otp, locale, translations, }: { url: string; name: string; otp: string; } & BaseMailProps): JSX.Element { const t = createTranslator({ locale, messages: translations, namespace: "mail", }); return ( {t("magicLink.body", { name })} {t("common.otp")}
{otp}
{t("common.useLink")} {t("magicLink.login")} → {t("common.openLinkInBrowser")} {url}
); } export default MagicLink; ``` -------------------------------- ### Build Docs App for Deployment Source: https://supastarter.dev/docs/nextjs/documentation Build the documentation application before deploying it. This command filters the build process to only the docs app. ```bash pnpm --filter @repo/docs build ``` -------------------------------- ### Manually Format Codebase Source: https://supastarter.dev/docs/nextjs/codebase/formatting-and-linting Run this command to manually format the entire codebase using the project's configured formatter. ```bash pnpm format ``` -------------------------------- ### Get Active Organization on Server Side Source: https://supastarter.dev/docs/nextjs/organizations/use-organizations Retrieves the active organization data on the server using the organization slug from the URL. This function is useful for server-side rendering or API routes. ```tsx export default async function OrganizationPage({ children, params, }: PropsWithChildren<{ params: Promise<{ organizationSlug: string; }>; }>) { const { organizationSlug } = await params; const organization = await getActiveOrganization(organizationSlug); return
Active organization: {organization.name}
; } ``` -------------------------------- ### Configure PlanetScale Connection String Source: https://supastarter.dev/docs/nextjs/database/providers/planetscale Add the PlanetScale database connection string to your local environment variables file. ```bash DATABASE_URL="mysql://user:password@aws.connect.psdb.cloud/your-database?sslaccept=strict" ``` -------------------------------- ### Set Plausible URL Environment Variable Source: https://supastarter.dev/docs/nextjs/analytics/plausible Add the Plausible app URL to your .env.local file and deployment environment. ```bash NEXT_PUBLIC_PLAUSIBLE_URL=your_url_here ``` -------------------------------- ### Protect Route for Active or Specific Subscription (Server-Side) Source: https://supastarter.dev/docs/nextjs/authentication/permissions Secure server-side routes based on subscription status. This example checks for any active plan or a specific subscription level like 'pro'. ```tsx export async function MyPremiumPage() { const purchases = await getPurchases(); const { activePlan, hasSubscription } = createPurchasesHelper(purchases); if (!activePlan) { return redirect("/app"); // or show a message to the user that they need to subscribe to the premium plan } // or check for a specific subscription - you don't need to check for the active plan if you use this if (!hasSubscription('pro')) { return
This page is only accessible for users with a pro subscription
; } return
This page is only accessible for users with an active subscription
; } ``` -------------------------------- ### Configure .env.local for DigitalOcean Spaces Source: https://supastarter.dev/docs/nextjs/storage/digitalocean-spaces Add these environment variables to your .env.local file to connect to DigitalOcean Spaces. Ensure you replace the placeholder keys and endpoint with your actual Spaces credentials and region. ```bash S3_ACCESS_KEY_ID="your-spaces-access-key" S3_SECRET_ACCESS_KEY="your-spaces-secret-key" S3_ENDPOINT="https://nyc3.digitaloceanspaces.com" S3_REGION="nyc3" ``` -------------------------------- ### Call API Mutation in Client Component Source: https://supastarter.dev/docs/nextjs/api/usage-in-frontend Use `useMutation` from Tanstack Query to perform mutations in a client component. The example shows how to call a create mutation and handle the asynchronous response. ```tsx const { mutateAsync, isLoading } = useMutation(orpc.posts.create.mutationOptions()); const post = await mutateAsync({ input: { title: "My first post", content: "This is my first post", } }); ``` -------------------------------- ### Configure Postmark Server Token Source: https://supastarter.dev/docs/nextjs/mailing/postmark Add your Postmark server token as an environment variable in your .env.local file. ```bash POSTMARK_SERVER_TOKEN="your-server-token" ``` -------------------------------- ### Switching to Anthropic AI Model Source: https://supastarter.dev/docs/nextjs/ai/overview Example of changing the text model to use Anthropic's Claude instead of OpenAI. This involves importing the Anthropic provider and specifying the desired model. ```typescript import { anthropic } from "@ai-sdk/anthropic"; export const textModel = anthropic("claude-3-5-sonnet-20240620"); ``` -------------------------------- ### Get Organization Data Server Side Source: https://supastarter.dev/docs/nextjs/organizations/use-organizations Retrieves full organization data on the server side using the `auth` class. Ensure to pass necessary headers, as cookies are not automatically attached. ```typescript const organization = await auth.api.getFullOrganization({ headers: await headers(), query: { organizationId: '1234lasjdfwlj34l', // replace with the organization id }, }); ``` -------------------------------- ### Run E2E Tests Locally Source: https://supastarter.dev/docs/nextjs/e2e Execute E2E tests for specific applications within the project using pnpm. This command starts the development server and opens the Playwright UI for test execution. ```bash pnpm --filter saas e2e # or pnpm --filter marketing e2e ``` -------------------------------- ### Configure Drizzle Client for libSQL Source: https://supastarter.dev/docs/nextjs/database/providers/turso Set up the Drizzle ORM client to use the @libsql/client driver with Turso connection details. ```typescript import { drizzle } from "drizzle-orm/libsql"; import { createClient } from "@libsql/client"; import * as schema from "./schema"; const client = createClient({ url: process.env.DATABASE_URL!, authToken: process.env.DATABASE_AUTH_TOKEN, }); export const db = drizzle(client, { schema }); ``` -------------------------------- ### UI: Submit Post with Organization Context Source: https://supastarter.dev/docs/nextjs/organizations/store-data-for-organizations Example of how to use the `useCreateOrganizationPostMutation` hook in a React component. It ensures an active organization is selected before attempting to create a post, passing the `organizationId` from the active organization context. ```tsx // Assume useActiveOrganization and useCreateOrganizationPostMutation are imported // Assume onSubmit is part of a form handler // Mock hooks for demonstration const useActiveOrganization = () => ({ activeOrganization: { id: "org-abc" } }); const useCreateOrganizationPostMutation = () => ({ mutateAsync: async (data) => { console.log("Mutation called with:", data); return Promise.resolve(); } }); const YourComponent = () => { const { activeOrganization } = useActiveOrganization(); const createOrganizationPostMutation = useCreateOrganizationPostMutation(); const onSubmit = async (formData) => { if (!activeOrganization) { throw new Error("No active organization found"); } await createOrganizationPostMutation.mutateAsync({ ...formData, // Assuming formData contains title and content organizationId: activeOrganization.id, }); console.log("Post created successfully!"); } // Example usage within a form return (
{ e.preventDefault(); // Simulate form data onSubmit({ title: "New Post Title", content: "Post content here." }); }}> {/* Input fields for title and content would go here */}
); }; ``` -------------------------------- ### Dodo Payments Product ID Environment Variables Source: https://supastarter.dev/docs/nextjs/payments/providers/dodopayments Define monthly and yearly product IDs for Dodo Payments in your .env.local file. ```bash NEXT_PUBLIC_PRODUCT_ID_PRO_MONTHLY="" NEXT_PUBLIC_PRODUCT_ID_PRO_YEARLY="" ```