### Setup Dependencies and Database Source: https://github.com/t3-oss/create-t3-turbo/blob/main/README.md Install project dependencies, initialize environment variables from the example file, and synchronize the Drizzle schema with the database. ```bash pnpm i cp .env.example .env pnpm db:push ``` -------------------------------- ### Configure Environment Variables Source: https://context7.com/t3-oss/create-t3-turbo/llms.txt Example configuration for required environment variables including database connection strings and OAuth credentials. ```bash POSTGRES_URL="postgres://postgres.[USERNAME]:[PASSWORD]@aws-0-eu-central-1.pooler.supabase.com:6543/postgres" AUTH_SECRET='supersecret' AUTH_DISCORD_ID='' AUTH_DISCORD_SECRET='' ``` -------------------------------- ### Manage Auth Router Sessions Source: https://context7.com/t3-oss/create-t3-turbo/llms.txt Provides examples for retrieving user sessions and defining protected endpoints that require authentication. ```typescript import type { TRPCRouterRecord } from "@trpc/server"; import { protectedProcedure, publicProcedure } from "../trpc"; export const authRouter = { getSession: publicProcedure.query(({ ctx }) => { return ctx.session; }), getSecretMessage: protectedProcedure.query(() => { return "you can see this secret message!"; }), } satisfies TRPCRouterRecord; ``` -------------------------------- ### tRPC API Router Setup Source: https://context7.com/t3-oss/create-t3-turbo/llms.txt Defines the main tRPC router by combining authentication and post sub-routers, ensuring type safety across the application. ```APIDOC ## tRPC API Router Setup ### Description Combines auth and post sub-routers into a single typesafe API router. Exports the router and its type for client-side inference. ### Method N/A (This is a configuration file) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Code Example ```typescript // packages/api/src/root.ts import { authRouter } from "./router/auth"; import { postRouter } from "./router/post"; import { createTRPCRouter } from "./trpc"; export const appRouter = createTRPCRouter({ auth: authRouter, post: postRouter, }); export type AppRouter = typeof appRouter; ``` ``` -------------------------------- ### Setup Next.js tRPC Client Provider Source: https://context7.com/t3-oss/create-t3-turbo/llms.txt Configures the tRPC client for React components using React Query. It handles request batching, logging, and SuperJSON transformation. ```typescript import { useState } from "react"; import { QueryClientProvider } from "@tanstack/react-query"; import { createTRPCClient, httpBatchStreamLink, loggerLink } from "@trpc/client"; import { createTRPCContext } from "@trpc/tanstack-react-query"; import SuperJSON from "superjson"; export const { useTRPC, TRPCProvider } = createTRPCContext(); export function TRPCReactProvider(props: { children: React.ReactNode }) { const [trpcClient] = useState(() => createTRPCClient({ links: [ loggerLink({ enabled: (op) => process.env.NODE_ENV === "development" }), httpBatchStreamLink({ transformer: SuperJSON, url: "/api/trpc", headers() { return { "x-trpc-source": "nextjs-react" }; }, }), ], }) ); return ( {props.children} ); } ``` -------------------------------- ### Configure Expo for iOS Simulator Source: https://github.com/t3-oss/create-t3-turbo/blob/main/README.md Modify the 'dev' script in `apps/expo/package.json` to enable launching the Expo Go app on an iOS simulator. This requires Xcode and command-line tools to be installed. ```json { "dev": "expo start --ios" } ``` -------------------------------- ### Configure Expo for Android Emulator Source: https://github.com/t3-oss/create-t3-turbo/blob/main/README.md Modify the 'dev' script in `apps/expo/package.json` to enable launching the Expo Go app on an Android emulator. This requires Android Studio tools to be installed. ```json { "dev": "expo start --android" } ``` -------------------------------- ### Initialize Project with CLI Source: https://github.com/t3-oss/create-t3-turbo/blob/main/README.md Use the Turborepo CLI to initialize a new project based on the create-t3-turbo template. This command requires pnpm as the package manager. ```bash npx create-turbo@latest -e https://github.com/t3-oss/create-t3-turbo ``` -------------------------------- ### Initialize New Package in Monorepo Source: https://github.com/t3-oss/create-t3-turbo/blob/main/README.md Run `pnpm turbo gen init` in the monorepo root to generate a new package. This script sets up essential files like `package.json`, `tsconfig.json`, and `index.ts`, along with necessary tooling configurations. ```bash pnpm turbo gen init ``` -------------------------------- ### Execute CLI Development Commands Source: https://context7.com/t3-oss/create-t3-turbo/llms.txt Common Turborepo and pnpm commands for managing dependencies, database migrations, and development workflows. ```bash pnpm i cp .env.example .env pnpm db:push pnpm --filter @acme/auth generate pnpm dev pnpm typecheck pnpm lint ``` -------------------------------- ### Add New UI Component with shadcn/ui CLI Source: https://github.com/t3-oss/create-t3-turbo/blob/main/README.md Use the `ui-add` script to interactively add new UI components to your project using the `shadcn/ui` CLI. This command simplifies the process of integrating pre-built components. ```bash pnpm ui-add ``` -------------------------------- ### Initialize Better Auth with Discord OAuth Source: https://context7.com/t3-oss/create-t3-turbo/llms.txt Sets up authentication using Better Auth with Drizzle adapter and Discord OAuth. It includes support for mobile integration via Expo and proxying for production URLs. ```typescript import { expo } from "@better-auth/expo"; import { betterAuth } from "better-auth"; import { drizzleAdapter } from "better-auth/adapters/drizzle"; import { oAuthProxy } from "better-auth/plugins"; import { db } from "@acme/db/client"; export function initAuth(options: { baseUrl: string; productionUrl: string; secret: string | undefined; discordClientId: string; discordClientSecret: string; }) { return betterAuth({ database: drizzleAdapter(db, { provider: "pg" }), baseURL: options.baseUrl, secret: options.secret, plugins: [ oAuthProxy({ productionURL: options.productionUrl }), expo(), ], socialProviders: { discord: { clientId: options.discordClientId, clientSecret: options.discordClientSecret, redirectURI: `${options.productionUrl}/api/auth/callback/discord`, }, }, trustedOrigins: ["expo://"], }); } ``` -------------------------------- ### Configure tRPC Root Router Source: https://context7.com/t3-oss/create-t3-turbo/llms.txt Initializes the main application router by combining sub-routers and exports the AppRouter type for client-side type inference. ```typescript import { authRouter } from "./router/auth"; import { postRouter } from "./router/post"; import { createTRPCRouter } from "./trpc"; export const appRouter = createTRPCRouter({ auth: authRouter, post: postRouter, }); export type AppRouter = typeof appRouter; ``` -------------------------------- ### Configure Database Client for Edge Source: https://context7.com/t3-oss/create-t3-turbo/llms.txt Initializes the Drizzle ORM client specifically for edge environments using Vercel Postgres. It includes schema integration and enforces snake_case casing. ```typescript import { sql } from "@vercel/postgres"; import { drizzle } from "drizzle-orm/vercel-postgres"; import * as schema from "./schema"; export const db = drizzle({ client: sql, schema, casing: "snake_case", }); ``` -------------------------------- ### Implement Post CRUD Operations Source: https://context7.com/t3-oss/create-t3-turbo/llms.txt Demonstrates typesafe CRUD operations for posts using Drizzle ORM and Zod validation, utilizing both public and protected procedures. ```typescript import type { TRPCRouterRecord } from "@trpc/server"; import { z } from "zod/v4"; import { desc, eq } from "@acme/db"; import { CreatePostSchema, Post } from "@acme/db/schema"; import { protectedProcedure, publicProcedure } from "../trpc"; export const postRouter = { all: publicProcedure.query(({ ctx }) => { return ctx.db.query.Post.findMany({ orderBy: desc(Post.id), limit: 10 }); }), byId: publicProcedure.input(z.object({ id: z.string() })).query(({ ctx, input }) => { return ctx.db.query.Post.findFirst({ where: eq(Post.id, input.id) }); }), create: protectedProcedure.input(CreatePostSchema).mutation(({ ctx, input }) => { return ctx.db.insert(Post).values(input); }), delete: protectedProcedure.input(z.string()).mutation(({ ctx, input }) => { return ctx.db.delete(Post).where(eq(Post.id, input)); }), } satisfies TRPCRouterRecord; ``` -------------------------------- ### tRPC Context and Procedures Source: https://context7.com/t3-oss/create-t3-turbo/llms.txt Sets up the tRPC context for database access and session information, and defines public and protected procedure types. ```APIDOC ## tRPC Context and Procedures ### Description Provides database access and session information through the tRPC context. Defines `publicProcedure` for unauthenticated access and `protectedProcedure` for authenticated-only endpoints. ### Method N/A (This is a configuration file) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Code Example ```typescript // packages/api/src/trpc.ts import { initTRPC, TRPCError } from "@trpc/server"; import superjson from "superjson"; import { z, ZodError } from "zod/v4"; import type { Auth } from "@acme/auth"; import { db } from "@acme/db/client"; export const createTRPCContext = async (opts: { headers: Headers; auth: Auth; }) => { const authApi = opts.auth.api; const session = await authApi.getSession({ headers: opts.headers }); return { authApi, session, db }; }; const t = initTRPC.context().create({ transformer: superjson, errorFormatter: ({ shape, error }) => ({ ...shape, data: { ...shape.data, zodError: error.cause instanceof ZodError ? z.flattenError(error.cause) : null, }, }), }); export const createTRPCRouter = t.router; export const publicProcedure = t.procedure; export const protectedProcedure = t.procedure.use(({ ctx, next }) => { if (!ctx.session?.user) { throw new TRPCError({ code: "UNAUTHORIZED" }); } return next({ ctx: { session: { ...ctx.session, user: ctx.session.user } } }); }); ``` ``` -------------------------------- ### Define tRPC Context and Procedures Source: https://context7.com/t3-oss/create-t3-turbo/llms.txt Sets up the tRPC context to provide database access and session information. Defines public and protected procedures with error formatting. ```typescript import { initTRPC, TRPCError } from "@trpc/server"; import superjson from "superjson"; import { z, ZodError } from "zod/v4"; import type { Auth } from "@acme/auth"; import { db } from "@acme/db/client"; export const createTRPCContext = async (opts: { headers: Headers; auth: Auth; }) => { const authApi = opts.auth.api; const session = await authApi.getSession({ headers: opts.headers }); return { authApi, session, db }; }; const t = initTRPC.context().create({ transformer: superjson, errorFormatter: ({ shape, error }) => ({ ...shape, data: { ...shape.data, zodError: error.cause instanceof ZodError ? z.flattenError(error.cause) : null, }, }), }); export const createTRPCRouter = t.router; export const publicProcedure = t.procedure; export const protectedProcedure = t.procedure.use(({ ctx, next }) => { if (!ctx.session?.user) { throw new TRPCError({ code: "UNAUTHORIZED" }); } return next({ ctx: { session: { ...ctx.session, user: ctx.session.user } } }); }); ``` -------------------------------- ### Manage UI Package Exports Source: https://context7.com/t3-oss/create-t3-turbo/llms.txt Defines how the shared UI package exports components for use in different applications within the monorepo. ```json { ".": "./src/index.ts", "./button": "./src/button.tsx", "./dropdown-menu": "./src/dropdown-menu.tsx", "./input": "./src/input.tsx" } ``` -------------------------------- ### Generate Better Auth Schema Source: https://github.com/t3-oss/create-t3-turbo/blob/main/README.md Use the Better Auth CLI to generate the necessary Drizzle schema files for authentication. This command filters the workspace to the auth package and outputs the schema to the database package. ```bash pnpm --filter @acme/auth generate ``` -------------------------------- ### Implement tRPC Hooks in React Components Source: https://context7.com/t3-oss/create-t3-turbo/llms.txt Demonstrates how to use tRPC with React Query for fetching data, performing mutations, and invalidating cache in React components. ```typescript export function PostList() { const trpc = useTRPC(); const { data: posts } = useSuspenseQuery(trpc.post.all.queryOptions()); return
{posts.map((post) => )}
; } export function CreatePostForm() { const trpc = useTRPC(); const queryClient = useQueryClient(); const createPost = useMutation( trpc.post.create.mutationOptions({ onSuccess: async () => { await queryClient.invalidateQueries(trpc.post.pathFilter()); }, onError: (err) => { if (err.data?.code === "UNAUTHORIZED") { console.error("You must be logged in to post"); } }, }) ); const handleSubmit = (data: { title: string; content: string }) => { createPost.mutate(data); }; } ``` -------------------------------- ### Configure tRPC Client for Expo Source: https://context7.com/t3-oss/create-t3-turbo/llms.txt Sets up the tRPC client for a React Native/Expo environment. It includes authentication cookie handling and logger middleware for development. ```typescript import { QueryClient } from "@tanstack/react-query"; import { createTRPCClient, httpBatchLink, loggerLink } from "@trpc/client"; import { createTRPCOptionsProxy } from "@trpc/tanstack-react-query"; import superjson from "superjson"; import type { AppRouter } from "@acme/api"; import { authClient } from "./auth"; import { getBaseUrl } from "./base-url"; export const queryClient = new QueryClient(); export const trpc = createTRPCOptionsProxy({ client: createTRPCClient({ links: [ loggerLink({ enabled: () => process.env.NODE_ENV === "development" }), httpBatchLink({ transformer: superjson, url: `${getBaseUrl()}/api/trpc`, headers() { const headers = new Map(); headers.set("x-trpc-source", "expo-react"); const cookies = authClient.getCookie(); if (cookies) headers.set("Cookie", cookies); return headers; }, }), ], }), queryClient, }); ``` -------------------------------- ### POST /api/posts Source: https://context7.com/t3-oss/create-t3-turbo/llms.txt Handles CRUD operations for posts, including creating, retrieving, and deleting posts. Supports public and protected procedures. ```APIDOC ## POST /api/posts ### Description Provides endpoints for managing posts. Includes procedures to fetch all posts, retrieve a single post by ID, create a new post, and delete a post. Create and delete operations require authentication. ### Method POST ### Endpoint /api/posts ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **create**: `CreatePostSchema` (object) - Required - Schema for creating a new post. - **byId**: `id` (string) - Required - The ID of the post to retrieve. - **delete**: `id` (string) - Required - The ID of the post to delete. ### Request Example ```json // Example for create procedure: { "title": "My First Post", "content": "This is the content of my first post." } // Example for byId or delete procedure: "post-id-123" ``` ### Response #### Success Response (200) - **all**: `Post[]` - An array of post objects. - **byId**: `Post | null` - The requested post object or null if not found. - **create**: `Post` - The newly created post object. - **delete**: `AffectedRowsOutput` - Information about the deletion operation. #### Response Example ```json // Example for all procedure: [ { "id": "post-id-123", "title": "My First Post", "content": "This is the content of my first post.", "createdAt": "2023-01-01T12:00:00.000Z", "updatedAt": "2023-01-01T12:00:00.000Z" } ] // Example for byId procedure: { "id": "post-id-123", "title": "My First Post", "content": "This is the content of my first post.", "createdAt": "2023-01-01T12:00:00.000Z", "updatedAt": "2023-01-01T12:00:00.000Z" } // Example for create procedure: { "id": "post-id-456", "title": "My Second Post", "content": "Content for the second post.", "createdAt": "2023-01-02T10:00:00.000Z", "updatedAt": "2023-01-02T10:00:00.000Z" } // Example for delete procedure: { "count": 1 } ``` ### Code Example ```typescript // packages/api/src/router/post.ts import type { TRPCRouterRecord } from "@trpc/server"; import { z } from "zod/v4"; import { desc, eq } from "@acme/db"; import { CreatePostSchema, Post } from "@acme/db/schema"; import { protectedProcedure, publicProcedure } from "../trpc"; export const postRouter = { // Get all posts (public) all: publicProcedure.query(({ ctx }) => { return ctx.db.query.Post.findMany({ orderBy: desc(Post.id), limit: 10, }); }), // Get post by ID (public) byId: publicProcedure .input(z.object({ id: z.string() })) .query(({ ctx, input }) => { return ctx.db.query.Post.findFirst({ where: eq(Post.id, input.id), }); }), // Create post (authenticated) create: protectedProcedure .input(CreatePostSchema) .mutation(({ ctx, input }) => { return ctx.db.insert(Post).values(input); }), // Delete post (authenticated) delete: protectedProcedure .input(z.string()) .mutation(({ ctx, input }) => { return ctx.db.delete(Post).where(eq(Post.id, input)); }), } satisfies TRPCRouterRecord; ``` ``` -------------------------------- ### Configure Next.js Server-Side tRPC Source: https://context7.com/t3-oss/create-t3-turbo/llms.txt Enables direct router access in Next.js Server Components. Uses React cache for request deduplication and provides hydration support for server-fetched data. ```typescript import { cache } from "react"; import { headers } from "next/headers"; import { dehydrate, HydrationBoundary } from "@tanstack/react-query"; import { createTRPCOptionsProxy } from "@trpc/tanstack-react-query"; import { appRouter, createTRPCContext } from "@acme/api"; const createContext = cache(async () => { const heads = new Headers(await headers()); heads.set("x-trpc-source", "rsc"); return createTRPCContext({ headers: heads, auth }); }); export const trpc = createTRPCOptionsProxy({ router: appRouter, ctx: createContext, queryClient: getQueryClient, }); ``` -------------------------------- ### Define Database Schema with Drizzle and Zod Source: https://context7.com/t3-oss/create-t3-turbo/llms.txt Defines a PostgreSQL table using Drizzle ORM and automatically generates Zod validation schemas. This ensures type safety and data integrity for database operations. ```typescript import { sql } from "drizzle-orm"; import { pgTable } from "drizzle-orm/pg-core"; import { createInsertSchema } from "drizzle-zod"; import { z } from "zod/v4"; export const Post = pgTable("post", (t) => ({ id: t.uuid().notNull().primaryKey().defaultRandom(), title: t.varchar({ length: 256 }).notNull(), content: t.text().notNull(), createdAt: t.timestamp().defaultNow().notNull(), updatedAt: t.timestamp({ mode: "date", withTimezone: true }) .$onUpdateFn(() => sql`now()`), })); export const CreatePostSchema = createInsertSchema(Post, { title: z.string().max(256), content: z.string().max(256), }).omit({ id: true, createdAt: true, updatedAt: true, }); ``` -------------------------------- ### Auth API Endpoints Source: https://context7.com/t3-oss/create-t3-turbo/llms.txt Provides endpoints for authentication-related operations, including retrieving user session information and accessing protected messages. ```APIDOC ## Auth API Endpoints ### Description Offers endpoints for session management and protected content access. Includes a public procedure to get the current session and a protected procedure to retrieve a secret message. ### Method GET ### Endpoint /api/auth ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **getSession**: `Session | null` - The current user session object or null if not authenticated. - **getSecretMessage**: `string` - A secret message accessible only to authenticated users. #### Response Example ```json // Example for getSession procedure: { "user": { "id": "user-id-123", "name": "John Doe", "email": "john.doe@example.com" }, "expires": "2024-12-31T23:59:59.000Z" } // Example for getSecretMessage procedure: "you can see this secret message!" ``` ### Code Example ```typescript // packages/api/src/router/auth.ts import type { TRPCRouterRecord } from "@trpc/server"; import { protectedProcedure, publicProcedure } from "../trpc"; export const authRouter = { getSession: publicProcedure.query(({ ctx }) => { return ctx.session; }), getSecretMessage: protectedProcedure.query(() => { return "you can see this secret message!"; }), } satisfies TRPCRouterRecord; ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.