├── .npmrc ├── src ├── styles │ └── globals.css ├── pages │ ├── api │ │ ├── auth │ │ │ └── [...nextauth].ts │ │ └── trpc │ │ │ └── [trpc].ts │ ├── _app.tsx │ └── index.tsx ├── server │ ├── api │ │ ├── root.ts │ │ ├── routers │ │ │ └── example.ts │ │ └── trpc.ts │ ├── db.ts │ └── auth.ts ├── db │ ├── schema.ts │ └── auth.ts ├── utils │ └── api.ts └── env.js ├── postcss.config.cjs ├── prettier.config.mjs ├── tailwind.config.ts ├── next.config.js ├── drizzle.config.ts ├── .gitignore ├── tsconfig.json ├── .env.example ├── .eslintrc.cjs ├── README.md ├── package.json └── public └── favicon.ico /.npmrc: -------------------------------------------------------------------------------- 1 | strict-peer-dependencies=false -------------------------------------------------------------------------------- /src/styles/globals.css: -------------------------------------------------------------------------------- 1 | @tailwind base; 2 | @tailwind components; 3 | @tailwind utilities; 4 | -------------------------------------------------------------------------------- /postcss.config.cjs: -------------------------------------------------------------------------------- 1 | const config = { 2 | plugins: { 3 | tailwindcss: {}, 4 | autoprefixer: {}, 5 | }, 6 | }; 7 | 8 | module.exports = config; 9 | -------------------------------------------------------------------------------- /src/pages/api/auth/[...nextauth].ts: -------------------------------------------------------------------------------- 1 | import NextAuth from "next-auth"; 2 | import { authOptions } from "@/server/auth"; 3 | 4 | export default NextAuth(authOptions); 5 | -------------------------------------------------------------------------------- /prettier.config.mjs: -------------------------------------------------------------------------------- 1 | /** @type {import('prettier').Config & import('prettier-plugin-tailwindcss').options} */ 2 | const config = { 3 | plugins: ["prettier-plugin-tailwindcss"], 4 | }; 5 | 6 | export default config; 7 | -------------------------------------------------------------------------------- /tailwind.config.ts: -------------------------------------------------------------------------------- 1 | import { type Config } from "tailwindcss"; 2 | 3 | export default { 4 | content: ["./src/**/*.tsx"], 5 | theme: { 6 | extend: {}, 7 | }, 8 | plugins: [], 9 | } satisfies Config; 10 | -------------------------------------------------------------------------------- /next.config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. This is especially useful 3 | * for Docker builds. 4 | */ 5 | await import("./src/env.js"); 6 | 7 | /** @type {import("next").NextConfig} */ 8 | const config = {}; 9 | 10 | export default config; 11 | -------------------------------------------------------------------------------- /src/server/api/root.ts: -------------------------------------------------------------------------------- 1 | import { createTRPCRouter } from "@/server/api/trpc"; 2 | import { exampleRouter } from "@/server/api/routers/example"; 3 | 4 | /** 5 | * This is the primary router for your server. 6 | * 7 | * All routers added in /api/routers should be manually added here. 8 | */ 9 | export const appRouter = createTRPCRouter({ 10 | example: exampleRouter, 11 | }); 12 | 13 | // export type definition of API 14 | export type AppRouter = typeof appRouter; 15 | -------------------------------------------------------------------------------- /drizzle.config.ts: -------------------------------------------------------------------------------- 1 | // drizzle.config.ts 2 | import type { Config } from "drizzle-kit"; 3 | import "dotenv/config"; 4 | 5 | import { env } from "@/env.js"; 6 | 7 | export default { 8 | driver: "mysql2", 9 | schema: ["./src/db/auth.ts", "./src/db/schema.ts"], 10 | dbCredentials: { 11 | host: env.DB_HOST, 12 | user: env.DB_USERNAME, 13 | password: env.DB_PASSWORD, 14 | database: env.DB_NAME, 15 | }, 16 | verbose: true, 17 | strict: true, 18 | tablesFilter: ["t3-drzl_*"], 19 | } satisfies Config; 20 | -------------------------------------------------------------------------------- /src/pages/_app.tsx: -------------------------------------------------------------------------------- 1 | import { type AppType } from "next/app"; 2 | import { type Session } from "next-auth"; 3 | import { SessionProvider } from "next-auth/react"; 4 | 5 | import { api } from "@/utils/api"; 6 | 7 | import "@/styles/globals.css"; 8 | 9 | const MyApp: AppType<{ session: Session | null }> = ({ 10 | Component, 11 | pageProps: { session, ...pageProps }, 12 | }) => { 13 | return ( 14 | 15 | 16 | 17 | ); 18 | }; 19 | 20 | export default api.withTRPC(MyApp); 21 | -------------------------------------------------------------------------------- /src/db/schema.ts: -------------------------------------------------------------------------------- 1 | import { 2 | mysqlTableCreator, 3 | serial, 4 | timestamp, 5 | uniqueIndex, 6 | varchar, 7 | } from "drizzle-orm/mysql-core"; 8 | 9 | const mysqlTable = mysqlTableCreator((name) => `project1_${name}`); 10 | 11 | export const example = mysqlTable( 12 | "example", 13 | { 14 | id: serial("id").primaryKey(), 15 | name: varchar("name", { length: 256 }), 16 | createdAt: timestamp("created_at").defaultNow().notNull(), 17 | updatedAt: timestamp("updatedAt").onUpdateNow(), 18 | }, 19 | (example) => ({ 20 | nameIndex: uniqueIndex("name_idx").on(example.name), 21 | }), 22 | ); 23 | -------------------------------------------------------------------------------- /src/pages/api/trpc/[trpc].ts: -------------------------------------------------------------------------------- 1 | import { createNextApiHandler } from "@trpc/server/adapters/next"; 2 | 3 | import { env } from "@/env.js"; 4 | import { createTRPCContext } from "@/server/api/trpc"; 5 | import { appRouter } from "@/server/api/root"; 6 | 7 | // export API handler 8 | export default createNextApiHandler({ 9 | router: appRouter, 10 | createContext: createTRPCContext, 11 | onError: 12 | env.NODE_ENV === "development" 13 | ? ({ path, error }) => { 14 | console.error( 15 | `❌ tRPC failed on ${path ?? ""}: ${error.message}`, 16 | ); 17 | } 18 | : undefined, 19 | }); 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # next.js 12 | /.next/ 13 | /out/ 14 | next-env.d.ts 15 | 16 | # production 17 | /build 18 | 19 | # misc 20 | .DS_Store 21 | *.pem 22 | 23 | # debug 24 | npm-debug.log* 25 | yarn-debug.log* 26 | yarn-error.log* 27 | .pnpm-debug.log* 28 | 29 | # local env files 30 | # do not commit any .env files to git, except for the .env.example file. https://create.t3.gg/en/usage/env-variables#using-environment-variables 31 | .env 32 | .env*.local 33 | 34 | # vercel 35 | .vercel 36 | 37 | # typescript 38 | *.tsbuildinfo 39 | -------------------------------------------------------------------------------- /src/server/api/routers/example.ts: -------------------------------------------------------------------------------- 1 | import { z } from "zod"; 2 | 3 | import { 4 | createTRPCRouter, 5 | publicProcedure, 6 | protectedProcedure, 7 | } from "@/server/api/trpc"; 8 | 9 | import { example } from "@/db/schema"; 10 | 11 | export const exampleRouter = createTRPCRouter({ 12 | hello: publicProcedure 13 | .input(z.object({ text: z.string() })) 14 | .query(({ input }) => { 15 | return { 16 | greeting: `Hello ${input.text}`, 17 | }; 18 | }), 19 | 20 | getExample: publicProcedure.query(({ ctx }) => { 21 | return ctx.db.select().from(example); 22 | }), 23 | 24 | getSecretMessage: protectedProcedure.query(() => { 25 | return "you can now see this secret message!"; 26 | }), 27 | }); 28 | -------------------------------------------------------------------------------- /src/server/db.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable @typescript-eslint/no-unsafe-assignment */ 2 | import { drizzle } from "drizzle-orm/mysql2"; 3 | import mysql, { type Pool } from "mysql2/promise"; 4 | 5 | import * as auth from "../db/auth"; 6 | import * as base from "../db/schema"; 7 | import { env } from "@/env.js"; 8 | 9 | const globalForMySQL = globalThis as unknown as { poolConnection: Pool }; 10 | 11 | const poolConnection = 12 | globalForMySQL.poolConnection || 13 | mysql.createPool({ 14 | host: env.DB_HOST, 15 | user: env.DB_USERNAME, 16 | password: env.DB_PASSWORD, 17 | database: env.DB_NAME, 18 | }); 19 | 20 | if (env.NODE_ENV !== "production") 21 | globalForMySQL.poolConnection = poolConnection; 22 | 23 | export const db = drizzle(poolConnection, { 24 | logger: env.NODE_ENV === "development" ? true : false, 25 | mode: "default", 26 | schema: { ...auth, ...base }, 27 | }); 28 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Base Options: */ 4 | "esModuleInterop": true, 5 | "skipLibCheck": true, 6 | "target": "es2022", 7 | "allowJs": true, 8 | "resolveJsonModule": true, 9 | "moduleDetection": "force", 10 | "isolatedModules": true, 11 | 12 | /* Strictness */ 13 | "strict": true, 14 | "noUncheckedIndexedAccess": true, 15 | "checkJs": true, 16 | 17 | /* Bundled projects */ 18 | "lib": ["dom", "dom.iterable", "ES2022"], 19 | "noEmit": true, 20 | "module": "ESNext", 21 | "moduleResolution": "Bundler", 22 | "jsx": "preserve", 23 | "plugins": [{ "name": "next" }], 24 | "incremental": true, 25 | 26 | /* Path Aliases */ 27 | "baseUrl": ".", 28 | "paths": { 29 | "@/*": ["./src/*"] 30 | } 31 | }, 32 | "include": [ 33 | ".eslintrc.cjs", 34 | "next-env.d.ts", 35 | "**/*.ts", 36 | "**/*.tsx", 37 | "**/*.cjs", 38 | "**/*.js", 39 | ".next/types/**/*.ts" 40 | ], 41 | "exclude": ["node_modules"] 42 | } 43 | -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | # Since the ".env" file is gitignored, you can use the ".env.example" file to 2 | # build a new ".env" file when you clone the repo. Keep this file up-to-date 3 | # when you add new variables to `.env`. 4 | 5 | # This file will be committed to version control, so make sure not to have any 6 | # secrets in it. If you are cloning this repo, create a copy of this file named 7 | # ".env" and populate it with your secrets. 8 | 9 | # When adding additional environment variables, the schema in "/src/env.mjs" 10 | # should be updated accordingly. 11 | 12 | # development | test | production 13 | NODE_ENV="development" 14 | 15 | # Drizzle Credentials 16 | DB_HOST="localhost" 17 | DB_USERNAME="user" 18 | DB_PASSWORD="verysecretpassword" 19 | DB_NAME="mydb" 20 | 21 | 22 | # Next Auth 23 | # You can generate a new secret on the command line with: 24 | # openssl rand -base64 32 25 | # https://next-auth.js.org/configuration/options#secret 26 | NEXTAUTH_SECRET="" 27 | NEXTAUTH_URL="http://localhost:3000" 28 | 29 | # Next Auth Discord Provider 30 | DISCORD_CLIENT_ID="" 31 | DISCORD_CLIENT_SECRET="" 32 | -------------------------------------------------------------------------------- /.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | // eslint-disable-next-line @typescript-eslint/no-var-requires 2 | /** @type {import("eslint").Linter.Config} */ 3 | 4 | const config = { 5 | parser: "@typescript-eslint/parser", 6 | parserOptions: { 7 | project: true, 8 | }, 9 | plugins: ["@typescript-eslint"], 10 | extends: [ 11 | "plugin:@next/next/recommended", 12 | "plugin:@typescript-eslint/recommended-type-checked", 13 | "plugin:@typescript-eslint/stylistic-type-checked", 14 | ], 15 | rules: { 16 | "@typescript-eslint/array-type": "off", 17 | "@typescript-eslint/consistent-type-definitions": "off", 18 | "@typescript-eslint/consistent-type-imports": [ 19 | "warn", 20 | { 21 | prefer: "type-imports", 22 | fixStyle: "inline-type-imports", 23 | }, 24 | ], 25 | "@typescript-eslint/no-unused-vars": ["warn", { argsIgnorePattern: "^_" }], 26 | "@typescript-eslint/require-await": "off", 27 | "@typescript-eslint/no-misused-promises": [ 28 | "error", 29 | { 30 | checksVoidReturn: { attributes: false }, 31 | }, 32 | ], 33 | }, 34 | }; 35 | 36 | module.exports = config; 37 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Create T3 App 2 | 3 | This is a [T3 Stack](https://create.t3.gg/) project bootstrapped with `create-t3-app` using [Drizzle-orm](https://github.com/drizzle-team/drizzle-orm). 4 | 5 | ## Get started 6 | 7 | 1. Copy and fill secrets 8 | 9 | ```bash 10 | pnpm i 11 | cp .env.example .env 12 | ``` 13 | 14 | 2. Push your schema changes 15 | 16 | ```bash 17 | pnpm db:push 18 | ``` 19 | 20 | 3. Start developing 21 | 22 | ```bash 23 | pnpm dev 24 | ``` 25 | 26 | ## What's next? How do I make an app with this? 27 | 28 | We try to keep this project as simple as possible, so you can start with just the scaffolding we set up for you, and add additional things later when they become necessary. 29 | 30 | If you are not familiar with the different technologies used in this project, please refer to the respective docs. If you still are in the wind, please join our [Discord](https://t3.gg/discord) and ask for help. 31 | 32 | - [Next.js](https://nextjs.org) 33 | - [NextAuth.js](https://next-auth.js.org) 34 | - [Drizzle-orm](https://github.com/drizzle-team/drizzle-orm) 35 | - [Tailwind CSS](https://tailwindcss.com) 36 | - [tRPC](https://trpc.io) 37 | 38 | ## Learn More 39 | 40 | To learn more about the [T3 Stack](https://create.t3.gg/), take a look at the following resources: 41 | 42 | - [Documentation](https://create.t3.gg/) 43 | - [Learn the T3 Stack](https://create.t3.gg/en/faq#what-learning-resources-are-currently-available) — Check out these awesome tutorials 44 | 45 | You can check out the [create-t3-app GitHub repository](https://github.com/t3-oss/create-t3-app) — your feedback and contributions are welcome! 46 | 47 | ## How do I deploy this? 48 | 49 | Follow our deployment guides for [Vercel](https://create.t3.gg/en/deployment/vercel), [Netlify](https://create.t3.gg/en/deployment/netlify) and [Docker](https://create.t3.gg/en/deployment/docker) for more information. 50 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "my-t3-drizzle", 3 | "version": "0.1.0", 4 | "private": true, 5 | "type": "module", 6 | "scripts": { 7 | "build": "next build", 8 | "dev": "next dev", 9 | "lint": "next lint", 10 | "start": "next start", 11 | "format:write": "prettier --write './src/**/*.{js,json,ts,tsx,css,md,mdx}' --check", 12 | "format:check": "prettier --check './src/**/*.{ts,tsx,mdx}' --check", 13 | "db:push": "dotenv drizzle-kit push:mysql --config drizzle.config.ts", 14 | "db:studio": "dotenv drizzle-kit studio", 15 | "db:generate": "dotenv drizzle-kit generate:mysql --config drizzle.config.ts" 16 | }, 17 | "dependencies": { 18 | "@auth/drizzle-adapter": "^0.3.6", 19 | "@paralleldrive/cuid2": "^2.2.1", 20 | "@t3-oss/env-nextjs": "^0.7.1", 21 | "@tanstack/react-query": "^4.36.1", 22 | "@trpc/client": "^10.43.6", 23 | "@trpc/next": "^10.43.6", 24 | "@trpc/react-query": "^10.43.6", 25 | "@trpc/server": "^10.43.6", 26 | "drizzle-orm": "^0.29.1", 27 | "next": "^14.1.1", 28 | "next-auth": "^4.24.5", 29 | "react": "18.2.0", 30 | "react-dom": "18.2.0", 31 | "superjson": "^2.2.1", 32 | "zod": "^3.22.4" 33 | }, 34 | "devDependencies": { 35 | "@next/eslint-plugin-next": "^14.0.3", 36 | "@types/eslint": "^8.44.7", 37 | "@types/node": "^18.17.0", 38 | "@types/react": "^18.2.37", 39 | "@types/react-dom": "^18.2.15", 40 | "@typescript-eslint/eslint-plugin": "^6.11.0", 41 | "@typescript-eslint/parser": "^6.11.0", 42 | "autoprefixer": "^10.4.14", 43 | "drizzle-kit": "^0.20.2", 44 | "eslint": "^8.54.0", 45 | "dotenv-cli": "^7.3.0", 46 | "eslint-config-next": "^13.5.4", 47 | "mysql2": "^3.9.8", 48 | "postcss": "^8.4.27", 49 | "prettier": "^3.1.0", 50 | "prettier-plugin-tailwindcss": "^0.5.7", 51 | "tailwindcss": "^3.3.5", 52 | "typescript": "^5.1.6" 53 | }, 54 | "ct3aMetadata": { 55 | "initVersion": "7.24.1" 56 | }, 57 | "packageManager": "pnpm@8.9.0" 58 | } 59 | -------------------------------------------------------------------------------- /src/utils/api.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This is the client-side entrypoint for your tRPC API. It is used to create the `api` object which 3 | * contains the Next.js App-wrapper, as well as your type-safe React Query hooks. 4 | * 5 | * We also create a few inference helpers for input and output types. 6 | */ 7 | import { httpBatchLink, loggerLink } from "@trpc/client"; 8 | import { createTRPCNext } from "@trpc/next"; 9 | import { type inferRouterInputs, type inferRouterOutputs } from "@trpc/server"; 10 | import superjson from "superjson"; 11 | 12 | import { type AppRouter } from "@/server/api/root"; 13 | 14 | function getBaseUrl() { 15 | if (typeof window !== "undefined") return ""; 16 | if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`; 17 | return `http://localhost:${process.env.PORT ?? 3000}`; 18 | } 19 | 20 | /** A set of type-safe react-query hooks for your tRPC API. */ 21 | export const api = createTRPCNext({ 22 | config() { 23 | return { 24 | /** 25 | * Transformer used for data de-serialization from the server. 26 | * 27 | * @see https://trpc.io/docs/data-transformers 28 | */ 29 | transformer: superjson, 30 | 31 | /** 32 | * Links used to determine request flow from client to server. 33 | * 34 | * @see https://trpc.io/docs/links 35 | */ 36 | links: [ 37 | loggerLink({ 38 | enabled: (opts) => 39 | process.env.NODE_ENV === "development" || 40 | (opts.direction === "down" && opts.result instanceof Error), 41 | }), 42 | httpBatchLink({ 43 | url: `${getBaseUrl()}/api/trpc`, 44 | }), 45 | ], 46 | }; 47 | }, 48 | /** 49 | * Whether tRPC should await queries when server rendering pages. 50 | * 51 | * @see https://trpc.io/docs/nextjs#ssr-boolean-default-false 52 | */ 53 | ssr: false, 54 | }); 55 | 56 | /** 57 | * Inference helper for inputs. 58 | * 59 | * @example type HelloInput = RouterInputs['example']['hello'] 60 | */ 61 | export type RouterInputs = inferRouterInputs; 62 | 63 | /** 64 | * Inference helper for outputs. 65 | * 66 | * @example type HelloOutput = RouterOutputs['example']['hello'] 67 | */ 68 | export type RouterOutputs = inferRouterOutputs; 69 | -------------------------------------------------------------------------------- /src/server/auth.ts: -------------------------------------------------------------------------------- 1 | import { type GetServerSidePropsContext } from "next"; 2 | import { 3 | getServerSession, 4 | type NextAuthOptions, 5 | type DefaultSession, 6 | } from "next-auth"; 7 | import DiscordProvider from "next-auth/providers/discord"; 8 | import { env } from "@/env.js"; 9 | import { db } from "@/server/db"; 10 | // import { DrizzleAdapter } from "./adapters/drizzleAdapter"; 11 | import { DrizzleAdapter } from "@auth/drizzle-adapter"; 12 | 13 | import { mysqlTable } from "@/db/auth"; 14 | 15 | /** 16 | * Module augmentation for `next-auth` types. Allows us to add custom properties to the `session` 17 | * object and keep type safety. 18 | * 19 | * @see https://next-auth.js.org/getting-started/typescript#module-augmentation 20 | */ 21 | declare module "next-auth" { 22 | interface Session extends DefaultSession { 23 | user: { 24 | id: string; 25 | // ...other properties 26 | // role: UserRole; 27 | } & DefaultSession["user"]; 28 | } 29 | 30 | // interface User { 31 | // // ...other properties 32 | // // role: UserRole; 33 | // } 34 | } 35 | 36 | /** 37 | * Options for NextAuth.js used to configure adapters, providers, callbacks, etc. 38 | * 39 | * @see https://next-auth.js.org/configuration/options 40 | */ 41 | export const authOptions: NextAuthOptions = { 42 | callbacks: { 43 | session: ({ session, user }) => ({ 44 | ...session, 45 | user: { 46 | ...session.user, 47 | id: user.id, 48 | }, 49 | }), 50 | }, 51 | adapter: DrizzleAdapter(db, mysqlTable), 52 | providers: [ 53 | DiscordProvider({ 54 | clientId: env.DISCORD_CLIENT_ID, 55 | clientSecret: env.DISCORD_CLIENT_SECRET, 56 | }), 57 | /** 58 | * ...add more providers here. 59 | * 60 | * Most other providers require a bit more work than the Discord provider. For example, the 61 | * GitHub provider requires you to add the `refresh_token_expires_in` field to the Account 62 | * model. Refer to the NextAuth.js docs for the provider you want to use. Example: 63 | * 64 | * @see https://next-auth.js.org/providers/github 65 | */ 66 | ], 67 | }; 68 | 69 | /** 70 | * Wrapper for `getServerSession` so that you don't need to import the `authOptions` in every file. 71 | * 72 | * @see https://next-auth.js.org/configuration/nextjs 73 | */ 74 | export const getServerAuthSession = (ctx: { 75 | req: GetServerSidePropsContext["req"]; 76 | res: GetServerSidePropsContext["res"]; 77 | }) => { 78 | return getServerSession(ctx.req, ctx.res, authOptions); 79 | }; 80 | -------------------------------------------------------------------------------- /src/env.js: -------------------------------------------------------------------------------- 1 | import { createEnv } from "@t3-oss/env-nextjs"; 2 | import { z } from "zod"; 3 | 4 | export const env = createEnv({ 5 | /** 6 | * Specify your server-side environment variables schema here. This way you can ensure the app 7 | * isn't built with invalid env vars. 8 | */ 9 | server: { 10 | DB_HOST: z.string().min(1), 11 | DB_USERNAME: z.string().min(1), 12 | DB_PASSWORD: z.string().min(1), 13 | DB_NAME: z.string().min(1), 14 | NODE_ENV: z 15 | .enum(["development", "test", "production"]) 16 | .default("development"), 17 | NEXTAUTH_SECRET: 18 | process.env.NODE_ENV === "production" 19 | ? z.string() 20 | : z.string().optional(), 21 | NEXTAUTH_URL: z.preprocess( 22 | // This makes Vercel deployments not fail if you don't set NEXTAUTH_URL 23 | // Since NextAuth.js automatically uses the VERCEL_URL if present. 24 | (str) => process.env.VERCEL_URL ?? str, 25 | // VERCEL_URL doesn't include `https` so it cant be validated as a URL 26 | process.env.VERCEL ? z.string() : z.string().url(), 27 | ), 28 | // Add ` on ID and SECRET if you want to make sure they're not empty 29 | DISCORD_CLIENT_ID: z.string(), 30 | DISCORD_CLIENT_SECRET: z.string(), 31 | }, 32 | 33 | /** 34 | * Specify your client-side environment variables schema here. This way you can ensure the app 35 | * isn't built with invalid env vars. To expose them to the client, prefix them with 36 | * `NEXT_PUBLIC_`. 37 | */ 38 | client: { 39 | // NEXT_PUBLIC_CLIENTVAR: z.string(), 40 | }, 41 | 42 | /** 43 | * You can't destruct `process.env` as a regular object in the Next.js edge runtimes (e.g. 44 | * middlewares) or client-side so we need to destruct manually. 45 | */ 46 | runtimeEnv: { 47 | DB_HOST: process.env.DB_HOST, 48 | DB_USERNAME: process.env.DB_USERNAME, 49 | DB_PASSWORD: process.env.DB_PASSWORD, 50 | DB_NAME: process.env.DB_NAME, 51 | NODE_ENV: process.env.NODE_ENV, 52 | NEXTAUTH_SECRET: process.env.NEXTAUTH_SECRET, 53 | NEXTAUTH_URL: process.env.NEXTAUTH_URL, 54 | DISCORD_CLIENT_ID: process.env.DISCORD_CLIENT_ID, 55 | DISCORD_CLIENT_SECRET: process.env.DISCORD_CLIENT_SECRET, 56 | }, 57 | /** 58 | * Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. This is especially 59 | * useful for Docker builds. 60 | */ 61 | skipValidation: !!process.env.SKIP_ENV_VALIDATION, 62 | /** 63 | * Makes it so that empty strings are treated as undefined. 64 | * `SOME_VAR: z.string()` and `SOME_VAR=''` will throw an error. 65 | */ 66 | emptyStringAsUndefined: true, 67 | }); 68 | -------------------------------------------------------------------------------- /src/db/auth.ts: -------------------------------------------------------------------------------- 1 | import { relations, sql } from "drizzle-orm"; 2 | import { 3 | index, 4 | int, 5 | mysqlTableCreator, 6 | primaryKey, 7 | text, 8 | timestamp, 9 | varchar, 10 | } from "drizzle-orm/mysql-core"; 11 | import { type AdapterAccount } from "next-auth/adapters"; 12 | 13 | /** 14 | * This is an example of how to use the multi-project schema feature of Drizzle ORM. Use the same 15 | * database instance for multiple projects. 16 | * 17 | * @see https://orm.drizzle.team/docs/goodies#multi-project-schema 18 | */ 19 | export const mysqlTable = mysqlTableCreator((name) => `t3-drzl_${name}`); 20 | 21 | export const users = mysqlTable("user", { 22 | id: varchar("id", { length: 255 }).notNull().primaryKey(), 23 | name: varchar("name", { length: 255 }), 24 | email: varchar("email", { length: 255 }).notNull(), 25 | emailVerified: timestamp("emailVerified", { 26 | mode: "date", 27 | fsp: 3, 28 | }).default(sql`CURRENT_TIMESTAMP(3)`), 29 | image: varchar("image", { length: 255 }), 30 | }); 31 | 32 | export const usersRelations = relations(users, ({ many }) => ({ 33 | accounts: many(accounts), 34 | sessions: many(sessions), 35 | })); 36 | 37 | export const accounts = mysqlTable( 38 | "account", 39 | { 40 | userId: varchar("userId", { length: 255 }).notNull(), 41 | type: varchar("type", { length: 255 }) 42 | .$type() 43 | .notNull(), 44 | provider: varchar("provider", { length: 255 }).notNull(), 45 | providerAccountId: varchar("providerAccountId", { length: 255 }).notNull(), 46 | refresh_token: text("refresh_token"), 47 | access_token: text("access_token"), 48 | expires_at: int("expires_at"), 49 | token_type: varchar("token_type", { length: 255 }), 50 | scope: varchar("scope", { length: 255 }), 51 | id_token: text("id_token"), 52 | session_state: varchar("session_state", { length: 255 }), 53 | }, 54 | (account) => ({ 55 | compoundKey: primaryKey(account.provider, account.providerAccountId), 56 | userIdIdx: index("userId_idx").on(account.userId), 57 | }), 58 | ); 59 | 60 | export const accountsRelations = relations(accounts, ({ one }) => ({ 61 | user: one(users, { fields: [accounts.userId], references: [users.id] }), 62 | })); 63 | 64 | export const sessions = mysqlTable( 65 | "session", 66 | { 67 | sessionToken: varchar("sessionToken", { length: 255 }) 68 | .notNull() 69 | .primaryKey(), 70 | userId: varchar("userId", { length: 255 }).notNull(), 71 | expires: timestamp("expires", { mode: "date" }).notNull(), 72 | }, 73 | (session) => ({ 74 | userIdIdx: index("userId_idx").on(session.userId), 75 | }), 76 | ); 77 | 78 | export const sessionsRelations = relations(sessions, ({ one }) => ({ 79 | user: one(users, { fields: [sessions.userId], references: [users.id] }), 80 | })); 81 | 82 | export const verificationTokens = mysqlTable( 83 | "verificationToken", 84 | { 85 | identifier: varchar("identifier", { length: 255 }).notNull(), 86 | token: varchar("token", { length: 255 }).notNull(), 87 | expires: timestamp("expires", { mode: "date" }).notNull(), 88 | }, 89 | (vt) => ({ 90 | compoundKey: primaryKey(vt.identifier, vt.token), 91 | }), 92 | ); 93 | -------------------------------------------------------------------------------- /src/pages/index.tsx: -------------------------------------------------------------------------------- 1 | import { type NextPage } from "next"; 2 | import Head from "next/head"; 3 | import Link from "next/link"; 4 | import { signIn, signOut, useSession } from "next-auth/react"; 5 | 6 | import { api } from "@/utils/api"; 7 | 8 | const Home: NextPage = () => { 9 | const hello = api.example.hello.useQuery({ text: "from tRPC" }); 10 | const example = api.example.getExample.useQuery(); 11 | 12 | console.log("example:", example.data); 13 | return ( 14 | <> 15 | 16 | Create T3 App 17 | 18 | 19 | 20 | 21 |
22 |
23 |

24 | Create T3 App 25 |

26 |
27 | 32 |

First Steps →

33 |
34 | Just the basics - Everything you need to know to set up your 35 | database and authentication. 36 |
37 | 38 | 43 |

Documentation →

44 |
45 | Learn more about Create T3 App, the libraries it uses, and how 46 | to deploy it. 47 |
48 | 49 |
50 |
51 |

52 | {hello.data ? hello.data.greeting : "Loading tRPC query..."} 53 |

54 | 55 |
56 |
57 |
58 | 59 | ); 60 | }; 61 | 62 | export default Home; 63 | 64 | const AuthShowcase: React.FC = () => { 65 | const { data: sessionData } = useSession(); 66 | 67 | const { data: secretMessage } = api.example.getSecretMessage.useQuery( 68 | undefined, // no input 69 | { enabled: sessionData?.user !== undefined }, 70 | ); 71 | 72 | return ( 73 |
74 |

75 | {sessionData && Logged in as {sessionData.user?.name}} 76 | {secretMessage && - {secretMessage}} 77 |

78 | 84 |
85 | ); 86 | }; 87 | -------------------------------------------------------------------------------- /src/server/api/trpc.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * YOU PROBABLY DON'T NEED TO EDIT THIS FILE, UNLESS: 3 | * 1. You want to modify request context (see Part 1). 4 | * 2. You want to create a new middleware or type of procedure (see Part 3). 5 | * 6 | * TL;DR - This is where all the tRPC server stuff is created and plugged in. The pieces you will 7 | * need to use are documented accordingly near the end. 8 | */ 9 | 10 | /** 11 | * 1. CONTEXT 12 | * 13 | * This section defines the "contexts" that are available in the backend API. 14 | * 15 | * These allow you to access things when processing a request, like the database, the session, etc. 16 | */ 17 | import { type CreateNextContextOptions } from "@trpc/server/adapters/next"; 18 | import { type Session } from "next-auth"; 19 | 20 | import { getServerAuthSession } from "@/server/auth"; 21 | import { db } from "@/server/db"; 22 | 23 | import { initTRPC, TRPCError } from "@trpc/server"; 24 | import superjson from "superjson"; 25 | import { ZodError } from "zod"; 26 | 27 | type CreateContextOptions = { 28 | session: Session | null; 29 | }; 30 | 31 | /** 32 | * This helper generates the "internals" for a tRPC context. If you need to use it, you can export 33 | * it from here. 34 | * 35 | * Examples of things you may need it for: 36 | * - testing, so we don't have to mock Next.js' req/res 37 | * - tRPC's `createSSGHelpers`, where we don't have req/res 38 | * 39 | * @see https://create.t3.gg/en/usage/trpc#-serverapitrpcts 40 | */ 41 | const createInnerTRPCContext = (opts: CreateContextOptions) => { 42 | return { 43 | session: opts.session, 44 | db, 45 | }; 46 | }; 47 | 48 | /** 49 | * This is the actual context you will use in your router. It will be used to process every request 50 | * that goes through your tRPC endpoint. 51 | * 52 | * @see https://trpc.io/docs/context 53 | */ 54 | export const createTRPCContext = async (opts: CreateNextContextOptions) => { 55 | const { req, res } = opts; 56 | 57 | // Get the session from the server using the getServerSession wrapper function 58 | const session = await getServerAuthSession({ req, res }); 59 | 60 | return createInnerTRPCContext({ 61 | session, 62 | }); 63 | }; 64 | 65 | /** 66 | * 2. INITIALIZATION 67 | * 68 | * This is where the tRPC API is initialized, connecting the context and transformer. We also parse 69 | * ZodErrors so that you get typesafety on the frontend if your procedure fails due to validation 70 | * errors on the backend. 71 | */ 72 | 73 | const t = initTRPC.context().create({ 74 | transformer: superjson, 75 | errorFormatter({ shape, error }) { 76 | return { 77 | ...shape, 78 | data: { 79 | ...shape.data, 80 | zodError: 81 | error.cause instanceof ZodError ? error.cause.flatten() : null, 82 | }, 83 | }; 84 | }, 85 | }); 86 | 87 | /** 88 | * 3. ROUTER & PROCEDURE (THE IMPORTANT BIT) 89 | * 90 | * These are the pieces you use to build your tRPC API. You should import these a lot in the 91 | * "/src/server/api/routers" directory. 92 | */ 93 | 94 | /** 95 | * This is how you create new routers and sub-routers in your tRPC API. 96 | * 97 | * @see https://trpc.io/docs/router 98 | */ 99 | export const createTRPCRouter = t.router; 100 | 101 | /** 102 | * Public (unauthenticated) procedure 103 | * 104 | * This is the base piece you use to build new queries and mutations on your tRPC API. It does not 105 | * guarantee that a user querying is authorized, but you can still access user session data if they 106 | * are logged in. 107 | */ 108 | export const publicProcedure = t.procedure; 109 | 110 | /** Reusable middleware that enforces users are logged in before running the procedure. */ 111 | const enforceUserIsAuthed = t.middleware(({ ctx, next }) => { 112 | if (!ctx.session?.user) { 113 | throw new TRPCError({ code: "UNAUTHORIZED" }); 114 | } 115 | return next({ 116 | ctx: { 117 | // infers the `session` as non-nullable 118 | session: { ...ctx.session, user: ctx.session.user }, 119 | }, 120 | }); 121 | }); 122 | 123 | /** 124 | * Protected (authenticated) procedure 125 | * 126 | * If you want a query or mutation to ONLY be accessible to logged in users, use this. It verifies 127 | * the session is valid and guarantees `ctx.session.user` is not null. 128 | * 129 | * @see https://trpc.io/docs/procedures 130 | */ 131 | export const protectedProcedure = t.procedure.use(enforceUserIsAuthed); 132 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- 1 |  h6  (�00 h&�(  ���L���A���$������������5����������A����������������������b�������������������� 2 | �����������������������}���0����������b�����������������l����������_�������2����������_���X���\�������������������������R������m�����������������������L�������������������G���N������������������������������Q�������������A���O���������������������������������������|������( @ ������B���h���n���R������f�����������;��� ���������������������������������%��������������J����������������������������������������������O��������������J�������������������������f���_����������������������>��������������J������������������)��� ��������������������������������J������������������"������������������_��������������J���{����������=�������������������������J���{���5�����������������������������J��������������������������J�����������������������������J���i�������������������������J���%���������������3��������������J���4���9������U�����������������������������J���S�����������5���*���������������������������������J���������������������1���8������������������������J��� ������������������,�����������������J��� 3 | ������������������(��������������J��� �������������������$������<���<�������������������������!�������������������������V���a���a���a���a���a���a���a���a���a���a���a���a���a���a���a���a���a���a���+���������������������������������������������������������������������������������������������������������-�������������������������������������������������������������������������������������������������������������(�������������������������[���h���h���h���h���h���h���h���h���h���h���h���h���h���h���h���h���h���h���h���h���M��������������� 4 | (0` ������ ������"���%���$������������ ���J���J���J���;������ ���g��������������������������������B��� ���+������������������������b�����������������������������������������������������.������������������������������������������������������������������������������������;������.��������������������������������������������������������������������������������������������O������.���������������������������������������������������O���$������!���2������������������������������#���.����������������������:�����������������������j������!����������������������������.��������������������������������������������N�������������������������G���.����������������������)�������������������x������)�������������������������.����������������������y��������������� ����������������������&���.���������������������� 5 | ���{�������������!�������������������J���.���������������������� 6 | ���y���A����������������������_���.�����������������������������������������e���.�����������������������������������������]���.����������������������%�������������������G���.��������������������������������������������!���.����������������������5�������������������������.��������������������������������������������5���.����������������������������&������ ���,��������������������������.�������������������������C�����������8������ ���������������������������������.����������������������L�������������������"������y�����������������������8������.������������������������������������������������������������������������*���.����������������������$��������������������������.������u���������.�������������������������&�����������������������������������.���������������������������������������������������.����������������������*��������������������������&���.�������������������������-��������������������������������d���d���d���O��� 7 | ���%�����������������������������1��������������������������������4����������������������������� ������!���!���!���!���!���!���!���!���!���!���!���!���!���!���!���!���!���!���!���!���!���!���!���!���!���!���!���������.�����������������������������U����������������������������������������������������������������������������������������������������������������������0���8�����������������������������a���������������������������������������������������������������������������������������������������������������������������������<�������������������������� ���a����������������������������������������������������������������������������������������������������������������������������������9�������������������������� ���X�������������������������������������������������������������������������������������������������������������������������������������<������������������1��� ���!���#���#���#���#���#���#���#���#���#���#���#���#���#���#���#���#���#���#���#���#���#���#���#���#���#���#���#���#���#���#��� ��� ��������������������� --------------------------------------------------------------------------------