From 11c0c896244b762c45320855217bf3bbf77fda9f Mon Sep 17 00:00:00 2001 From: th3r00t Date: Sun, 19 Mar 2023 21:08:52 -0400 Subject: [PATCH] Using create-t3-app. --- src/client/.env.example | 25 ++++ src/client/.eslintrc.cjs | 35 +++++ src/client/.eslintrc.json | 3 - src/client/.gitignore | 8 +- src/client/README.md | 42 +++--- src/client/next.config.js | 8 -- src/client/next.config.mjs | 22 +++ src/client/package.json | 46 +++++-- src/client/postcss.config.cjs | 8 ++ src/client/prettier.config.cjs | 6 + src/client/prisma/schema.prisma | 81 +++++++++++ src/client/public/favicon.ico | Bin 0 -> 15406 bytes src/client/public/next.svg | 1 - src/client/public/thirteen.svg | 1 - src/client/public/vercel.svg | 1 - src/client/src/app/api/hello/route.ts | 3 - src/client/src/app/favicon.ico | Bin 25931 -> 0 bytes src/client/src/app/layout.tsx | 18 --- src/client/src/app/page.tsx | 94 ------------- src/client/src/env.mjs | 94 +++++++++++++ src/client/src/pages/_app.tsx | 20 +++ .../src/pages/api/auth/[...nextauth].ts | 4 + src/client/src/pages/api/trpc/[trpc].ts | 19 +++ src/client/src/pages/index.tsx | 83 +++++++++++ src/client/src/server/api/root.ts | 14 ++ src/client/src/server/api/routers/example.ts | 25 ++++ src/client/src/server/api/trpc.ts | 130 ++++++++++++++++++ src/client/src/server/auth.ts | 76 ++++++++++ src/client/src/server/db.ts | 14 ++ src/client/src/types/index.tsx | 18 --- src/client/src/utils/api.ts | 68 +++++++++ src/client/tailwind.config.cjs | 10 ++ src/client/theme.tsx | 20 --- src/client/tsconfig.json | 21 +-- 34 files changed, 806 insertions(+), 212 deletions(-) create mode 100644 src/client/.env.example create mode 100644 src/client/.eslintrc.cjs delete mode 100644 src/client/.eslintrc.json delete mode 100644 src/client/next.config.js create mode 100644 src/client/next.config.mjs create mode 100644 src/client/postcss.config.cjs create mode 100644 src/client/prettier.config.cjs create mode 100644 src/client/prisma/schema.prisma create mode 100644 src/client/public/favicon.ico delete mode 100644 src/client/public/next.svg delete mode 100644 src/client/public/thirteen.svg delete mode 100644 src/client/public/vercel.svg delete mode 100644 src/client/src/app/api/hello/route.ts delete mode 100644 src/client/src/app/favicon.ico delete mode 100644 src/client/src/app/layout.tsx delete mode 100644 src/client/src/app/page.tsx create mode 100644 src/client/src/env.mjs create mode 100644 src/client/src/pages/_app.tsx create mode 100644 src/client/src/pages/api/auth/[...nextauth].ts create mode 100644 src/client/src/pages/api/trpc/[trpc].ts create mode 100644 src/client/src/pages/index.tsx create mode 100644 src/client/src/server/api/root.ts create mode 100644 src/client/src/server/api/routers/example.ts create mode 100644 src/client/src/server/api/trpc.ts create mode 100644 src/client/src/server/auth.ts create mode 100644 src/client/src/server/db.ts delete mode 100644 src/client/src/types/index.tsx create mode 100644 src/client/src/utils/api.ts create mode 100644 src/client/tailwind.config.cjs delete mode 100644 src/client/theme.tsx diff --git a/src/client/.env.example b/src/client/.env.example new file mode 100644 index 0000000..c1464a2 --- /dev/null +++ b/src/client/.env.example @@ -0,0 +1,25 @@ +# Since the ".env" file is gitignored, you can use the ".env.example" file 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 environment variables, the schema in "/src/env.mjs" +# should be updated accordingly. + +# Prisma +# https://www.prisma.io/docs/reference/database-reference/connection-urls#env +DATABASE_URL="file:./db.sqlite" + +# Next Auth +# You can generate a new secret on the command line with: +# openssl rand -base64 32 +# 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/src/client/.eslintrc.cjs b/src/client/.eslintrc.cjs new file mode 100644 index 0000000..8b7a0e8 --- /dev/null +++ b/src/client/.eslintrc.cjs @@ -0,0 +1,35 @@ +// eslint-disable-next-line @typescript-eslint/no-var-requires +const path = require("path"); + +/** @type {import("eslint").Linter.Config} */ +const config = { + overrides: [ + { + extends: [ + "plugin:@typescript-eslint/recommended-requiring-type-checking", + ], + files: ["*.ts", "*.tsx"], + parserOptions: { + project: path.join(__dirname, "tsconfig.json"), + }, + }, + ], + parser: "@typescript-eslint/parser", + parserOptions: { + project: path.join(__dirname, "tsconfig.json"), + }, + plugins: ["@typescript-eslint"], + extends: ["next/core-web-vitals", "plugin:@typescript-eslint/recommended"], + rules: { + "@typescript-eslint/consistent-type-imports": [ + "warn", + { + prefer: "type-imports", + fixStyle: "inline-type-imports", + }, + ], + "@typescript-eslint/no-unused-vars": ["warn", { argsIgnorePattern: "^_" }], + }, +}; + +module.exports = config; diff --git a/src/client/.eslintrc.json b/src/client/.eslintrc.json deleted file mode 100644 index bffb357..0000000 --- a/src/client/.eslintrc.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": "next/core-web-vitals" -} diff --git a/src/client/.gitignore b/src/client/.gitignore index c87c9b3..2971a0b 100644 --- a/src/client/.gitignore +++ b/src/client/.gitignore @@ -8,9 +8,14 @@ # testing /coverage +# database +/prisma/db.sqlite +/prisma/db.sqlite-journal + # next.js /.next/ /out/ +next-env.d.ts # production /build @@ -26,6 +31,8 @@ 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 @@ -33,4 +40,3 @@ yarn-error.log* # typescript *.tsbuildinfo -next-env.d.ts diff --git a/src/client/README.md b/src/client/README.md index 5bc7ca2..fba19ed 100644 --- a/src/client/README.md +++ b/src/client/README.md @@ -1,38 +1,28 @@ -This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app). +# Create T3 App -## Getting Started +This is a [T3 Stack](https://create.t3.gg/) project bootstrapped with `create-t3-app`. -First, run the development server: +## What's next? How do I make an app with this? -```bash -npm run dev -# or -yarn dev -# or -pnpm dev -``` +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. -Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. +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. -You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. - -[API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.ts`. - -The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages. - -This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font. +- [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 Next.js, take a look at the following resources: +To learn more about the [T3 Stack](https://create.t3.gg/), take a look at the following resources: -- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. -- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. +- [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 Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome! +You can check out the [create-t3-app GitHub repository](https://github.com/t3-oss/create-t3-app) — your feedback and contributions are welcome! -## Deploy on Vercel +## How do I deploy this? -The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. - -Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details. +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/src/client/next.config.js b/src/client/next.config.js deleted file mode 100644 index dafb0c8..0000000 --- a/src/client/next.config.js +++ /dev/null @@ -1,8 +0,0 @@ -/** @type {import('next').NextConfig} */ -const nextConfig = { - experimental: { - appDir: true, - }, -} - -module.exports = nextConfig diff --git a/src/client/next.config.mjs b/src/client/next.config.mjs new file mode 100644 index 0000000..f9b4e26 --- /dev/null +++ b/src/client/next.config.mjs @@ -0,0 +1,22 @@ +/** + * 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.mjs")); + +/** @type {import("next").NextConfig} */ +const config = { + reactStrictMode: true, + + /** + * If you have the "experimental: { appDir: true }" setting enabled, then you + * must comment the below `i18n` config out. + * + * @see https://github.com/vercel/next.js/issues/41980 + */ + i18n: { + locales: ["en"], + defaultLocale: "en", + }, +}; +export default config; diff --git a/src/client/package.json b/src/client/package.json index 15448c4..2a71bd9 100644 --- a/src/client/package.json +++ b/src/client/package.json @@ -3,20 +3,46 @@ "version": "0.1.0", "private": true, "scripts": { - "dev": "next dev", "build": "next build", - "start": "next start", - "lint": "next lint" + "dev": "next dev", + "postinstall": "prisma generate", + "lint": "next lint", + "start": "next start" }, "dependencies": { - "@types/node": "18.15.3", - "@types/react": "18.0.28", - "@types/react-dom": "18.0.11", - "eslint": "8.36.0", - "eslint-config-next": "13.2.4", - "next": "13.2.4", + "@next-auth/prisma-adapter": "^1.0.5", + "@prisma/client": "^4.9.0", + "@tanstack/react-query": "^4.20.2", + "@trpc/client": "^10.9.0", + "@trpc/next": "^10.9.0", + "@trpc/react-query": "^10.9.0", + "@trpc/server": "^10.9.0", + "next": "^13.2.1", + "next-auth": "^4.19.0", "react": "18.2.0", "react-dom": "18.2.0", - "typescript": "5.0.2" + "superjson": "1.9.1", + "zod": "^3.20.6" + }, + "devDependencies": { + "@types/eslint": "^8.21.1", + "@types/node": "^18.14.0", + "@types/prettier": "^2.7.2", + "@types/react": "^18.0.28", + "@types/react-dom": "^18.0.11", + "@typescript-eslint/eslint-plugin": "^5.53.0", + "@typescript-eslint/parser": "^5.53.0", + "autoprefixer": "^10.4.7", + "eslint": "^8.34.0", + "eslint-config-next": "^13.2.1", + "postcss": "^8.4.14", + "prettier": "^2.8.1", + "prettier-plugin-tailwindcss": "^0.2.1", + "prisma": "^4.9.0", + "tailwindcss": "^3.2.0", + "typescript": "^4.9.5" + }, + "ct3aMetadata": { + "initVersion": "7.8.0" } } diff --git a/src/client/postcss.config.cjs b/src/client/postcss.config.cjs new file mode 100644 index 0000000..e305dd9 --- /dev/null +++ b/src/client/postcss.config.cjs @@ -0,0 +1,8 @@ +const config = { + plugins: { + tailwindcss: {}, + autoprefixer: {}, + }, +}; + +module.exports = config; diff --git a/src/client/prettier.config.cjs b/src/client/prettier.config.cjs new file mode 100644 index 0000000..ca28ed9 --- /dev/null +++ b/src/client/prettier.config.cjs @@ -0,0 +1,6 @@ +/** @type {import("prettier").Config} */ +const config = { + plugins: [require.resolve("prettier-plugin-tailwindcss")], +}; + +module.exports = config; diff --git a/src/client/prisma/schema.prisma b/src/client/prisma/schema.prisma new file mode 100644 index 0000000..8259662 --- /dev/null +++ b/src/client/prisma/schema.prisma @@ -0,0 +1,81 @@ +// 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]) +} + +model Books { + id String @id @default(cuid()) + title String + author String + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt +} + +model Collections { + id String @id @default(cuid()) + title String + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt +} diff --git a/src/client/public/favicon.ico b/src/client/public/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..60c702aac13409c82c4040f8fee9603eb84aa10c GIT binary patch literal 15406 zcmeHOX^b4j6>hH&u3!wtgoMM(Da<7x5Rn8Tjvq)?zybua1c*c20{$U^Aj%>HD9R-z zBuWB;ARB>eYK+y}Dk#s*$8Q(p+iLA_;N7bn84x`l%#I{rywlCmbkAPayBK)27Rhm!$WXNYV+Q zK^4@P%189Q__>DsD^FL?7r_P=JJvIlKl+CJ62dyd9WqHP5Sp7xG3? zPX~|xApI@EB+@r<8Zj2@M^QA-H<*IF*CS2am*|i;*E8hDd|es0ZRN*eT}q4f={qph zUyoWUdZ+R8ip52QA+%;l|Sa2^7!PrYAH1GAw4nmfKx zy1+M;Td^MB<(cfVs$m?`u57IHH)D=|NWm@3zi7tCFgENLSn7k=Pdv~@u`r2!VJ-Hn z5cXiS66w9>LT56iNCfU;)=ma= z`c9MYdEO$lXDjiAZma0~qmy`0Ud=wxm3KG>+B=)kiuq~siOx6F`)WK*<@aK}q_nFk z=W_Xo|D8k=&&!fe^n@YJ_ToIDgFft$u(^~7d^hv_v^bCawEFQf^jDeWqrcR6S<-hm zzt3;Z#bYA(s$u7s3+5#DVP-&b)99=$<^0;j3 zcc)NTm?l#!%O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%OSkaTSaNZniT#y)LG`(S^d#o(f0N$S=E0Xm z69nua-)1-RfN`**lRLwjZKf-mfScCTMmtQlmSkn&*%Qh=t8_ZBe~{3IHMCdn2^iBb zU@Z0dnsO%gtl?N6Y{&Y!ir&Ac*2mk5ac|mxL_VZh2;?)RIUwSqJpgNKaYjEF@;@WI zV;5<~G|ty}hr~8c`6=kme>Q^rmKXb<0b#1W2{PGdGuxm%Zdt`cMch0MyXbn%Lwe)X zm_Ofrn*7V_#@MFAI1Y+wEV-6^4ls%5b>Nb>VQu|ugs~#hQ+hYypVk$7do)3>4&JN5 z*Qv&IioJq8V&L9GYy;NYm7v3!Od*?f)&p$Ie z=7xjyDDv&@jzB)Sqc--SY9FM2yJ2IM#O`-=V2OZPO;(?CxHJq`3Uu%~L^f2g^2 A#Q*>R literal 0 HcmV?d00001 diff --git a/src/client/public/next.svg b/src/client/public/next.svg deleted file mode 100644 index 5bb00d4..0000000 --- a/src/client/public/next.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/client/public/thirteen.svg b/src/client/public/thirteen.svg deleted file mode 100644 index db65b53..0000000 --- a/src/client/public/thirteen.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/client/public/vercel.svg b/src/client/public/vercel.svg deleted file mode 100644 index 1aeda7d..0000000 --- a/src/client/public/vercel.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/client/src/app/api/hello/route.ts b/src/client/src/app/api/hello/route.ts deleted file mode 100644 index d1cc6ee..0000000 --- a/src/client/src/app/api/hello/route.ts +++ /dev/null @@ -1,3 +0,0 @@ -export async function GET(request: Request) { - return new Response('Hello, Next.js!') -} diff --git a/src/client/src/app/favicon.ico b/src/client/src/app/favicon.ico deleted file mode 100644 index 718d6fea4835ec2d246af9800eddb7ffb276240c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 25931 zcmeHv30#a{`}aL_*G&7qml|y<+KVaDM2m#dVr!KsA!#An?kSQM(q<_dDNCpjEux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2#gCCv4jM#ArwlzZ$7@9&XkFxZ4n!V zj3dyiwW4Ki2QG{@i>yuZXQizw_OkZI^-3otXC{!(lUpJF33gI60ak;Uqitp74|B6I zgg{b=Iz}WkhCGj1M=hu4#Aw173YxIVbISaoc z-nLZC*6Tgivd5V`K%GxhBsp@SUU60-rfc$=wb>zdJzXS&-5(NRRodFk;Kxk!S(O(a0e7oY=E( zAyS;Ow?6Q&XA+cnkCb{28_1N8H#?J!*$MmIwLq^*T_9-z^&UE@A(z9oGYtFy6EZef LrJugUA?W`A8`#=m diff --git a/src/client/src/app/layout.tsx b/src/client/src/app/layout.tsx deleted file mode 100644 index 3d9d723..0000000 --- a/src/client/src/app/layout.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import './globals.css' - -export const metadata = { - title: 'Create Next App', - description: 'Generated by create next app', -} - -export default function RootLayout({ - children, -}: { - children: React.ReactNode -}) { - return ( - - {children} - - ) -} diff --git a/src/client/src/app/page.tsx b/src/client/src/app/page.tsx deleted file mode 100644 index 32260d7..0000000 --- a/src/client/src/app/page.tsx +++ /dev/null @@ -1,94 +0,0 @@ -import Image from 'next/image' -import { Inter } from 'next/font/google' -import { CssBaseline } from '@material-ui/core'; -import { ThemeProvider } from '@material-ui/core/styles'; -import { theme } from '../theme'; -import styles from './page.module.css' - -const inter = Inter({ subsets: ['latin'] }) - -export default function Home() { - return ( - - ) -} diff --git a/src/client/src/env.mjs b/src/client/src/env.mjs new file mode 100644 index 0000000..fcad3ec --- /dev/null +++ b/src/client/src/env.mjs @@ -0,0 +1,94 @@ +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. + */ +const server = 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().min(1) : z.string().url(), + ), + // Add `.min(1) on ID and SECRET if you want to make sure they're not empty + 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_`. + */ +const client = z.object({ + // NEXT_PUBLIC_CLIENTVAR: z.string().min(1), +}); + +/** + * You can't destruct `process.env` as a regular object in the Next.js edge runtimes (e.g. + * middlewares) or client-side so we need to destruct manually. + * + * @type {Record | keyof z.infer, string | undefined>} + */ +const processEnv = { + DATABASE_URL: process.env.DATABASE_URL, + NODE_ENV: process.env.NODE_ENV, + NEXTAUTH_SECRET: process.env.NEXTAUTH_SECRET, + NEXTAUTH_URL: process.env.NEXTAUTH_URL, + DISCORD_CLIENT_ID: process.env.DISCORD_CLIENT_ID, + DISCORD_CLIENT_SECRET: process.env.DISCORD_CLIENT_SECRET, + // NEXT_PUBLIC_CLIENTVAR: process.env.NEXT_PUBLIC_CLIENTVAR, +}; + +// Don't touch the part below +// -------------------------- + +const merged = server.merge(client); + +/** @typedef {z.input} MergedInput */ +/** @typedef {z.infer} MergedOutput */ +/** @typedef {z.SafeParseReturnType} MergedSafeParseReturn */ + +let env = /** @type {MergedOutput} */ (process.env); + +if (!!process.env.SKIP_ENV_VALIDATION == false) { + const isServer = typeof window === "undefined"; + + const parsed = /** @type {MergedSafeParseReturn} */ ( + isServer + ? merged.safeParse(processEnv) // on server we can validate all env vars + : client.safeParse(processEnv) // on client we can only validate the ones that are exposed + ); + + if (parsed.success === false) { + console.error( + "❌ Invalid environment variables:", + parsed.error.flatten().fieldErrors, + ); + throw new Error("Invalid environment variables"); + } + + env = new Proxy(parsed.data, { + get(target, prop) { + if (typeof prop !== "string") return undefined; + // Throw a descriptive error if a server-side env var is accessed on the client + // Otherwise it would just be returning `undefined` and be annoying to debug + if (!isServer && !prop.startsWith("NEXT_PUBLIC_")) + throw new Error( + process.env.NODE_ENV === "production" + ? "❌ Attempted to access a server-side environment variable on the client" + : `❌ Attempted to access server-side environment variable '${prop}' on the client`, + ); + return target[/** @type {keyof typeof target} */ (prop)]; + }, + }); +} + +export { env }; diff --git a/src/client/src/pages/_app.tsx b/src/client/src/pages/_app.tsx new file mode 100644 index 0000000..81e8bcc --- /dev/null +++ b/src/client/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/client/src/pages/api/auth/[...nextauth].ts b/src/client/src/pages/api/auth/[...nextauth].ts new file mode 100644 index 0000000..8aefbb6 --- /dev/null +++ b/src/client/src/pages/api/auth/[...nextauth].ts @@ -0,0 +1,4 @@ +import NextAuth from "next-auth"; +import { authOptions } from "~/server/auth"; + +export default NextAuth(authOptions); diff --git a/src/client/src/pages/api/trpc/[trpc].ts b/src/client/src/pages/api/trpc/[trpc].ts new file mode 100644 index 0000000..3c744a0 --- /dev/null +++ b/src/client/src/pages/api/trpc/[trpc].ts @@ -0,0 +1,19 @@ +import { createNextApiHandler } from "@trpc/server/adapters/next"; + +import { env } from "~/env.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/client/src/pages/index.tsx b/src/client/src/pages/index.tsx new file mode 100644 index 0000000..97ec863 --- /dev/null +++ b/src/client/src/pages/index.tsx @@ -0,0 +1,83 @@ +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/client/src/server/api/root.ts b/src/client/src/server/api/root.ts new file mode 100644 index 0000000..93fba92 --- /dev/null +++ b/src/client/src/server/api/root.ts @@ -0,0 +1,14 @@ +import { createTRPCRouter } from "~/server/api/trpc"; +import { exampleRouter } from "~/server/api/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/client/src/server/api/routers/example.ts b/src/client/src/server/api/routers/example.ts new file mode 100644 index 0000000..73de162 --- /dev/null +++ b/src/client/src/server/api/routers/example.ts @@ -0,0 +1,25 @@ +import { z } from "zod"; + +import { + createTRPCRouter, + publicProcedure, + protectedProcedure, +} from "~/server/api/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/client/src/server/api/trpc.ts b/src/client/src/server/api/trpc.ts new file mode 100644 index 0000000..320ffd6 --- /dev/null +++ b/src/client/src/server/api/trpc.ts @@ -0,0 +1,130 @@ +/** + * 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 when processing a request, like the database, the session, etc. + */ +import { type CreateNextContextOptions } from "@trpc/server/adapters/next"; +import { type Session } from "next-auth"; + +import { getServerAuthSession } from "~/server/auth"; +import { prisma } from "~/server/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 don't 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 will use in your router. It will be used to process every request + * that goes through your tRPC endpoint. + * + * @see https://trpc.io/docs/context + */ +export const createTRPCContext = async (opts: CreateNextContextOptions) => { + const { req, res } = opts; + + // Get the session from the server using the 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. We also parse + * ZodErrors so that you get typesafety on the frontend if your procedure fails due to validation + * errors on the backend. + */ +import { initTRPC, TRPCError } from "@trpc/server"; +import superjson from "superjson"; +import { ZodError } from "zod"; + +const t = initTRPC.context().create({ + transformer: superjson, + errorFormatter({ shape, error }) { + return { + ...shape, + data: { + ...shape.data, + zodError: + error.cause instanceof ZodError ? error.cause.flatten() : null, + }, + }; + }, +}); + +/** + * 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" directory. + */ + +/** + * This is how you create new routers and sub-routers in your tRPC API. + * + * @see https://trpc.io/docs/router + */ +export const createTRPCRouter = t.router; + +/** + * Public (unauthenticated) 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 (authenticated) 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/client/src/server/auth.ts b/src/client/src/server/auth.ts new file mode 100644 index 0000000..7e6d826 --- /dev/null +++ b/src/client/src/server/auth.ts @@ -0,0 +1,76 @@ +import { type GetServerSidePropsContext } from "next"; +import { + getServerSession, + type NextAuthOptions, + type DefaultSession, +} from "next-auth"; +import DiscordProvider from "next-auth/providers/discord"; +import { PrismaAdapter } from "@next-auth/prisma-adapter"; +import { env } from "~/env.mjs"; +import { prisma } from "~/server/db"; + +/** + * Module augmentation for `next-auth` types. Allows us to add custom properties to the `session` + * object and keep type safety. + * + * @see https://next-auth.js.org/getting-started/typescript#module-augmentation + */ +declare module "next-auth" { + interface Session extends DefaultSession { + user: { + id: string; + // ...other properties + // role: UserRole; + } & DefaultSession["user"]; + } + + // interface User { + // // ...other properties + // // role: UserRole; + // } +} + +/** + * Options for NextAuth.js used to configure adapters, providers, callbacks, etc. + * + * @see https://next-auth.js.org/configuration/options + */ +export const authOptions: NextAuthOptions = { + callbacks: { + session({ session, user }) { + if (session.user) { + session.user.id = user.id; + // session.user.role = user.role; <-- put other properties on the session here + } + return session; + }, + }, + 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 + */ + ], +}; + +/** + * Wrapper for `getServerSession` so that you don't need to import the `authOptions` in every file. + * + * @see https://next-auth.js.org/configuration/nextjs + */ +export const getServerAuthSession = (ctx: { + req: GetServerSidePropsContext["req"]; + res: GetServerSidePropsContext["res"]; +}) => { + return getServerSession(ctx.req, ctx.res, authOptions); +}; diff --git a/src/client/src/server/db.ts b/src/client/src/server/db.ts new file mode 100644 index 0000000..f3d7be3 --- /dev/null +++ b/src/client/src/server/db.ts @@ -0,0 +1,14 @@ +import { PrismaClient } from "@prisma/client"; + +import { env } from "~/env.mjs"; + +const globalForPrisma = globalThis as unknown as { prisma: PrismaClient }; + +export const prisma = + globalForPrisma.prisma || + new PrismaClient({ + log: + env.NODE_ENV === "development" ? ["query", "error", "warn"] : ["error"], + }); + +if (env.NODE_ENV !== "production") globalForPrisma.prisma = prisma; diff --git a/src/client/src/types/index.tsx b/src/client/src/types/index.tsx deleted file mode 100644 index ab5cce3..0000000 --- a/src/client/src/types/index.tsx +++ /dev/null @@ -1,18 +0,0 @@ -// Path: types/index.tsx - -export interface IBook { - book_id: string - title: string - author: string - categories: string - cover: string - pages: string - progress: string - file_name: string - description: string - date: string - rights: string - tags: string - identifier: string - publisher: string -} diff --git a/src/client/src/utils/api.ts b/src/client/src/utils/api.ts new file mode 100644 index 0000000..f4f4ad5 --- /dev/null +++ b/src/client/src/utils/api.ts @@ -0,0 +1,68 @@ +/** + * This is the client-side entrypoint for your tRPC API. It is used to create the `api` object which + * contains the Next.js App-wrapper, as well as your type-safe 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 type-safe 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/src/client/tailwind.config.cjs b/src/client/tailwind.config.cjs new file mode 100644 index 0000000..a82e7e9 --- /dev/null +++ b/src/client/tailwind.config.cjs @@ -0,0 +1,10 @@ +/** @type {import('tailwindcss').Config} */ +const config = { + content: ["./src/**/*.{js,ts,jsx,tsx}"], + theme: { + extend: {}, + }, + plugins: [], +}; + +module.exports = config; diff --git a/src/client/theme.tsx b/src/client/theme.tsx deleted file mode 100644 index 78f5127..0000000 --- a/src/client/theme.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import { createTheme } from @material-ui/core/styles; - -const theme = createTheme({ - palette: { - primary: { - main: '#556cd6', - }, - secondary: { - main: '#19857b', - }, - error: { - main: '#f44336', - }, - background: { - default: '#fff', - }, - }, -}); - -export { theme }; diff --git a/src/client/tsconfig.json b/src/client/tsconfig.json index 0c7555f..03ebb74 100644 --- a/src/client/tsconfig.json +++ b/src/client/tsconfig.json @@ -1,8 +1,9 @@ { "compilerOptions": { - "target": "es5", + "target": "es2017", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, + "checkJs": true, "skipLibCheck": true, "strict": true, "forceConsistentCasingInFileNames": true, @@ -14,15 +15,19 @@ "isolatedModules": true, "jsx": "preserve", "incremental": true, - "plugins": [ - { - "name": "next" - } - ], + "noUncheckedIndexedAccess": true, + "baseUrl": ".", "paths": { - "@/*": ["./src/*"] + "~/*": ["./src/*"] } }, - "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], + "include": [ + ".eslintrc.cjs", + "next-env.d.ts", + "**/*.ts", + "**/*.tsx", + "**/*.cjs", + "**/*.mjs" + ], "exclude": ["node_modules"] }
- - -
- Next.js Logo -
- 13 -
-
- - -