From 63b6f3f749a2455a1e1edd0136a4fdb910787d01 Mon Sep 17 00:00:00 2001 From: Zeke Abshire Date: Sat, 14 Jan 2023 23:18:27 -0600 Subject: [PATCH] Initialized T3 app --- .env.example | 19 ++++ .eslintrc.json | 22 ++++ .gitignore | 42 ++++++++ README.md | 28 ++++++ next.config.mjs | 17 ++++ package.json | 41 ++++++++ prisma/schema.prisma | 66 ++++++++++++ public/favicon.ico | Bin 0 -> 15406 bytes src/env/client.mjs | 46 +++++++++ src/env/schema.mjs | 33 ++++++ src/env/server.mjs | 38 +++++++ src/pages/_app.tsx | 20 ++++ src/pages/api/auth/[...nextauth].ts | 38 +++++++ src/pages/api/trpc/[trpc].ts | 19 ++++ src/pages/index.module.css | 149 ++++++++++++++++++++++++++++ src/pages/index.tsx | 84 ++++++++++++++++ src/server/api/root.ts | 14 +++ src/server/api/routers/example.ts | 21 ++++ src/server/api/trpc.ts | 124 +++++++++++++++++++++++ src/server/auth.ts | 21 ++++ src/server/db.ts | 19 ++++ src/styles/globals.css | 16 +++ src/types/next-auth.d.ts | 12 +++ src/utils/api.ts | 65 ++++++++++++ tsconfig.json | 21 ++++ 25 files changed, 975 insertions(+) create mode 100644 .env.example create mode 100644 .eslintrc.json create mode 100644 .gitignore create mode 100644 README.md create mode 100644 next.config.mjs create mode 100644 package.json create mode 100644 prisma/schema.prisma create mode 100644 public/favicon.ico create mode 100644 src/env/client.mjs create mode 100644 src/env/schema.mjs create mode 100644 src/env/server.mjs create mode 100644 src/pages/_app.tsx create mode 100644 src/pages/api/auth/[...nextauth].ts create mode 100644 src/pages/api/trpc/[trpc].ts create mode 100644 src/pages/index.module.css create mode 100644 src/pages/index.tsx create mode 100644 src/server/api/root.ts create mode 100644 src/server/api/routers/example.ts create mode 100644 src/server/api/trpc.ts create mode 100644 src/server/auth.ts create mode 100644 src/server/db.ts create mode 100644 src/styles/globals.css create mode 100644 src/types/next-auth.d.ts create mode 100644 src/utils/api.ts create mode 100644 tsconfig.json diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..991c762 --- /dev/null +++ b/.env.example @@ -0,0 +1,19 @@ +# Since .env is gitignored, you can use .env.example to build a new `.env` file when you clone the repo. +# Keep this file up-to-date when you add new variables to `.env`. + +# This file will be committed to version control, so make sure not to have any secrets in it. +# If you are cloning this repo, create a copy of this file named `.env` and populate it with your secrets. + +# When adding additional env variables, the schema in /env/schema.mjs should be updated accordingly +# Prisma +DATABASE_URL=file:./db.sqlite + +# Next Auth +# You can generate the secret via 'openssl rand -base64 32' on Linux +# More info: https://next-auth.js.org/configuration/options#secret +# NEXTAUTH_SECRET= +NEXTAUTH_URL=http://localhost:3000 + +# Next Auth Discord Provider +DISCORD_CLIENT_ID= +DISCORD_CLIENT_SECRET= diff --git a/.eslintrc.json b/.eslintrc.json new file mode 100644 index 0000000..82671df --- /dev/null +++ b/.eslintrc.json @@ -0,0 +1,22 @@ +{ + "overrides": [ + { + "extends": [ + "plugin:@typescript-eslint/recommended-requiring-type-checking" + ], + "files": ["*.ts", "*.tsx"], + "parserOptions": { + "project": "tsconfig.json" + } + } + ], + "parser": "@typescript-eslint/parser", + "parserOptions": { + "project": "./tsconfig.json" + }, + "plugins": ["@typescript-eslint"], + "extends": ["next/core-web-vitals", "plugin:@typescript-eslint/recommended"], + "rules": { + "@typescript-eslint/consistent-type-imports": "warn" + } +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2971a0b --- /dev/null +++ b/.gitignore @@ -0,0 +1,42 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.js + +# testing +/coverage + +# database +/prisma/db.sqlite +/prisma/db.sqlite-journal + +# next.js +/.next/ +/out/ +next-env.d.ts + +# production +/build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# local env files +# 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 +.env +.env*.local + +# vercel +.vercel + +# typescript +*.tsbuildinfo diff --git a/README.md b/README.md new file mode 100644 index 0000000..fba19ed --- /dev/null +++ b/README.md @@ -0,0 +1,28 @@ +# Create T3 App + +This is a [T3 Stack](https://create.t3.gg/) project bootstrapped with `create-t3-app`. + +## What's next? How do I make an app with this? + +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. + +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. + +- [Next.js](https://nextjs.org) +- [NextAuth.js](https://next-auth.js.org) +- [Prisma](https://prisma.io) +- [Tailwind CSS](https://tailwindcss.com) +- [tRPC](https://trpc.io) + +## Learn More + +To learn more about the [T3 Stack](https://create.t3.gg/), take a look at the following resources: + +- [Documentation](https://create.t3.gg/) +- [Learn the T3 Stack](https://create.t3.gg/en/faq#what-learning-resources-are-currently-available) — Check out these awesome tutorials + +You can check out the [create-t3-app GitHub repository](https://github.com/t3-oss/create-t3-app) — your feedback and contributions are welcome! + +## How do I deploy this? + +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. diff --git a/next.config.mjs b/next.config.mjs new file mode 100644 index 0000000..b5bef6c --- /dev/null +++ b/next.config.mjs @@ -0,0 +1,17 @@ +// @ts-check +/** + * Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. + * This is especially useful for Docker builds. + */ +!process.env.SKIP_ENV_VALIDATION && (await import("./src/env/server.mjs")); + +/** @type {import("next").NextConfig} */ +const config = { + reactStrictMode: true, + swcMinify: true, + i18n: { + locales: ["en"], + defaultLocale: "en", + }, +}; +export default config; diff --git a/package.json b/package.json new file mode 100644 index 0000000..a9e3f89 --- /dev/null +++ b/package.json @@ -0,0 +1,41 @@ +{ + "name": "parallel", + "version": "0.1.0", + "private": true, + "scripts": { + "build": "next build", + "dev": "next dev", + "postinstall": "prisma generate", + "lint": "next lint", + "start": "next start" + }, + "dependencies": { + "@next-auth/prisma-adapter": "^1.0.5", + "@prisma/client": "^4.8.0", + "@tanstack/react-query": "^4.20.0", + "@trpc/client": "^10.8.1", + "@trpc/next": "^10.8.1", + "@trpc/react-query": "^10.8.1", + "@trpc/server": "^10.8.1", + "next": "13.1.1", + "next-auth": "^4.18.7", + "react": "18.2.0", + "react-dom": "18.2.0", + "superjson": "1.9.1", + "zod": "^3.20.2" + }, + "devDependencies": { + "@types/node": "^18.11.18", + "@types/react": "^18.0.26", + "@types/react-dom": "^18.0.10", + "@typescript-eslint/eslint-plugin": "^5.47.1", + "@typescript-eslint/parser": "^5.47.1", + "eslint": "^8.30.0", + "eslint-config-next": "13.1.1", + "prisma": "^4.8.0", + "typescript": "^4.9.4" + }, + "ct3aMetadata": { + "initVersion": "7.3.0" + } +} diff --git a/prisma/schema.prisma b/prisma/schema.prisma new file mode 100644 index 0000000..6d78c6a --- /dev/null +++ b/prisma/schema.prisma @@ -0,0 +1,66 @@ +// This is your Prisma schema file, +// learn more about it in the docs: https://pris.ly/d/prisma-schema + +generator client { + provider = "prisma-client-js" +} + +datasource db { + provider = "sqlite" + // NOTE: When using postgresql, mysql or sqlserver, uncomment the @db.Text annotations in model Account below + // Further reading: + // https://next-auth.js.org/adapters/prisma#create-the-prisma-schema + // https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#string + url = env("DATABASE_URL") +} + +model Example { + id String @id @default(cuid()) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt +} + +// Necessary for Next auth +model Account { + id String @id @default(cuid()) + userId String + type String + provider String + providerAccountId String + refresh_token String? // @db.Text + access_token String? // @db.Text + expires_at Int? + token_type String? + scope String? + id_token String? // @db.Text + session_state String? + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + + @@unique([provider, providerAccountId]) +} + +model Session { + id String @id @default(cuid()) + sessionToken String @unique + userId String + expires DateTime + user User @relation(fields: [userId], references: [id], onDelete: Cascade) +} + +model User { + id String @id @default(cuid()) + name String? + email String? @unique + emailVerified DateTime? + image String? + accounts Account[] + sessions Session[] +} + +model VerificationToken { + identifier String + token String @unique + expires DateTime + + @@unique([identifier, token]) +} diff --git a/public/favicon.ico b/public/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..efd76f16a3593544115c9a60576374dc3660b9f1 GIT binary patch literal 15406 zcmeI2No*BI5QZm86t3iuyH62ECx@JK#R3TwFxMayCm2~AIIu{Z0U>rH7K4Gl1e>G&-CBbRn^ti?RnpL-+Dub zdRpdqe}CtBzj~gRlk@3**bkmps?TzB9-Z zP{cRNh01NAKJ--{NV~qz126aO+b5GJPnPlH$IGNilVtn$?Sb|CzU=Pqmizbb%e8CQ zBo>Rw$B!TTRtdasZEcmSSFg&A8#kn`u1;>=yct;E|B|-Ad-Uj0xpL)-T)uo+9z1y9 zuM&9u^5sjZudkQKj~`1-O^uv7btB9zA+w z*pUPH!_bQtFQl@vQg-j&EqCtRk>=*+FrQmp#_q$14>o@MFD!L+by+`zkM3gfC_`~3jc%O#1GDxF{2l+S+hpYoH--ZiHewe z^7Hd$`0(LLdF05EQc+P6Rr7+3J32aS4&JtHoA|l5wpQN0eQR|h1K`MykwY?$8s4i{ zuVnAuy)t|DY&m)Iq?|r|S~hRqESolMGG4oOtz5cvDKZ!7$lG1iRl)2B~O?`WH~1GdLCj30dS z=1mmM+y7ZNFa}SaJQ4IA1`~b84@B8Mooa7ym$PTj+WbcO@Zm$*vSo{~9$`MjCd019 z1|lqUZ0gjh!a8#9+`0A(Fhr^Qew-ICUNn90?Ci90p=2EJ1F0Z%A79HHoLEQUlbCl? zMXcM-ojWHdPMom5qZ?VuObMv(O6&SV+pkNP zzk_lDU&}l4B$}f2{!s2mo@9vX%g@SXD#KRglmr z=H=zdgb5R*u&_|bb&+Rqfsp5{S+iu+s8IsO|H}g>o{tzYLZ(ljZu^cd;3tQ{nwkAO z_D+{BU25xj*7SZRw~owNYqHjL(H4*=xPsUPnP)M$CjrhckUwD`AA7*3awdUX9?$*E zGjhBx5Wbuo*t~i3Wbxv~vT)%-S-*b0Y}~lfa&qM7{Cw!pAv-TX-pU0cXT4;}63bmK zSg=4AEm~wUCx@3{a;@}{{5p9}_O)E0va&LhcX@fatX#R$a?s>o6WGD}`t@te$&#OD zpOQSG3q;NuJe;zf5^dOw_wF~k$D3DyLazC zj|KU0SFkhweer{hcmiF=-;hU6?5UC8rLQhgGW_g+u=lfU*)l6R!Rve)NPrTx8DKFk)2vDc3I0^XJcH*REZ%eED+o@qYZVSj=RPts;BkJ9LV5 z0sTlfVV~$V`_l9QpALS;1Nk36eq7iy$A^NQXZRuN^KH6`J#X|Q5g)L(4}OR_b@l4i zvSY^%+j|3hqEF1bQJzETuUv@Tj~qE-Ye25?FW?6!u|#!swa`b1XPhZyOkBYaCVV}( z(GUDPexH~Jokz#ndu(WEF#AQv&^K4`BUkj8`4+sKQNTXgvtz#&AH#f$%!xCx55|jU z^w$+acaS@Na@w?M))(|>+_-TvWy%zTi5_t-mp643uT=9{_ z&e#KX0b{S|J@bPL^VXMS#~jNU4(2WxyCD8yp34*hD`Nn&=5keMGDV(QoLLD3NWh(7 zBmiWxSLzp_jNU)heyvN^w+wm4S%_R612-1bA%v!wIm^MBlkb)P)O$A)!Tsn%9BYAA k^`Ak>)%$gfg|c%&7MPUK6V7XZ)v$AhCQDff3{(RD0`^Hap8x;= literal 0 HcmV?d00001 diff --git a/src/env/client.mjs b/src/env/client.mjs new file mode 100644 index 0000000..0f29b85 --- /dev/null +++ b/src/env/client.mjs @@ -0,0 +1,46 @@ +// @ts-check +import { clientSchema } from "./schema.mjs"; + +/** + * You can't destruct `process.env` as a regular object, so we do + * a workaround. This is because Next.js evaluates this at build time, + * and only used environment variables are included in the build. + * @type {{ [key: string]: string | undefined; }} + */ +let clientEnv = {}; +Object.keys(clientSchema.shape).forEach( + (key) => (clientEnv[key] = process.env[key]), +); + +const _clientEnv = clientSchema.safeParse(clientEnv); + +export const formatErrors = ( + /** @type {import('zod').ZodFormattedError,string>} */ + errors, +) => + Object.entries(errors) + .map(([name, value]) => { + if (value && "_errors" in value) + return `${name}: ${value._errors.join(", ")}\n`; + }) + .filter(Boolean); + +if (!_clientEnv.success) { + console.error( + "❌ Invalid environment variables:\n", + ...formatErrors(_clientEnv.error.format()), + ); + throw new Error("Invalid environment variables"); +} + +for (let key of Object.keys(_clientEnv.data)) { + if (!key.startsWith("NEXT_PUBLIC_")) { + console.warn( + `❌ Invalid public environment variable name: ${key}. It must begin with 'NEXT_PUBLIC_'`, + ); + + throw new Error("Invalid public environment variable name"); + } +} + +export const env = _clientEnv.data; diff --git a/src/env/schema.mjs b/src/env/schema.mjs new file mode 100644 index 0000000..c3be022 --- /dev/null +++ b/src/env/schema.mjs @@ -0,0 +1,33 @@ +// @ts-check +import { z } from "zod"; + +/** + * Specify your server-side environment variables schema here. + * This way you can ensure the app isn't built with invalid env vars. + */ +export const serverSchema = z.object({ + DATABASE_URL: z.string().url(), + NODE_ENV: z.enum(["development", "test", "production"]), + NEXTAUTH_SECRET: + process.env.NODE_ENV === "production" + ? z.string().min(1) + : z.string().min(1).optional(), + NEXTAUTH_URL: z.preprocess( + // This makes Vercel deployments not fail if you don't set NEXTAUTH_URL + // Since NextAuth.js automatically uses the VERCEL_URL if present. + (str) => process.env.VERCEL_URL ?? str, + // VERCEL_URL doesn't include `https` so it cant be validated as a URL + process.env.VERCEL ? z.string() : z.string().url(), + ), + DISCORD_CLIENT_ID: z.string(), + DISCORD_CLIENT_SECRET: z.string(), +}); + +/** + * Specify your client-side environment variables schema here. + * This way you can ensure the app isn't built with invalid env vars. + * To expose them to the client, prefix them with `NEXT_PUBLIC_`. + */ +export const clientSchema = z.object({ + // NEXT_PUBLIC_CLIENTVAR: z.string(), +}); diff --git a/src/env/server.mjs b/src/env/server.mjs new file mode 100644 index 0000000..6a8cc9d --- /dev/null +++ b/src/env/server.mjs @@ -0,0 +1,38 @@ +// @ts-check +/** + * This file is included in `/next.config.mjs` which ensures the app isn't built with invalid env vars. + * It has to be a `.mjs`-file to be imported there. + */ +import { serverSchema } from "./schema.mjs"; +import { env as clientEnv, formatErrors } from "./client.mjs"; + +/** + * You can't destruct `process.env` as a regular object, so we do + * a workaround. This is because Next.js evaluates this at build time, + * and only used environment variables are included in the build. + * @type {{ [key: string]: string | undefined; }} + */ +let serverEnv = {}; +Object.keys(serverSchema.shape).forEach( + (key) => (serverEnv[key] = process.env[key]), +); + +const _serverEnv = serverSchema.safeParse(serverEnv); + +if (!_serverEnv.success) { + console.error( + "❌ Invalid environment variables:\n", + ...formatErrors(_serverEnv.error.format()), + ); + throw new Error("Invalid environment variables"); +} + +for (let key of Object.keys(_serverEnv.data)) { + if (key.startsWith("NEXT_PUBLIC_")) { + console.warn("❌ You are exposing a server-side env-variable:", key); + + throw new Error("You are exposing a server-side env-variable"); + } +} + +export const env = { ..._serverEnv.data, ...clientEnv }; diff --git a/src/pages/_app.tsx b/src/pages/_app.tsx new file mode 100644 index 0000000..2a46c68 --- /dev/null +++ b/src/pages/_app.tsx @@ -0,0 +1,20 @@ +import { type AppType } from "next/app"; +import { type Session } from "next-auth"; +import { SessionProvider } from "next-auth/react"; + +import { api } from "../utils/api"; + +import "../styles/globals.css"; + +const MyApp: AppType<{ session: Session | null }> = ({ + Component, + pageProps: { session, ...pageProps }, +}) => { + return ( + + + + ); +}; + +export default api.withTRPC(MyApp); diff --git a/src/pages/api/auth/[...nextauth].ts b/src/pages/api/auth/[...nextauth].ts new file mode 100644 index 0000000..e218f01 --- /dev/null +++ b/src/pages/api/auth/[...nextauth].ts @@ -0,0 +1,38 @@ +import NextAuth, { type NextAuthOptions } from "next-auth"; +import DiscordProvider from "next-auth/providers/discord"; +// Prisma adapter for NextAuth, optional and can be removed +import { PrismaAdapter } from "@next-auth/prisma-adapter"; + +import { env } from "../../../env/server.mjs"; +import { prisma } from "../../../server/db"; + +export const authOptions: NextAuthOptions = { + // Include user.id on session + callbacks: { + session({ session, user }) { + if (session.user) { + session.user.id = user.id; + } + return session; + }, + }, + // Configure one or more authentication providers + adapter: PrismaAdapter(prisma), + providers: [ + DiscordProvider({ + clientId: env.DISCORD_CLIENT_ID, + clientSecret: env.DISCORD_CLIENT_SECRET, + }), + /** + * ...add more providers here + * + * Most other providers require a bit more work than the Discord provider. + * For example, the GitHub provider requires you to add the + * `refresh_token_expires_in` field to the Account model. Refer to the + * NextAuth.js docs for the provider you want to use. Example: + * @see https://next-auth.js.org/providers/github + */ + ], +}; + +export default NextAuth(authOptions); diff --git a/src/pages/api/trpc/[trpc].ts b/src/pages/api/trpc/[trpc].ts new file mode 100644 index 0000000..8ec828b --- /dev/null +++ b/src/pages/api/trpc/[trpc].ts @@ -0,0 +1,19 @@ +import { createNextApiHandler } from "@trpc/server/adapters/next"; + +import { env } from "../../../env/server.mjs"; +import { createTRPCContext } from "../../../server/api/trpc"; +import { appRouter } from "../../../server/api/root"; + +// export API handler +export default createNextApiHandler({ + router: appRouter, + createContext: createTRPCContext, + onError: + env.NODE_ENV === "development" + ? ({ path, error }) => { + console.error( + `❌ tRPC failed on ${path ?? ""}: ${error.message}`, + ); + } + : undefined, +}); diff --git a/src/pages/index.module.css b/src/pages/index.module.css new file mode 100644 index 0000000..d9caeea --- /dev/null +++ b/src/pages/index.module.css @@ -0,0 +1,149 @@ +.main { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + min-height: 100vh; + background-image: linear-gradient(to bottom, #2e026d, #15162c); +} + +.container { + width: 100%; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 3rem; + padding: 4rem 1rem; +} + +@media (min-width: 640px) { + .container { + max-width: 640px; + } +} + +@media (min-width: 768px) { + .container { + max-width: 768px; + } +} + +@media (min-width: 1024px) { + .container { + max-width: 1024px; + } +} + +@media (min-width: 1280px) { + .container { + max-width: 1280px; + } +} + +@media (min-width: 1536px) { + .container { + max-width: 1536px; + } +} + +.title { + font-size: 3rem; + line-height: 1; + font-weight: 800; + letter-spacing: -0.025em; + margin: 0; + color: white; +} + +@media (min-width: 640px) { + .title { + font-size: 5rem; + } +} + +.pinkSpan { + color: hsl(280 100% 70%); +} + +.cardRow { + display: grid; + grid-template-columns: repeat(1, minmax(0, 1fr)); + gap: 1rem; +} + +@media (min-width: 640px) { + .cardRow { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} + +@media (min-width: 768px) { + .cardRow { + gap: 2rem; + } +} + +.card { + max-width: 20rem; + display: flex; + flex-direction: column; + gap: 1rem; + padding: 1rem; + border-radius: 0.75rem; + color: white; + background-color: rgb(255 255 255 / 0.1); +} + +.card:hover { + background-color: rgb(255 255 255 / 0.2); + transition: background-color 150ms cubic-bezier(0.5, 0, 0.2, 1); +} + +.cardTitle { + font-size: 1.5rem; + line-height: 2rem; + font-weight: 700; + margin: 0; +} + +.cardText { + font-size: 1.125rem; + line-height: 1.75rem; +} + +.showcaseContainer { + display: flex; + flex-direction: column; + align-items: center; + gap: 0.5rem; +} + +.showcaseText { + color: white; + text-align: center; + font-size: 1.5rem; + line-height: 2rem; +} + +.authContainer { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 1rem; +} + +.loginButton { + border-radius: 9999px; + background-color: rgb(255 255 255 / 0.1); + padding: 0.75rem 2.5rem; + font-weight: 600; + color: white; + text-decoration-line: none; + transition: background-color 150ms cubic-bezier(0.5, 0, 0.2, 1); +} + +.loginButton:hover { + background-color: rgb(255 255 255 / 0.2); +} diff --git a/src/pages/index.tsx b/src/pages/index.tsx new file mode 100644 index 0000000..adcaac7 --- /dev/null +++ b/src/pages/index.tsx @@ -0,0 +1,84 @@ +import styles from "./index.module.css"; +import { type NextPage } from "next"; +import Head from "next/head"; +import Link from "next/link"; +import { signIn, signOut, useSession } from "next-auth/react"; + +import { api } from "../utils/api"; + +const Home: NextPage = () => { + const hello = api.example.hello.useQuery({ text: "from tRPC" }); + + return ( + <> + + Create T3 App + + + +
+
+

+ Create T3 App +

+
+ +

First Steps →

+
+ Just the basics - Everything you need to know to set up your + database and authentication. +
+ + +

Documentation →

+
+ Learn more about Create T3 App, the libraries it uses, and how + to deploy it. +
+ +
+
+

+ {hello.data ? hello.data.greeting : "Loading tRPC query..."} +

+ +
+
+
+ + ); +}; + +export default Home; + +const AuthShowcase: React.FC = () => { + const { data: sessionData } = useSession(); + + const { data: secretMessage } = api.example.getSecretMessage.useQuery( + undefined, // no input + { enabled: sessionData?.user !== undefined }, + ); + + return ( +
+

+ {sessionData && Logged in as {sessionData.user?.name}} + {secretMessage && - {secretMessage}} +

+ +
+ ); +}; diff --git a/src/server/api/root.ts b/src/server/api/root.ts new file mode 100644 index 0000000..c3f288e --- /dev/null +++ b/src/server/api/root.ts @@ -0,0 +1,14 @@ +import { createTRPCRouter } from "./trpc"; +import { exampleRouter } from "./routers/example"; + +/** + * This is the primary router for your server. + * + * All routers added in /api/routers should be manually added here + */ +export const appRouter = createTRPCRouter({ + example: exampleRouter, +}); + +// export type definition of API +export type AppRouter = typeof appRouter; diff --git a/src/server/api/routers/example.ts b/src/server/api/routers/example.ts new file mode 100644 index 0000000..1586033 --- /dev/null +++ b/src/server/api/routers/example.ts @@ -0,0 +1,21 @@ +import { z } from "zod"; + +import { createTRPCRouter, publicProcedure, protectedProcedure } from "../trpc"; + +export const exampleRouter = createTRPCRouter({ + hello: publicProcedure + .input(z.object({ text: z.string() })) + .query(({ input }) => { + return { + greeting: `Hello ${input.text}`, + }; + }), + + getAll: publicProcedure.query(({ ctx }) => { + return ctx.prisma.example.findMany(); + }), + + getSecretMessage: protectedProcedure.query(() => { + return "you can now see this secret message!"; + }), +}); diff --git a/src/server/api/trpc.ts b/src/server/api/trpc.ts new file mode 100644 index 0000000..298667c --- /dev/null +++ b/src/server/api/trpc.ts @@ -0,0 +1,124 @@ +/** + * YOU PROBABLY DON'T NEED TO EDIT THIS FILE, UNLESS: + * 1. You want to modify request context (see Part 1) + * 2. You want to create a new middleware or type of procedure (see Part 3) + * + * tl;dr - this is where all the tRPC server stuff is created and plugged in. + * The pieces you will need to use are documented accordingly near the end + */ + +/** + * 1. CONTEXT + * + * This section defines the "contexts" that are available in the backend API + * + * These allow you to access things like the database, the session, etc, when + * processing a request + * + */ +import { type CreateNextContextOptions } from "@trpc/server/adapters/next"; +import { type Session } from "next-auth"; + +import { getServerAuthSession } from "../auth"; +import { prisma } from "../db"; + +type CreateContextOptions = { + session: Session | null; +}; + +/** + * This helper generates the "internals" for a tRPC context. If you need to use + * it, you can export it from here + * + * Examples of things you may need it for: + * - testing, so we dont have to mock Next.js' req/res + * - trpc's `createSSGHelpers` where we don't have req/res + * @see https://create.t3.gg/en/usage/trpc#-servertrpccontextts + */ +const createInnerTRPCContext = (opts: CreateContextOptions) => { + return { + session: opts.session, + prisma, + }; +}; + +/** + * This is the actual context you'll use in your router. It will be used to + * process every request that goes through your tRPC endpoint + * @link https://trpc.io/docs/context + */ +export const createTRPCContext = async (opts: CreateNextContextOptions) => { + const { req, res } = opts; + + // Get the session from the server using the unstable_getServerSession wrapper function + const session = await getServerAuthSession({ req, res }); + + return createInnerTRPCContext({ + session, + }); +}; + +/** + * 2. INITIALIZATION + * + * This is where the trpc api is initialized, connecting the context and + * transformer + */ +import { initTRPC, TRPCError } from "@trpc/server"; +import superjson from "superjson"; + +const t = initTRPC.context().create({ + transformer: superjson, + errorFormatter({ shape }) { + return shape; + }, +}); + +/** + * 3. ROUTER & PROCEDURE (THE IMPORTANT BIT) + * + * These are the pieces you use to build your tRPC API. You should import these + * a lot in the /src/server/api/routers folder + */ + +/** + * This is how you create new routers and subrouters in your tRPC API + * @see https://trpc.io/docs/router + */ +export const createTRPCRouter = t.router; + +/** + * Public (unauthed) procedure + * + * This is the base piece you use to build new queries and mutations on your + * tRPC API. It does not guarantee that a user querying is authorized, but you + * can still access user session data if they are logged in + */ +export const publicProcedure = t.procedure; + +/** + * Reusable middleware that enforces users are logged in before running the + * procedure + */ +const enforceUserIsAuthed = t.middleware(({ ctx, next }) => { + if (!ctx.session || !ctx.session.user) { + throw new TRPCError({ code: "UNAUTHORIZED" }); + } + return next({ + ctx: { + // infers the `session` as non-nullable + session: { ...ctx.session, user: ctx.session.user }, + }, + }); +}); + +/** + * Protected (authed) procedure + * + * If you want a query or mutation to ONLY be accessible to logged in users, use + * this. It verifies the session is valid and guarantees ctx.session.user is not + * null + * + * @see https://trpc.io/docs/procedures + */ +export const protectedProcedure = t.procedure.use(enforceUserIsAuthed); diff --git a/src/server/auth.ts b/src/server/auth.ts new file mode 100644 index 0000000..a99fdae --- /dev/null +++ b/src/server/auth.ts @@ -0,0 +1,21 @@ +import { type GetServerSidePropsContext } from "next"; +import { unstable_getServerSession } from "next-auth"; + +import { authOptions } from "../pages/api/auth/[...nextauth]"; + +/** + * Wrapper for unstable_getServerSession, used in trpc createContext and the + * restricted API route + * + * Don't worry too much about the "unstable", it's safe to use but the syntax + * may change in future versions + * + * @see https://next-auth.js.org/configuration/nextjs + */ + +export const getServerAuthSession = async (ctx: { + req: GetServerSidePropsContext["req"]; + res: GetServerSidePropsContext["res"]; +}) => { + return await unstable_getServerSession(ctx.req, ctx.res, authOptions); +}; diff --git a/src/server/db.ts b/src/server/db.ts new file mode 100644 index 0000000..5df917c --- /dev/null +++ b/src/server/db.ts @@ -0,0 +1,19 @@ +import { PrismaClient } from "@prisma/client"; + +import { env } from "../env/server.mjs"; + +declare global { + // eslint-disable-next-line no-var + var prisma: PrismaClient | undefined; +} + +export const prisma = + global.prisma || + new PrismaClient({ + log: + env.NODE_ENV === "development" ? ["query", "error", "warn"] : ["error"], + }); + +if (env.NODE_ENV !== "production") { + global.prisma = prisma; +} diff --git a/src/styles/globals.css b/src/styles/globals.css new file mode 100644 index 0000000..e5e2dcc --- /dev/null +++ b/src/styles/globals.css @@ -0,0 +1,16 @@ +html, +body { + padding: 0; + margin: 0; + font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, + Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif; +} + +a { + color: inherit; + text-decoration: none; +} + +* { + box-sizing: border-box; +} diff --git a/src/types/next-auth.d.ts b/src/types/next-auth.d.ts new file mode 100644 index 0000000..fc41716 --- /dev/null +++ b/src/types/next-auth.d.ts @@ -0,0 +1,12 @@ +import { type DefaultSession } from "next-auth"; + +declare module "next-auth" { + /** + * Returned by `useSession`, `getSession` and received as a prop on the `SessionProvider` React Context + */ + interface Session { + user?: { + id: string; + } & DefaultSession["user"]; + } +} diff --git a/src/utils/api.ts b/src/utils/api.ts new file mode 100644 index 0000000..c99a366 --- /dev/null +++ b/src/utils/api.ts @@ -0,0 +1,65 @@ +/** + * This is the client-side entrypoint for your tRPC API. + * It's used to create the `api` object which contains the Next.js App-wrapper + * as well as your typesafe react-query hooks. + * + * We also create a few inference helpers for input and output types + */ +import { httpBatchLink, loggerLink } from "@trpc/client"; +import { createTRPCNext } from "@trpc/next"; +import { type inferRouterInputs, type inferRouterOutputs } from "@trpc/server"; +import superjson from "superjson"; + +import { type AppRouter } from "../server/api/root"; + +const getBaseUrl = () => { + if (typeof window !== "undefined") return ""; // browser should use relative url + if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`; // SSR should use vercel url + return `http://localhost:${process.env.PORT ?? 3000}`; // dev SSR should use localhost +}; + +/** + * A set of typesafe react-query hooks for your tRPC API + */ +export const api = createTRPCNext({ + config() { + return { + /** + * Transformer used for data de-serialization from the server + * @see https://trpc.io/docs/data-transformers + **/ + transformer: superjson, + + /** + * Links used to determine request flow from client to server + * @see https://trpc.io/docs/links + * */ + links: [ + loggerLink({ + enabled: (opts) => + process.env.NODE_ENV === "development" || + (opts.direction === "down" && opts.result instanceof Error), + }), + httpBatchLink({ + url: `${getBaseUrl()}/api/trpc`, + }), + ], + }; + }, + /** + * Whether tRPC should await queries when server rendering pages + * @see https://trpc.io/docs/nextjs#ssr-boolean-default-false + */ + ssr: false, +}); + +/** + * Inference helper for inputs + * @example type HelloInput = RouterInputs['example']['hello'] + **/ +export type RouterInputs = inferRouterInputs; +/** + * Inference helper for outputs + * @example type HelloOutput = RouterOutputs['example']['hello'] + **/ +export type RouterOutputs = inferRouterOutputs; diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..658068a --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "es2017", + "lib": ["dom", "dom.iterable", "esnext"], + "allowJs": true, + "skipLibCheck": true, + "strict": true, + "forceConsistentCasingInFileNames": true, + "noEmit": true, + "esModuleInterop": true, + "module": "esnext", + "moduleResolution": "node", + "resolveJsonModule": true, + "isolatedModules": true, + "jsx": "preserve", + "incremental": true, + "noUncheckedIndexedAccess": true + }, + "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "**/*.cjs", "**/*.mjs"], + "exclude": ["node_modules"] +}