### Install create-t3-app using yarn Source: https://github.com/t3-oss/create-t3-app/blob/main/cli/README.md This command initializes a new T3 Stack project using yarn. It guides the user through a series of questions to customize the project setup. Yarn must be installed globally. ```bash yarn create t3-app ``` -------------------------------- ### tRPC Router Setup Example Source: https://context7.com/t3-oss/create-t3-app/llms.txt Illustrates the setup of a tRPC router for type-safe API routes in a T3 Stack application. This example defines procedures for queries and mutations, including input validation with Zod and database interactions using Prisma. It also shows how to create protected procedures requiring authentication. ```typescript // src/server/api/routers/post.ts import { z } from "zod"; import { createTRPCRouter, publicProcedure, protectedProcedure } from "~/server/api/trpc"; export const postRouter = createTRPCRouter({ // Query with input validation hello: publicProcedure .input(z.object({ text: z.string() })) .query(({ input }) => { return { greeting: `Hello ${input.text}`, }; }), // Mutation with database access create: publicProcedure .input(z.object({ name: z.string().min(1) })) .mutation(async ({ ctx, input }) => { return ctx.db.post.create({ data: { name: input.name, }, }); }), // Query with database access getLatest: publicProcedure.query(async ({ ctx }) => { const post = await ctx.db.post.findFirst({ orderBy: { createdAt: "desc" }, }); return post ?? null; }), // Protected procedure (requires authentication) getSecretMessage: protectedProcedure.query(({ ctx }) => { return `Hello ${ctx.session.user.name}, you can see this secret message!`; }), }); ``` -------------------------------- ### Create T3 App CI/Automated Usage Examples Source: https://context7.com/t3-oss/create-t3-app/llms.txt Provides examples for using the create-t3-app CLI in CI environments or for automated setups. These commands utilize the --CI flag along with explicit package selections to bypass interactive prompts and configure specific stack components and database providers. ```bash # CI mode with specific package selections npm create t3-app@latest my-app --CI \ --tailwind true \ --trpc true \ --prisma true \ --nextAuth true \ --appRouter true \ --eslint true \ --dbProvider postgres # CI mode with Drizzle instead of Prisma npm create t3-app@latest my-app --CI \ --tailwind true \ --trpc true \ --drizzle true \ --dbProvider mysql \ --eslint true # CI mode with Better Auth and Biome npm create t3-app@latest my-app --CI \ --tailwind true \ --trpc true \ --drizzle true \ --betterAuth true \ --biome true \ --dbProvider sqlite # Database provider options: sqlite, mysql, postgres, planetscale npm create t3-app@latest my-app --CI --prisma true --dbProvider planetscale ``` -------------------------------- ### Clone and Run create-t3-app Locally Source: https://github.com/t3-oss/create-t3-app/blob/main/www/README.md This snippet shows the commands to clone the create-t3-app repository, navigate to the www directory, install dependencies, and start the local development server. ```bash git clone https://github.com/t3-oss/create-t3-app.git cd create-t3-app/www pnpm i pnpm dev ``` -------------------------------- ### Install create-t3-app using Bun Source: https://github.com/t3-oss/create-t3-app/blob/main/README.md This command uses the Bun package manager to create a new T3 Stack application. Ensure Bun is installed on your system before running this command. It initiates the project setup process by downloading and executing the latest version of create-t3-app. ```bash bun create t3-app@latest ``` -------------------------------- ### Install create-t3-app using pnpm Source: https://github.com/t3-oss/create-t3-app/blob/main/cli/README.md This command scaffolds a new T3 Stack application using pnpm. It provides an interactive setup process where users can select their desired configurations. pnpm needs to be installed on your system. ```bash pnpm create t3-app@latest ``` -------------------------------- ### Create T3 App CLI Usage Examples Source: https://context7.com/t3-oss/create-t3-app/llms.txt Demonstrates various ways to use the create-t3-app CLI for scaffolding new projects. This includes interactive mode, using different package managers, specifying project names, using default configurations, and customizing options like Git initialization, dependency installation, and import aliases. ```bash # Interactive mode - prompts for all options npm create t3-app@latest # Using different package managers yarn create t3-app pnpm create t3-app@latest bun create t3-app@latest # Specify project name npm create t3-app@latest my-app # Use all defaults (Next.js + Tailwind + tRPC + Prisma + NextAuth + ESLint) npm create t3-app@latest my-app --default # Skip git initialization npm create t3-app@latest my-app --noGit # Skip dependency installation npm create t3-app@latest my-app --noInstall # Custom import alias npm create t3-app@latest my-app --import-alias "@/" ``` -------------------------------- ### Install create-t3-app using npm Source: https://github.com/t3-oss/create-t3-app/blob/main/cli/README.md This command initializes a new T3 Stack project using npm. It prompts the user with questions to configure the application based on their specific needs. Ensure you have Node.js and npm installed. ```bash npm create t3-app@latest ``` -------------------------------- ### Install Netlify CLI (Bash) Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/deployment/netlify.mdx Installs the Netlify CLI globally on your machine, allowing you to manage Netlify deployments from the command line. ```bash npm i -g netlify-cli ``` -------------------------------- ### Scaffold T3 App with NextAuth, Tailwind, Drizzle, and PostgreSQL (pnpm) Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/installation.mdx This command scaffolds a T3 App with NextAuth.js, Tailwind CSS, Drizzle, and PostgreSQL using pnpm, utilizing experimental CI flags for an automated setup. The `--dbProvider postgres` flag specifies the database. Ensure the `--CI` flag is present. ```bash pnpm dlx create-t3-app@latest --CI --nextAuth --tailwind --drizzle --dbProvider postgres ``` -------------------------------- ### Start Local Netlify Development Environment (Bash) Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/deployment/netlify.mdx Starts a local development server for your Netlify project, accessible at localhost:8888. This command is useful for testing your deployment locally before pushing to production. ```bash ntl dev ``` -------------------------------- ### tRPC Root Router Configuration Example Source: https://context7.com/t3-oss/create-t3-app/llms.txt Demonstrates the configuration of the root tRPC router, which aggregates all individual routers and exports type definitions for client-side usage. This setup is crucial for enabling type safety across the client and server communication within the T3 Stack. ```typescript // src/server/api/root.ts import { postRouter } from "~/server/api/routers/post"; import { createCallerFactory, createTRPCRouter } from "~/server/api/trpc"; export const appRouter = createTRPCRouter({ post: postRouter, // Add more routers here }); // Export type definition for client export type AppRouter = typeof appRouter; // Server-side caller for RSC export const createCaller = createCallerFactory(appRouter); ``` -------------------------------- ### Install Vercel CLI Globally (Bash) Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/deployment/vercel.md This command installs the Vercel Command Line Interface (CLI) globally on your system using npm. This is a prerequisite for deploying projects from the command line. Ensure you have Node.js and npm installed. ```bash npm i -g vercel ``` -------------------------------- ### Scaffold T3 App with CI flags (pnpm) Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/installation.mdx This command scaffolds a T3 App with tRPC and Tailwind CSS using pnpm, leveraging experimental CI flags for an automated setup. Ensure the `--CI` flag is present for other flags to take effect. ```bash pnpm dlx create-t3-app@latest --CI --trpc --tailwind ``` -------------------------------- ### NextAuth.js Authentication Setup (TypeScript) Source: https://context7.com/t3-oss/create-t3-app/llms.txt Configures NextAuth.js with Discord OAuth provider and Prisma adapter for authentication. It defines session structure and includes necessary imports from next-auth and Prisma. ```typescript import { type DefaultSession, type NextAuthConfig } from "next-auth"; import DiscordProvider from "next-auth/providers/discord"; import { PrismaAdapter } from "@auth/prisma-adapter"; import { db } from "~/server/db"; declare module "next-auth" { interface Session extends DefaultSession { user: { id: string; } & DefaultSession["user"]; } } export const authConfig = { providers: [ DiscordProvider({ clientId: process.env.AUTH_DISCORD_ID, clientSecret: process.env.AUTH_DISCORD_SECRET, }), ], adapter: PrismaAdapter(db), callbacks: { session: ({ session, user }) => ({ ...session, user: { ...session.user, id: user.id, }, }), }, } satisfies NextAuthConfig; ``` -------------------------------- ### Example .env.example file content Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/usage/env-variables.mdx This demonstrates how to add an environment variable to the `.env.example` file. For secret variables, the value should be omitted. ```bash TWITTER_API_TOKEN= ``` -------------------------------- ### Set up TRPCReactProvider for React Query and tRPC Client Source: https://context7.com/t3-oss/create-t3-app/llms.txt Configures the TRPCReactProvider to wrap the application, integrating React Query and tRPC client setup. This includes defining API links for communication and enabling development-time logging. ```typescript "use client"; import { QueryClientProvider } from "@tanstack/react-query"; import { httpBatchStreamLink, loggerLink } from "@trpc/client"; import { createTRPCReact } from "@trpc/react-query"; import { useState } from "react"; import SuperJSON from "superjson"; import { type AppRouter } from "~/server/api/root"; import { createQueryClient } from "./query-client"; export const api = createTRPCReact(); export function TRPCReactProvider(props: { children: React.ReactNode }) { const queryClient = createQueryClient(); const [trpcClient] = useState(() => api.createClient({ links: [ loggerLink({ enabled: (op) => process.env.NODE_ENV === "development" || (op.direction === "down" && op.result instanceof Error), }), httpBatchStreamLink({ transformer: SuperJSON, url: "/api/trpc", headers: () => { const headers = new Headers(); headers.set("x-trpc-source", "nextjs-react"); return headers; }, }), ], }) ); return ( {props.children} ); } ``` -------------------------------- ### Example .env file content Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/usage/env-variables.mdx This shows an example of how to add a server-side environment variable to the `.env` file. The format is `KEY=VALUE`. ```env TWITTER_API_TOKEN=1234567890 ``` -------------------------------- ### Better Auth Authentication Setup (TypeScript) Source: https://context7.com/t3-oss/create-t3-app/llms.txt Sets up Better Auth with a Drizzle adapter and GitHub social provider. It defines the database connection and social login configurations, exporting the auth instance and session type. ```typescript import { betterAuth } from "better-auth"; import { drizzleAdapter } from "better-auth/adapters/drizzle"; import { db } from "~/server/db"; export const auth = betterAuth({ database: drizzleAdapter(db, { provider: "pg", // or "mysql", "sqlite" }), socialProviders: { github: { clientId: process.env.BETTER_AUTH_GITHUB_CLIENT_ID!, clientSecret: process.env.BETTER_AUTH_GITHUB_CLIENT_SECRET!, }, }, }); export type Session = typeof auth.$Infer.Session; ``` -------------------------------- ### Docker Compose Build and Run Command Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/deployment/docker.md The command to build the Docker image and start the T3 application container using Docker Compose. After running this command, the application can be accessed at `localhost:3000`. ```bash docker compose up --build ``` -------------------------------- ### Prisma Client Configuration for Development Source: https://context7.com/t3-oss/create-t3-app/llms.txt Configures the Prisma client with logging enabled for development environments to aid in debugging. It utilizes environment variables for configuration. This setup ensures hot reloading works seamlessly. ```typescript // src/server/db.ts import { PrismaClient } from "@prisma/client"; import { env } from "~/env"; const createPrismaClient = () => new PrismaClient({ log: env.NODE_ENV === "development" ? ["query", "error", "warn"] : ["error"], }); const globalForPrisma = globalThis as unknown as { prisma: ReturnType | undefined; }; export const db = globalForPrisma.prisma ?? createPrismaClient(); if (env.NODE_ENV !== "production") globalForPrisma.prisma = db; ``` -------------------------------- ### Protect Pages with Next.js Middleware Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/usage/_next-auth-app-router.mdx Shows how to protect pages in a Next.js application using the middleware file. This setup leverages the auth function from '@/auth' to handle authentication checks for incoming requests. ```typescript export { auth as middleware } from "@/auth" ``` -------------------------------- ### Configure Vercel Project Build and Commands (JSON) Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/deployment/vercel.md This JSON configuration file allows you to specify build, development, and installation commands for Vercel. It's useful for projects where Vercel's automatic detection might not be sufficient. No external dependencies are required for this configuration. ```json { "buildCommand": "npm run build", "devCommand": "npm run dev", "installCommand": "npm install" } ``` -------------------------------- ### Traditional CSS vs. Tailwind CSS Example Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/usage/tailwind.md Demonstrates the difference between writing traditional CSS in a separate file and applying utility classes directly in HTML using Tailwind CSS. This highlights Tailwind's conciseness and efficiency in UI development. ```css .my-class { display: flex; flex-direction: column; justify-content: center; align-items: center; background-color: #fff; border: 1px solid #e2e8f0; border-radius: 0.25rem; padding: 1rem; } ``` ```jsx import "./my-class.css";
...
``` ```html
...
``` -------------------------------- ### Seed Prisma Database with TypeScript Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/usage/prisma.md This TypeScript code defines a `seed.ts` file used to populate the Prisma database with initial data. It demonstrates using `db.example.upsert` to create or update an example record, ensuring the database is seeded correctly before application startup. ```typescript import { db } from "../src/server/db"; async function main() { const id = "cl9ebqhxk00003b600tymydho"; await db.example.upsert({ where: { id, }, create: { id, }, update: {}, }); } main() .then(async () => { await db.$disconnect(); }) .catch(async (e) => { console.error(e); await db.$disconnect(); process.exit(1); }); ``` -------------------------------- ### Dockerfile for T3 Stack Deployment Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/deployment/docker.md A multi-stage Dockerfile designed to build and run a T3 stack application. It includes stages for installing dependencies, building the application with Next.js standalone output, and a final lean runner stage using distroless. ```dockerfile ##### DEPENDENCIES FROM --platform=linux/amd64 node:20-alpine AS deps RUN apk add --no-cache libc6-compat openssl WORKDIR /app # Install Prisma Client - remove if not using Prisma COPY prisma ./ # Install dependencies based on the preferred package manager COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./ RUN \ if [ -f yarn.lock ]; then yarn --frozen-lockfile; \ elif [ -f package-lock.json ]; then npm ci; \ elif [ -f pnpm-lock.yaml ]; then npm install -g pnpm && pnpm i; \ else echo "Lockfile not found." && exit 1; \ fi ##### BUILDER FROM --platform=linux/amd64 node:20-alpine AS builder ARG DATABASE_URL ARG NEXT_PUBLIC_CLIENTVAR WORKDIR /app COPY --from=deps /app/node_modules ./ COPY . . # ENV NEXT_TELEMETRY_DISABLED 1 RUN \ if [ -f yarn.lock ]; then SKIP_ENV_VALIDATION=1 yarn build; \ elif [ -f package-lock.json ]; then SKIP_ENV_VALIDATION=1 npm run build; \ elif [ -f pnpm-lock.yaml ]; then npm install -g pnpm && SKIP_ENV_VALIDATION=1 pnpm run build; \ else echo "Lockfile not found." && exit 1; \ fi ##### RUNNER FROM --platform=linux/amd64 gcr.io/distroless/nodejs20-debian12 AS runner WORKDIR /app ENV NODE_ENV production # ENV NEXT_TELEMETRY_DISABLED 1 COPY --from=builder /app/next.config.js ./ COPY --from=builder /app/public ./public COPY --from=builder /app/package.json ./package.json COPY --from=builder /app/.next/standalone ./ COPY --from=builder /app/.next/static ./.next/static EXPOSE 3000 ENV PORT 3000 CMD ["server.js"] ``` -------------------------------- ### Use tRPC Client in React Components with Type Safety Source: https://context7.com/t3-oss/create-t3-app/llms.txt Demonstrates how to use the tRPC client within React components, leveraging full type safety and React Query integration for data fetching and mutations. It includes examples for fetching the latest post and creating a new post. ```typescript "use client"; import { useState } from "react"; import { api } from "~/trpc/react"; export function LatestPost() { const [latestPost] = api.post.getLatest.useSuspenseQuery(); const utils = api.useUtils(); const [name, setName] = useState(""); const createPost = api.post.create.useMutation({ onSuccess: async () => { await utils.post.invalidate(); setName(""); }, }); return (
{latestPost ? (

Your most recent post: {latestPost.name}

) : (

You have no posts yet.

)
{ e.preventDefault(); createPost.mutate({ name }); }} > setName(e.target.value)} />
); } ``` -------------------------------- ### Initialize Netlify Project Configuration (Bash) Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/deployment/netlify.mdx Initializes your project for Netlify deployment, setting up necessary configurations. This command helps in automating the continuous deployment process. ```bash ntl init ``` -------------------------------- ### Database Commands (Bash) Source: https://context7.com/t3-oss/create-t3-app/llms.txt Lists generated npm scripts for database operations using Prisma and Drizzle, including commands for pushing schema changes, opening the database studio, generating migrations, and applying migrations. ```bash # Prisma commands npm run db:push # Push schema changes to database npm run db:studio # Open Prisma Studio GUI npm run db:generate # Generate migration files npm run db:migrate # Apply migrations to database # Drizzle commands npm run db:push # Push schema changes to database npm run db:studio # Open Drizzle Studio GUI npm run db:generate # Generate migration files npm run db:migrate # Apply migrations to database # Start development database (MySQL/PostgreSQL only) ./start-database.sh ``` -------------------------------- ### Environment File Template (.env) Source: https://context7.com/t3-oss/create-t3-app/llms.txt Provides a template for the .env file, including placeholders for authentication secrets and database connection strings for various databases like PostgreSQL, MySQL, and SQLite. ```bash # .env # When adding additional environment variables, update "/src/env.js" # Next Auth AUTH_SECRET="generated-secret-here" AUTH_DISCORD_ID="" AUTH_DISCORD_SECRET="" # Database (PostgreSQL) DATABASE_URL="postgresql://postgres:password@localhost:5432/myapp" # Database (MySQL) # DATABASE_URL="mysql://root:password@localhost:3306/myapp" # Database (SQLite) # DATABASE_URL="file:./db.sqlite" # Database (PlanetScale) # DATABASE_URL="mysql://YOUR_MYSQL_URL_HERE?sslaccept=strict" ``` -------------------------------- ### Enable CORS for tRPC API in Next.js Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/usage/trpc.md Configures a Next.js API route to handle tRPC requests while enabling Cross-Origin Resource Sharing (CORS). This is essential for consuming the API from different domains, such as in a monorepo setup. ```typescript import { type NextApiRequest, type NextApiResponse } from "next"; import { createNextApiHandler } from "@trpc/server/adapters/next"; import { appRouter } from "~/server/api/root"; import { createTRPCContext } from "~/server/api/trpc"; import cors from "nextjs-cors"; const handler = async (req: NextApiRequest, res: NextApiResponse) => { // Enable cors await cors(req, res); // Create and call the tRPC handler return createNextApiHandler({ router: appRouter, createContext: createTRPCContext, })(req, res); }; export default handler; ``` -------------------------------- ### Project Structure Overview Source: https://context7.com/t3-oss/create-t3-app/llms.txt This outlines the typical directory structure generated by Create T3 App, showcasing the organization of Next.js App Router, tRPC, authentication, database, and styling configurations. ```tree my-app/ ├── src/ │ ├── app/ # Next.js App Router │ │ ├── _components/ # React components │ │ ├── api/ │ │ │ ├── auth/ # Auth API routes │ │ │ └── trpc/ # tRPC API handler │ │ ├── layout.tsx # Root layout │ │ └── page.tsx # Home page │ ├── server/ │ │ ├── api/ │ │ │ ├── routers/ # tRPC routers │ │ │ ├── root.ts # Root router │ │ │ └── trpc.ts # tRPC configuration │ │ ├── auth/ # NextAuth configuration │ │ └── db.ts # Database client │ ├── trpc/ │ │ ├── react.tsx # Client-side tRPC │ │ ├── server.ts # Server-side tRPC │ │ └── query-client.ts # React Query config │ ├── styles/ │ │ └── globals.css # Global styles │ └── env.js # Environment validation ├── prisma/ │ └── schema.prisma # Database schema (if Prisma) ├── drizzle.config.ts # Drizzle config (if Drizzle) ├── .env # Environment variables ├── .env.example # Example env file ├── next.config.js # Next.js configuration ├── package.json └── tsconfig.json ``` -------------------------------- ### Drizzle Schema Definition for PostgreSQL Source: https://context7.com/t3-oss/create-t3-app/llms.txt Defines the database schema using Drizzle ORM for PostgreSQL. It includes table creation helpers and specific column types. This example sets up a 'posts' table with indexing. ```typescript // src/server/db/schema.ts import { sql } from "drizzle-orm"; import { index, pgTableCreator, serial, timestamp, varchar, } from "drizzle-orm/pg-core"; // Prefix tables with app name to avoid conflicts export const createTable = pgTableCreator((name) => `myapp_${name}`); export const posts = createTable( "post", { id: serial("id").primaryKey(), name: varchar("name", { length: 256 }), createdAt: timestamp("created_at", { withTimezone: true }) .default(sql`CURRENT_TIMESTAMP`) .notNull(), updatedAt: timestamp("updated_at", { withTimezone: true }).$onUpdate( () => new Date() ), }, (example) => ({ nameIndex: index("name_idx").on(example.name), }) ); // For SQLite use: // import { sqliteTableCreator, text, integer } from "drizzle-orm/sqlite-core"; // For MySQL use: // import { mysqlTableCreator, varchar, int, timestamp } from "drizzle-orm/mysql-core"; ``` -------------------------------- ### Deploy Project with Vercel CLI (Bash) Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/deployment/vercel.md This command initiates a deployment of your project using the Vercel CLI. It can be used with flags to include environment variables and to skip interactive prompts. For production deployments, use the `--prod` flag. ```bash vercel vercel --env DATABASE_URL=YOUR_DATABASE_URL_HERE --yes vercel --prod ``` -------------------------------- ### Next.js API Endpoint for Fetching User Data Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/usage/trpc.md A standard Next.js API route to fetch a user object from the database using Prisma. It handles GET requests and basic ID validation. This serves as a baseline for comparison with tRPC. ```typescript import { type NextApiRequest, type NextApiResponse } from "next"; import { prisma } from "../../../server/db"; const userByIdHandler = async (req: NextApiRequest, res: NextApiResponse) => { if (req.method !== "GET") { return res.status(405).end(); } const { id } = req.query; if (!id || typeof id !== "string") { return res.status(400).json({ error: "Invalid id" }); } const examples = await prisma.example.findFirst({ where: { id, }, }); res.status(200).json(examples); }; export default userByIdHandler; ``` -------------------------------- ### Deploy to Netlify Production (Bash) Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/deployment/netlify.mdx Deploys your project to Netlify's production environment. The `--build` flag ensures the project is built before deployment, and `--prod` targets the main site URL. ```bash ntl deploy --prod --build ``` -------------------------------- ### Build and Run Docker Image Locally Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/deployment/docker.md Provides the bash commands to build a Docker image for the T3 stack application and run it as a container. It demonstrates how to pass build arguments and environment variables. ```bash docker build -t ct3a-docker --build-arg NEXT_PUBLIC_CLIENTVAR=clientvar . docker run -p 3000:3000 -e DATABASE_URL="database_url_goes_here" ct3a-docker ``` -------------------------------- ### User Query with Protected Procedure Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/usage/_next-auth-pages.mdx An example of a tRPC router that uses the `protectedProcedure` to fetch user data from the database. It requires authentication and uses the user's ID from the session to query the 'users' table in Prisma. ```typescript import { protectedProcedure } from "../trpc"; import { prisma } from "../../server/db"; // Assuming prisma client is exported from here import { router } from "../trpc"; const userRouter = router({ me: protectedProcedure.query(async ({ ctx }) => { const user = await prisma.user.findUnique({ where: { id: ctx.session.user.id, }, }); return user; }), }); ``` -------------------------------- ### Configure Prisma Database Seeding in package.json Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/usage/prisma.md This snippet shows how to configure the `package.json` file to include scripts for seeding the Prisma database. It specifies the command to run the seed script and the path to the seed file, utilizing `tsx` for efficient TypeScript execution. ```json { "scripts": { "db-seed": "NODE_ENV=development prisma db seed" }, "prisma": { "seed": "tsx prisma/seed.ts" } } ``` -------------------------------- ### Set Default Language Redirect (Astro) Source: https://github.com/t3-oss/create-t3-app/blob/main/www/README.md Provides an example of how to modify the redirect path in `src/pages/index.astro` to set a new default language, such as Spanish ('es'), instead of English ('en'). This ensures that users landing on the homepage are directed to the correct language version of the site. ```html ``` -------------------------------- ### Get Server Auth Session Helper Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/usage/_next-auth-pages.mdx A helper function to retrieve the server-side session using NextAuth.js's getServerSession. It abstracts the need to import NextAuth.js options and getServerSession directly, simplifying session access within server-side contexts. ```typescript import { type GetServerSidePropsContext } from "next"; import { getServerSession } from "next-auth"; import { authOptions } from "../pages/api/auth/[...nextauth]"; export const getServerAuthSession = (ctx: { req: GetServerSidePropsContext["req"]; res: GetServerSidePropsContext["res"]; }) => { return getServerSession(ctx.req, ctx.res, authOptions); }; ``` -------------------------------- ### Add Language Directory Structure (Astro) Source: https://github.com/t3-oss/create-t3-app/blob/main/www/README.md Demonstrates how to extend the Astro project's directory structure to include a new language, such as Spanish ('es'), alongside the default English ('en'). This involves creating a new subdirectory for the language within the `src/pages` directory and mirroring the existing page structure. ```diff 📂 src/pages ┣ 📂 en ┃ ┣ 📜 page-1.md ┃ ┣ 📜 page-2.md ┃ ┣ 📜 page-3.astro + ┣ 📂 es + ┃ ┣ 📜 page-1.md + ┃ ┣ 📜 page-2.md + ┃ ┣ 📜 page-3.astro ``` -------------------------------- ### Docker Compose Configuration for T3 App Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/deployment/docker.md Defines the Docker Compose setup for building and running the T3 application. It specifies the build context, Dockerfile, exposed ports, and environment variables. This configuration is used with the `docker compose up --build` command. ```yaml version: "3.9" services: app: platform: "linux/amd64" build: context: . dockerfile: Dockerfile args: NEXT_PUBLIC_CLIENTVAR: "clientvar" working_dir: /app ports: - "3000:3000" image: t3-app environment: - DATABASE_URL=database_url_goes_here ``` -------------------------------- ### Netlify Build Configuration (TOML) Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/deployment/netlify.mdx Defines the build command and publish directory for a Netlify deployment. This file ensures reproducible builds when deploying your project. ```toml [build] command = "next build" publish = ".next" ``` -------------------------------- ### Access Environment Variables in Client Components Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/usage/env-variables.mdx This React TypeScript example illustrates accessing environment variables in a client component. It shows that accessing server-side variables like `env.DATABASE_URL` will cause a runtime error, while client-side variables like `env.NEXT_PUBLIC_WS_KEY` are safe to access. ```typescript import { env } from "../env.js"; // ❌ This will throw a runtime error const dbUrl = env.DATABASE_URL; // ✅ This is fine const wsKey = env.NEXT_PUBLIC_WS_KEY; ``` -------------------------------- ### Retrieve Session Server-Side with `auth` Helper (Next.js) Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/usage/_next-auth-app-router.mdx Demonstrates how to fetch the user's session data on the server in a Next.js application using the `auth` helper function provided by create-t3-app. This is essential for server-side rendering or API routes that require user authentication. ```tsx import { auth } from "~/server/auth"; export default async function Home() { const session = await auth(); // ... rest of your component logic } ``` -------------------------------- ### Add Server-Side Environment Variable (Twitter API Token) Source: https://github.com/t3-oss/create-t3-app/blob/main/www/src/pages/en/usage/env-variables.mdx This example demonstrates adding a new server-side environment variable, `TWITTER_API_TOKEN`. It includes the steps for updating the `.env` file, defining the validation schema in `env.js` using `zod`, and mapping it in the `runtimeEnv` configuration. ```typescript import { createEnv } from "@t3-oss/env-nextjs"; import { z } from "zod"; export const env = createEnv({ server: { TWITTER_API_TOKEN: z.string(), }, // ... runtimeEnv: { // ... TWITTER_API_TOKEN: process.env.TWITTER_API_TOKEN, }, }); ```