Initial commit

This commit is contained in:
Meier Lukas
2023-12-08 22:35:15 +01:00
commit a2cedf73c0
74 changed files with 15357 additions and 0 deletions

24
.env.example Normal file
View File

@@ -0,0 +1,24 @@
# 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.
# The database URL is used to connect to your PlanetScale database.
DB_HOST='aws.connect.psdb.cloud'
DB_NAME='YOUR_DB_NAME'
DB_USERNAME=''
DB_PASSWORD='pscale_pw_'
# @see https://next-auth.js.org/configuration/options#nextauth_url
AUTH_URL='http://localhost:3000'
AUTH_REDIRECT_PROXY_URL="http://localhost:3001/api"
# You can generate the secret via 'openssl rand -base64 32' on Unix
# @see https://next-auth.js.org/configuration/options#secret
AUTH_SECRET='supersecret'
# Preconfigured Discord OAuth provider, works out-of-the-box
# @see https://next-auth.js.org/providers/discord
AUTH_DISCORD_ID=''
AUTH_DISCORD_SECRET=''

3
.github/FUNDING.yml vendored Normal file
View File

@@ -0,0 +1,3 @@
# These are supported funding model platforms
github: juliusmarminge

37
.github/ISSUE_TEMPLATE/bug_report.yml vendored Normal file
View File

@@ -0,0 +1,37 @@
name: 🐞 Bug Report
description: Create a bug report to help us improve
title: "bug: "
labels: ["🐞❔ unconfirmed bug"]
body:
- type: textarea
attributes:
label: Provide environment information
description: |
Run this command in your project root and paste the results in a code block:
```bash
npx envinfo --system --binaries
```
validations:
required: true
- type: textarea
attributes:
label: Describe the bug
description: A clear and concise description of the bug, as well as what you expected to happen when encountering it.
validations:
required: true
- type: input
attributes:
label: Link to reproduction
description: Please provide a link to a reproduction of the bug. Issues without a reproduction repo may be ignored.
validations:
required: true
- type: textarea
attributes:
label: To reproduce
description: Describe how to reproduce your bug. Steps, code snippets, reproduction repos etc.
validations:
required: true
- type: textarea
attributes:
label: Additional information
description: Add any other information related to the bug here, screenshots if applicable.

View File

@@ -0,0 +1,29 @@
# This template is heavily inspired by the Next.js's template:
# See here: https://github.com/vercel/next.js/blob/canary/.github/ISSUE_TEMPLATE/3.feature_request.yml
name: 🛠 Feature Request
description: Create a feature request for the core packages
title: "feat: "
labels: ["✨ enhancement"]
body:
- type: markdown
attributes:
value: |
Thank you for taking the time to file a feature request. Please fill out this form as completely as possible.
- type: textarea
attributes:
label: Describe the feature you'd like to request
description: Please describe the feature as clear and concise as possible. Remember to add context as to why you believe this feature is needed.
validations:
required: true
- type: textarea
attributes:
label: Describe the solution you'd like to see
description: Please describe the solution you would like to see. Adding example usage is a good way to provide context.
validations:
required: true
- type: textarea
attributes:
label: Additional information
description: Add any other information related to the feature here. If your feature request is related to any issues or discussions, link them here.

13
.github/renovate.json vendored Normal file
View File

@@ -0,0 +1,13 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": ["config:base"],
"packageRules": [
{
"matchPackagePatterns": ["^@acme/"],
"enabled": false
}
],
"updateInternalDeps": true,
"rangeStrategy": "bump",
"automerge": true
}

57
.github/workflows/ci.yml vendored Normal file
View File

@@ -0,0 +1,57 @@
name: CI
on:
pull_request:
branches: ["*"]
push:
branches: ["main"]
merge_group:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/master' }}
# You can leverage Vercel Remote Caching with Turbo to speed up your builds
# @link https://turborepo.org/docs/core-concepts/remote-caching#remote-caching-on-vercel-builds
env:
FORCE_COLOR: 3
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ vars.TURBO_TEAM }}
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup
uses: ./tooling/github/setup
- name: Copy env
shell: bash
run: cp .env.example .env
- name: Lint
run: pnpm lint && pnpm lint:ws
format:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup
uses: ./tooling/github/setup
- name: Format
run: pnpm format
typecheck:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup
uses: ./tooling/github/setup
- name: Typecheck
run: turbo typecheck

50
.gitignore vendored Normal file
View File

@@ -0,0 +1,50 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
node_modules
.pnp
.pnp.js
# testing
coverage
# next.js
.next/
out/
next-env.d.ts
# nitro
.nitro/
.output/
# expo
.expo/
dist/
expo-env.d.ts
apps/expo/.gitignore
# production
build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# local env files
.env
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
# turbo
.turbo

5
.npmrc Normal file
View File

@@ -0,0 +1,5 @@
# Expo doesn't play nice with pnpm by default.
# The symbolic links of pnpm break the rules of Expo monorepos.
# @link https://docs.expo.dev/guides/monorepos/#common-issues
node-linker=hoisted
strict-peer-dependencies=false

1
.nvmrc Normal file
View File

@@ -0,0 +1 @@
18.18.2

9
.vscode/extensions.json vendored Normal file
View File

@@ -0,0 +1,9 @@
{
"recommendations": [
"bradlc.vscode-tailwindcss",
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"expo.vscode-expo-tools",
"yoavbls.pretty-ts-errors"
]
}

13
.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,13 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Next.js",
"type": "node-terminal",
"request": "launch",
"command": "pnpm dev",
"cwd": "${workspaceFolder}/apps/nextjs/",
"skipFiles": ["<node_internals>/**"]
}
]
}

7
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,7 @@
{
"eslint.workingDirectories": [
{
"mode": "auto"
}
]
}

21
LICENSE Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Julius Marminge
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

245
README.md Normal file
View File

@@ -0,0 +1,245 @@
# create-t3-turbo
> **Note**
> Due to high demand, this repo now uses the `app` directory with some new experimental features. If you want to use the more traditional `pages` router, [check out the repo before the update](https://github.com/t3-oss/create-t3-turbo/tree/414aff131ca124573e721f3779df3edb64989fd4).
> **Note**
> OAuth deployments are now working for preview deployments. Read [deployment guide](https://github.com/t3-oss/create-t3-turbo#auth-proxy) and [check out the source](./apps/auth-proxy) to learn more!
## Installation
There are two ways of initializing an app using the `create-t3-turbo` starter. You can either use this repository as a template:
![use-as-template](https://github.com/t3-oss/create-t3-turbo/assets/51714798/bb6c2e5d-d8b6-416e-aeb3-b3e50e2ca994)
or use Turbo's CLI to init your project (use PNPM as package manager):
```bash
npx create-turbo@latest -e https://github.com/t3-oss/create-t3-turbo
```
## About
Ever wondered how to migrate your T3 application into a monorepo? Stop right here! This is the perfect starter repo to get you running with the perfect stack!
It uses [Turborepo](https://turborepo.org) and contains:
```text
.github
└─ workflows
└─ CI with pnpm cache setup
.vscode
└─ Recommended extensions and settings for VSCode users
apps
├─ auth-proxy
| ├─ Nitro server to proxy OAuth requests in preview deployments
| └─ Uses Auth.js Core
├─ expo
| ├─ Expo SDK 49
| ├─ React Native using React 18
| ├─ Navigation using Expo Router
| ├─ Tailwind using Nativewind
| └─ Typesafe API calls using tRPC
└─ next.js
├─ Next.js 14
├─ React 18
├─ Tailwind CSS
└─ E2E Typesafe API Server & Client
packages
├─ api
| └─ tRPC v10 router definition
├─ auth
| └─ Authentication using next-auth. **NOTE: Only for Next.js app, not Expo**
└─ db
└─ Typesafe db calls using Drizzle & Planetscale
tooling
├─ eslint
| └─ shared, fine-grained, eslint presets
├─ prettier
| └─ shared prettier configuration
├─ tailwind
| └─ shared tailwind configuration
└─ typescript
└─ shared tsconfig you can extend from
```
> In this template, we use `@acme` as a placeholder for package names. As a user, you might want to replace it with your own organization or project name. You can use find-and-replace to change all the instances of `@acme` to something like `@my-company` or `@project-name`.
## Quick Start
> **Note**
> The [db](./packages/db) package is preconfigured to use PlanetScale and is **edge-bound** with the [database.js](https://github.com/planetscale/database-js) driver. If you're using something else, make the necesary modifications to the [schema](./packages/db/schema) as well as the [client](./packages/db/index.ts) and the [drizzle config](./packages/db/drizzle.config.ts). If you want to switch to non-edge database driver, remove `export const runtime = "edge";` [from all pages and api routes](https://github.com/t3-oss/create-t3-turbo/issues/634#issuecomment-1730240214).
To get it running, follow the steps below:
### 1. Setup dependencies
```bash
# Install dependencies
pnpm i
# Configure environment variables
# There is an `.env.example` in the root directory you can use for reference
cp .env.example .env
# Push the Drizzle schema to the database
pnpm db:push
```
### 2. Configure Expo `dev`-script
#### Use iOS Simulator
1. Make sure you have XCode and XCommand Line Tools installed [as shown on expo docs](https://docs.expo.dev/workflow/ios-simulator).
> **NOTE:** If you just installed XCode, or if you have updated it, you need to open the simulator manually once. Run `npx expo start` in the root dir, and then enter `I` to launch Expo Go. After the manual launch, you can run `pnpm dev` in the root directory.
```diff
+ "dev": "expo start --ios",
```
2. Run `pnpm dev` at the project root folder.
#### Use Android Emulator
1. Install Android Studio tools [as shown on expo docs](https://docs.expo.dev/workflow/android-studio-emulator).
2. Change the `dev` script at `apps/expo/package.json` to open the Android emulator.
```diff
+ "dev": "expo start --android",
```
3. Run `pnpm dev` at the project root folder.
> **TIP:** It might be easier to run each app in separate terminal windows so you get the logs from each app separately. This is also required if you want your terminals to be interactive, e.g. to access the Expo QR code. You can run `pnpm --filter expo dev` and `pnpm --filter nextjs dev` to run each app in a separate terminal window.
### 3. When it's time to add a new package
To add a new package, simply run `pnpm turbo gen init` in the monorepo root. This will prompt you for a package name as well as if you want to install any dependencies to the new package (of course you can also do this yourself later).
The generator sets up the `package.json`, `tsconfig.json` and a `index.ts`, as well as configures all the necessary configurations for tooling around your package such as formatting, linting and typechecking. When the package is created, you're ready to go build out the package.
## FAQ
### Does the starter include Solito?
No. Solito will not be included in this repo. It is a great tool if you want to share code between your Next.js and Expo app. However, the main purpose of this repo is not the integration between Next.js and Expo — it's the codesplitting of your T3 App into a monorepo. The Expo app is just a bonus example of how you can utilize the monorepo with multiple apps but can just as well be any app such as Vite, Electron, etc.
Integrating Solito into this repo isn't hard, and there are a few [offical templates](https://github.com/nandorojo/solito/tree/master/example-monorepos) by the creators of Solito that you can use as a reference.
### What auth solution should I use instead of Next-Auth.js for Expo?
I've left this kind of open for you to decide. Some options are [Clerk](https://clerk.dev), [Supabase Auth](https://supabase.com/docs/guides/auth), [Firebase Auth](https://firebase.google.com/docs/auth/) or [Auth0](https://auth0.com/docs). Note that if you're dropping the Expo app for something more "browser-like", you can still use Next-Auth.js for those. [See an example in a Plasmo Chrome Extension here](https://github.com/t3-oss/create-t3-turbo/tree/chrome/apps/chrome).
The Clerk.dev team even made an [official template repository](https://github.com/clerkinc/t3-turbo-and-clerk) integrating Clerk.dev with this repo.
During Launch Week 7, Supabase [announced their fork](https://supabase.com/blog/launch-week-7-community-highlights#t3-turbo-x-supabase) of this repo integrating it with their newly announced auth improvements. You can check it out [here](https://github.com/supabase-community/create-t3-turbo).
### Does this pattern leak backend code to my client applications?
No, it does not. The `api` package should only be a production dependency in the Next.js application where it's served. The Expo app, and all other apps you may add in the future, should only add the `api` package as a dev dependency. This lets you have full typesafety in your client applications, while keeping your backend code safe.
If you need to share runtime code between the client and server, such as input validation schemas, you can create a separate `shared` package for this and import it on both sides.
## Deployment
### Next.js
#### Prerequisites
> **Note**
> Please note that the Next.js application with tRPC must be deployed in order for the Expo app to communicate with the server in a production environment.
#### Deploy to Vercel
Let's deploy the Next.js application to [Vercel](https://vercel.com). If you've never deployed a Turborepo app there, don't worry, the steps are quite straightforward. You can also read the [official Turborepo guide](https://vercel.com/docs/concepts/monorepos/turborepo) on deploying to Vercel.
1. Create a new project on Vercel, select the `apps/nextjs` folder as the root directory. Vercel's zero-config system should handle all configurations for you.
2. Add your `DATABASE_URL` environment variable.
3. Done! Your app should successfully deploy. Assign your domain and use that instead of `localhost` for the `url` in the Expo app so that your Expo app can communicate with your backend when you are not in development.
### Auth Proxy
The auth proxy is a Nitro server that proxies OAuth requests in preview deployments. This is required for the Next.js app to be able to authenticate users in preview deployments. The auth proxy is not used for OAuth requests in production deployments. To get it running, it's easiest to use Vercel Edge functions. See the [Nitro docs](https://nitro.unjs.io/deploy/providers/vercel#vercel-edge-functions) for how to deploy Nitro to Vercel.
Then, there are some environment variables you need to set in order to get OAuth working:
- For the Next.js app, set `AUTH_REDIRECT_PROXY_URL` to the URL of the auth proxy.
- For the auth proxy server, set `AUTH_REDIRECT_PROXY_URL` to the same as above, as well as `AUTH_DISCORD_ID`, `AUTH_DISCORD_SECRET` (or the equivalent for your OAuth provider(s)). Lastly, set `AUTH_SECRET` **to the same value as in the Next.js app** for preview environments.
Read more about the setup in [the auth proxy README](./apps/auth-proxy/README.md).
### Expo
Deploying your Expo application works slightly differently compared to Next.js on the web. Instead of "deploying" your app online, you need to submit production builds of your app to app stores, like [Apple App Store](https://www.apple.com/app-store) and [Google Play](https://play.google.com/store/apps). You can read the full [guide to distributing your app](https://docs.expo.dev/distribution/introduction), including best practices, in the Expo docs.
1. Make sure to modify the `getBaseUrl` function to point to your backend's production URL:
<https://github.com/t3-oss/create-t3-turbo/blob/656965aff7db271e5e080242c4a3ce4dad5d25f8/apps/expo/src/utils/api.tsx#L20-L37>
2. Let's start by setting up [EAS Build](https://docs.expo.dev/build/introduction), which is short for Expo Application Services. The build service helps you create builds of your app, without requiring a full native development setup. The commands below are a summary of [Creating your first build](https://docs.expo.dev/build/setup).
```bash
# Install the EAS CLI
pnpm add -g eas-cli
# Log in with your Expo account
eas login
# Configure your Expo app
cd apps/expo
eas build:configure
```
3. After the initial setup, you can create your first build. You can build for Android and iOS platforms and use different [`eas.json` build profiles](https://docs.expo.dev/build-reference/eas-json) to create production builds or development, or test builds. Let's make a production build for iOS.
```bash
eas build --platform ios --profile production
```
> If you don't specify the `--profile` flag, EAS uses the `production` profile by default.
4. Now that you have your first production build, you can submit this to the stores. [EAS Submit](https://docs.expo.dev/submit/introduction) can help you send the build to the stores.
```bash
eas submit --platform ios --latest
```
> You can also combine build and submit in a single command, using `eas build ... --auto-submit`.
5. Before you can get your app in the hands of your users, you'll have to provide additional information to the app stores. This includes screenshots, app information, privacy policies, etc. _While still in preview_, [EAS Metadata](https://docs.expo.dev/eas/metadata) can help you with most of this information.
6. Once everything is approved, your users can finally enjoy your app. Let's say you spotted a small typo; you'll have to create a new build, submit it to the stores, and wait for approval before you can resolve this issue. In these cases, you can use EAS Update to quickly send a small bugfix to your users without going through this long process. Let's start by setting up EAS Update.
The steps below summarize the [Getting started with EAS Update](https://docs.expo.dev/eas-update/getting-started/#configure-your-project) guide.
```bash
# Add the `expo-updates` library to your Expo app
cd apps/expo
pnpm expo install expo-updates
# Configure EAS Update
eas update:configure
```
7. Before we can send out updates to your app, you have to create a new build and submit it to the app stores. For every change that includes native APIs, you have to rebuild the app and submit the update to the app stores. See steps 2 and 3.
8. Now that everything is ready for updates, let's create a new update for `production` builds. With the `--auto` flag, EAS Update uses your current git branch name and commit message for this update. See [How EAS Update works](https://docs.expo.dev/eas-update/how-eas-update-works/#publishing-an-update) for more information.
```bash
cd apps/expo
eas update --auto
```
> Your OTA (Over The Air) updates must always follow the app store's rules. You can't change your app's primary functionality without getting app store approval. But this is a fast way to update your app for minor changes and bug fixes.
9. Done! Now that you have created your production build, submitted it to the stores, and installed EAS Update, you are ready for anything!
## References
The stack originates from [create-t3-app](https://github.com/t3-oss/create-t3-app).
A [blog post](https://jumr.dev/blog/t3-turbo) where I wrote how to migrate a T3 app into this.

View File

@@ -0,0 +1,7 @@
AUTH_SECRET=""
AUTH_DISCORD_ID=""
AUTH_DISCORD_SECRET=""
AUTH_REDIRECT_PROXY_URL=""
NITRO_PRESET="vercel_edge"

16
apps/auth-proxy/README.md Normal file
View File

@@ -0,0 +1,16 @@
# Auth Proxy
This is a simple proxy server that enables OAuth authentication for preview environments.
## Setup
Deploy it somewhere (Vercel is a one-click, zero-config option) and set the following environment variables:
- `AUTH_DISCORD_ID` - The Discord OAuth client ID
- `AUTH_DISCORD_SECRET` - The Discord OAuth client secret
- `AUTH_REDIRECT_PROXY_URL` - The URL of this proxy server
- `AUTH_SECRET` - Your secret
Make sure the `AUTH_SECRET` and `AUTH_REDIRECT_PROXY_URL` match the values set for the main application's deployment for preview environments, and that you're using the same OAuth credentials for the proxy and the application's preview environment. The lines below shows what values should match eachother in both deployments.
![Environment variables setup](https://github.com/t3-oss/create-t3-turbo/assets/51714798/5fadd3f5-f705-459a-82ab-559a3df881d0)

View File

@@ -0,0 +1,33 @@
{
"name": "@acme/auth-proxy",
"private": true,
"type": "module",
"scripts": {
"build": "nitro build",
"clean": "rm -rf .turbo node_modules",
"dev": "nitro dev --port 3001",
"lint": "eslint .",
"format": "prettier --check . --ignore-path ../../.gitignore",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@auth/core": "^0.18.4"
},
"devDependencies": {
"@acme/eslint-config": "workspace:^0.2.0",
"@acme/prettier-config": "workspace:^0.1.0",
"@acme/tailwind-config": "workspace:^0.1.0",
"@acme/tsconfig": "workspace:^0.1.0",
"eslint": "^8.53.0",
"nitropack": "^2.8.1",
"prettier": "^3.1.0",
"typescript": "^5.3.3"
},
"eslintConfig": {
"root": true,
"extends": [
"@acme/eslint-config/base"
]
},
"prettier": "@acme/prettier-config"
}

View File

@@ -0,0 +1,17 @@
import { Auth } from "@auth/core";
import Discord from "@auth/core/providers/discord";
import { eventHandler, toWebRequest } from "h3";
export default eventHandler(async (event) =>
Auth(toWebRequest(event), {
secret: process.env.AUTH_SECRET,
trustHost: !!process.env.VERCEL,
redirectProxyUrl: process.env.AUTH_REDIRECT_PROXY_URL,
providers: [
Discord({
clientId: process.env.AUTH_DISCORD_ID,
clientSecret: process.env.AUTH_DISCORD_SECRET,
}),
],
}),
);

View File

@@ -0,0 +1,4 @@
{
"extends": "@acme/tsconfig/base.json",
"include": ["routes"]
}

28
apps/nextjs/README.md Normal file
View File

@@ -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)
- [Drizzle](https://orm.drizzle.team)
- [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) and [Docker](https://create.t3.gg/en/deployment/docker) for more information.

View File

@@ -0,0 +1,15 @@
// Importing env files here to validate on build
import "./src/env.mjs";
import "@acme/auth/env.mjs";
/** @type {import("next").NextConfig} */
const config = {
reactStrictMode: true,
/** Enables hot reloading for local packages without a build step */
transpilePackages: ["@acme/api", "@acme/auth", "@acme/db"],
/** We already do linting and typechecking as separate tasks in CI */
eslint: { ignoreDuringBuilds: true },
typescript: { ignoreBuildErrors: true },
};
export default config;

56
apps/nextjs/package.json Normal file
View File

@@ -0,0 +1,56 @@
{
"name": "@acme/nextjs",
"version": "0.1.0",
"private": true,
"scripts": {
"build": "pnpm with-env next build",
"clean": "git clean -xdf .next .turbo node_modules",
"dev": "pnpm with-env next dev",
"lint": "dotenv -v SKIP_ENV_VALIDATION=1 next lint",
"format": "prettier --check . --ignore-path ../../.gitignore",
"start": "pnpm with-env next start",
"typecheck": "tsc --noEmit",
"with-env": "dotenv -e ../../.env --"
},
"dependencies": {
"@acme/api": "workspace:^0.1.0",
"@acme/auth": "workspace:^0.1.0",
"@acme/db": "workspace:^0.1.0",
"@t3-oss/env-nextjs": "^0.7.1",
"@tanstack/react-query": "^5.8.7",
"@tanstack/react-query-devtools": "^5.8.7",
"@tanstack/react-query-next-experimental": "5.8.7",
"@trpc/client": "next",
"@trpc/next": "next",
"@trpc/react-query": "next",
"@trpc/server": "next",
"next": "^14.0.3",
"react": "18.2.0",
"react-dom": "18.2.0",
"superjson": "2.2.1",
"zod": "^3.22.2"
},
"devDependencies": {
"@acme/eslint-config": "workspace:^0.2.0",
"@acme/prettier-config": "workspace:^0.1.0",
"@acme/tailwind-config": "workspace:^0.1.0",
"@acme/tsconfig": "workspace:^0.1.0",
"@types/node": "^18.18.13",
"@types/react": "^18.2.42",
"@types/react-dom": "^18.2.17",
"dotenv-cli": "^7.3.0",
"eslint": "^8.53.0",
"prettier": "^3.1.0",
"tailwindcss": "3.3.5",
"typescript": "^5.3.3"
},
"eslintConfig": {
"root": true,
"extends": [
"@acme/eslint-config/base",
"@acme/eslint-config/nextjs",
"@acme/eslint-config/react"
]
},
"prettier": "@acme/prettier-config"
}

View File

@@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

View File

@@ -0,0 +1,13 @@
<svg width="258" height="198" viewBox="0 0 258 198" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_1_12)">
<path d="M165.269 24.0976L188.481 -0.000411987H0V24.0976H165.269Z" fill="black"/>
<path d="M163.515 95.3516L253.556 2.71059H220.74L145.151 79.7886L163.515 95.3516Z" fill="black"/>
<path d="M233.192 130.446C233.192 154.103 214.014 173.282 190.357 173.282C171.249 173.282 155.047 160.766 149.534 143.467L146.159 132.876L126.863 152.171L128.626 156.364C138.749 180.449 162.568 197.382 190.357 197.382C227.325 197.382 257.293 167.414 257.293 130.446C257.293 105.965 243.933 84.7676 224.49 73.1186L219.929 70.3856L202.261 88.2806L210.322 92.5356C223.937 99.7236 233.192 114.009 233.192 130.446Z" fill="black"/>
<path d="M87.797 191.697V44.6736H63.699V191.697H87.797Z" fill="black"/>
</g>
<defs>
<clipPath id="clip0_1_12">
<rect width="258" height="198" fill="white"/>
</clipPath>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 923 B

View File

@@ -0,0 +1,39 @@
import { auth, signIn, signOut } from "@acme/auth";
export async function AuthShowcase() {
const session = await auth();
if (!session) {
return (
<form
action={async () => {
"use server";
await signIn("discord");
}}
>
<button className="rounded-full bg-white/10 px-10 py-3 font-semibold no-underline transition hover:bg-white/20">
Sign in with Discord
</button>
</form>
);
}
return (
<div className="flex flex-col items-center justify-center gap-4">
<p className="text-center text-2xl text-white">
{session && <span>Logged in as {session.user.name}</span>}
</p>
<form
action={async () => {
"use server";
await signOut();
}}
>
<button className="rounded-full bg-white/10 px-10 py-3 font-semibold no-underline transition hover:bg-white/20">
Sign out
</button>
</form>
</div>
);
}

View File

@@ -0,0 +1,148 @@
"use client";
import { useState } from "react";
import { api } from "~/utils/api";
import type { RouterOutputs } from "~/utils/api";
export function CreatePostForm() {
const context = api.useContext();
const [title, setTitle] = useState("");
const [content, setContent] = useState("");
const { mutateAsync: createPost, error } = api.post.create.useMutation({
async onSuccess() {
setTitle("");
setContent("");
await context.post.all.invalidate();
},
});
return (
<form
className="flex w-full max-w-2xl flex-col"
onSubmit={async (e) => {
e.preventDefault();
try {
await createPost({
title,
content,
});
setTitle("");
setContent("");
await context.post.all.invalidate();
} catch {
// noop
}
}}
>
<input
className="mb-2 rounded bg-white/10 p-2 text-white"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Title"
/>
{error?.data?.zodError?.fieldErrors.title && (
<span className="mb-2 text-red-500">
{error.data.zodError.fieldErrors.title}
</span>
)}
<input
className="mb-2 rounded bg-white/10 p-2 text-white"
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="Content"
/>
{error?.data?.zodError?.fieldErrors.content && (
<span className="mb-2 text-red-500">
{error.data.zodError.fieldErrors.content}
</span>
)}
{}
<button type="submit" className="rounded bg-pink-400 p-2 font-bold">
Create
</button>
{error?.data?.code === "UNAUTHORIZED" && (
<span className="mt-2 text-red-500">You must be logged in to post</span>
)}
</form>
);
}
export function PostList() {
const [posts] = api.post.all.useSuspenseQuery();
if (posts.length === 0) {
return (
<div className="relative flex w-full flex-col gap-4">
<PostCardSkeleton pulse={false} />
<PostCardSkeleton pulse={false} />
<PostCardSkeleton pulse={false} />
<div className="absolute inset-0 flex flex-col items-center justify-center bg-black/10">
<p className="text-2xl font-bold text-white">No posts yet</p>
</div>
</div>
);
}
return (
<div className="flex w-full flex-col gap-4">
{posts.map((p) => {
return <PostCard key={p.id} post={p} />;
})}
</div>
);
}
export function PostCard(props: {
post: RouterOutputs["post"]["all"][number];
}) {
const context = api.useContext();
const deletePost = api.post.delete.useMutation();
return (
<div className="flex flex-row rounded-lg bg-white/10 p-4 transition-all hover:scale-[101%]">
<div className="flex-grow">
<h2 className="text-2xl font-bold text-pink-400">{props.post.title}</h2>
<p className="mt-2 text-sm">{props.post.content}</p>
</div>
<div>
<button
className="cursor-pointer text-sm font-bold uppercase text-pink-400"
onClick={async () => {
await deletePost.mutateAsync(props.post.id);
await context.post.all.invalidate();
}}
>
Delete
</button>
</div>
</div>
);
}
export function PostCardSkeleton(props: { pulse?: boolean }) {
const { pulse = true } = props;
return (
<div className="flex flex-row rounded-lg bg-white/10 p-4 transition-all hover:scale-[101%]">
<div className="flex-grow">
<h2
className={`w-1/4 rounded bg-pink-400 text-2xl font-bold ${
pulse && "animate-pulse"
}`}
>
&nbsp;
</h2>
<p
className={`mt-2 w-1/3 rounded bg-current text-sm ${
pulse && "animate-pulse"
}`}
>
&nbsp;
</p>
</div>
</div>
);
}

View File

@@ -0,0 +1,3 @@
export { GET, POST } from "@acme/auth";
export const runtime = "edge";

View File

@@ -0,0 +1,42 @@
import { fetchRequestHandler } from "@trpc/server/adapters/fetch";
import { appRouter, createTRPCContext } from "@acme/api";
import { auth } from "@acme/auth";
export const runtime = "edge";
/**
* Configure basic CORS headers
* You should extend this to match your needs
*/
function setCorsHeaders(res: Response) {
res.headers.set("Access-Control-Allow-Origin", "*");
res.headers.set("Access-Control-Request-Method", "*");
res.headers.set("Access-Control-Allow-Methods", "OPTIONS, GET, POST");
res.headers.set("Access-Control-Allow-Headers", "*");
}
export function OPTIONS() {
const response = new Response(null, {
status: 204,
});
setCorsHeaders(response);
return response;
}
const handler = auth(async (req) => {
const response = await fetchRequestHandler({
endpoint: "/api/trpc",
router: appRouter,
req,
createContext: () => createTRPCContext({ auth: req.auth, req }),
onError({ error, path }) {
console.error(`>>> tRPC Error on '${path}'`, error);
},
});
setCorsHeaders(response);
return response;
});
export { handler as GET, handler as POST };

View File

@@ -0,0 +1,48 @@
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "~/styles/globals.css";
import { headers } from "next/headers";
import { TRPCReactProvider } from "./providers";
const fontSans = Inter({
subsets: ["latin"],
variable: "--font-sans",
});
/**
* Since we're passing `headers()` to the `TRPCReactProvider` we need to
* make the entire app dynamic. You can move the `TRPCReactProvider` further
* down the tree (e.g. /dashboard and onwards) to make part of the app statically rendered.
*/
export const dynamic = "force-dynamic";
export const metadata: Metadata = {
title: "Create T3 Turbo",
description: "Simple monorepo with shared backend for web & mobile apps",
openGraph: {
title: "Create T3 Turbo",
description: "Simple monorepo with shared backend for web & mobile apps",
url: "https://create-t3-turbo.vercel.app",
siteName: "Create T3 Turbo",
},
twitter: {
card: "summary_large_image",
site: "@jullerino",
creator: "@jullerino",
},
};
export default function Layout(props: { children: React.ReactNode }) {
return (
<html lang="en">
<body className={["font-sans", fontSans.variable].join(" ")}>
<TRPCReactProvider headers={headers()}>
{props.children}
</TRPCReactProvider>
</body>
</html>
);
}

View File

@@ -0,0 +1,38 @@
import { Suspense } from "react";
import { AuthShowcase } from "./_components/auth-showcase";
import {
CreatePostForm,
PostCardSkeleton,
PostList,
} from "./_components/posts";
export const runtime = "edge";
export default function HomePage() {
return (
<main className="flex h-screen flex-col items-center bg-gradient-to-b from-[#2e026d] to-[#15162c] text-white">
<div className="container mt-12 flex flex-col items-center justify-center gap-4 py-8">
<h1 className="text-5xl font-extrabold tracking-tight sm:text-[5rem]">
Create <span className="text-pink-400">T3</span> Turbo
</h1>
<AuthShowcase />
<CreatePostForm />
<div className="h-[40vh] w-full max-w-2xl overflow-y-scroll">
<Suspense
fallback={
<div className="flex w-full flex-col gap-4">
<PostCardSkeleton />
<PostCardSkeleton />
<PostCardSkeleton />
</div>
}
>
<PostList />
</Suspense>
</div>
</div>
</main>
);
}

View File

@@ -0,0 +1,66 @@
"use client";
import { useState } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import { ReactQueryStreamedHydration } from "@tanstack/react-query-next-experimental";
import { loggerLink, unstable_httpBatchStreamLink } from "@trpc/client";
import superjson from "superjson";
import { env } from "~/env.mjs";
import { api } from "~/utils/api";
const getBaseUrl = () => {
if (typeof window !== "undefined") return ""; // browser should use relative url
if (env.VERCEL_URL) return env.VERCEL_URL; // SSR should use vercel url
return `http://localhost:${env.PORT}`; // dev SSR should use localhost
};
export function TRPCReactProvider(props: {
children: React.ReactNode;
headers?: Headers;
}) {
const [queryClient] = useState(
() =>
new QueryClient({
defaultOptions: {
queries: {
staleTime: 5 * 1000,
},
},
}),
);
const [trpcClient] = useState(() =>
api.createClient({
transformer: superjson,
links: [
loggerLink({
enabled: (opts) =>
process.env.NODE_ENV === "development" ||
(opts.direction === "down" && opts.result instanceof Error),
}),
unstable_httpBatchStreamLink({
url: `${getBaseUrl()}/api/trpc`,
headers() {
const headers = new Map(props.headers);
headers.set("x-trpc-source", "nextjs-react");
return Object.fromEntries(headers);
},
}),
],
}),
);
return (
<api.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>
<ReactQueryStreamedHydration transformer={superjson}>
{props.children}
</ReactQueryStreamedHydration>
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
</api.Provider>
);
}

45
apps/nextjs/src/env.mjs Normal file
View File

@@ -0,0 +1,45 @@
import { createEnv } from "@t3-oss/env-nextjs";
import { z } from "zod";
export const env = createEnv({
shared: {
VERCEL_URL: z
.string()
.optional()
.transform((v) => (v ? `https://${v}` : undefined)),
PORT: z.coerce.number().default(3000),
},
/**
* Specify your server-side environment variables schema here. This way you can ensure the app isn't
* built with invalid env vars.
*/
server: {
DB_USERNAME: z.string(),
DB_PASSWORD: z.string(),
DB_HOST: z.string(),
DB_NAME: z.string(),
},
/**
* Specify your client-side environment variables schema here.
* For them to be exposed to the client, prefix them with `NEXT_PUBLIC_`.
*/
client: {
// NEXT_PUBLIC_CLIENTVAR: z.string(),
},
/**
* Destructure all variables from `process.env` to make sure they aren't tree-shaken away.
*/
runtimeEnv: {
VERCEL_URL: process.env.VERCEL_URL,
PORT: process.env.PORT,
DB_USERNAME: process.env.DB_USERNAME,
DB_PASSWORD: process.env.DB_PASSWORD,
DB_HOST: process.env.DB_HOST,
DB_NAME: process.env.DB_NAME,
// NEXT_PUBLIC_CLIENTVAR: process.env.NEXT_PUBLIC_CLIENTVAR,
},
skipValidation:
!!process.env.CI ||
!!process.env.SKIP_ENV_VALIDATION ||
process.env.npm_lifecycle_event === "lint",
});

View File

View File

@@ -0,0 +1,7 @@
import { createTRPCReact } from "@trpc/react-query";
import type { AppRouter } from "@acme/api";
export const api = createTRPCReact<AppRouter>();
export { type RouterInputs, type RouterOutputs } from "@acme/api";

17
apps/nextjs/tsconfig.json Normal file
View File

@@ -0,0 +1,17 @@
{
"extends": "@acme/tsconfig/base.json",
"compilerOptions": {
"baseUrl": ".",
"paths": {
"~/*": ["./src/*"]
},
"plugins": [
{
"name": "next"
}
],
"tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json"
},
"include": [".", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}

36
package.json Normal file
View File

@@ -0,0 +1,36 @@
{
"name": "create-t3-turbo",
"private": true,
"engines": {
"node": ">=18.18.2"
},
"packageManager": "pnpm@8.11.0",
"scripts": {
"build": "turbo build",
"clean": "git clean -xdf node_modules",
"clean:workspaces": "turbo clean",
"postinstall": "pnpm lint:ws",
"db:push": "pnpm -F db push",
"db:studio": "pnpm -F db studio",
"dev": "turbo dev --parallel",
"format": "turbo format --continue -- --cache --cache-location node_modules/.cache/.prettiercache",
"format:fix": "turbo format --continue -- --write --cache --cache-location node_modules/.cache/.prettiercache",
"lint": "turbo lint --continue -- --cache --cache-location node_modules/.cache/.eslintcache",
"lint:fix": "turbo lint --continue -- --fix --cache --cache-location node_modules/.cache/.eslintcache",
"lint:ws": "pnpm dlx sherif@latest",
"typecheck": "turbo typecheck"
},
"devDependencies": {
"@acme/prettier-config": "workspace:^0.1.0",
"@turbo/gen": "^1.10.16",
"prettier": "^3.1.0",
"turbo": "^1.10.16",
"typescript": "^5.3.3"
},
"pnpm": {
"overrides": {
"@auth/core": "0.18.0"
}
},
"prettier": "@acme/prettier-config"
}

18
packages/api/index.ts Normal file
View File

@@ -0,0 +1,18 @@
import type { inferRouterInputs, inferRouterOutputs } from "@trpc/server";
import type { AppRouter } from "./src/root";
export { appRouter, type AppRouter } from "./src/root";
export { createTRPCContext } from "./src/trpc";
/**
* Inference helpers for input types
* @example type HelloInput = RouterInputs['example']['hello']
**/
export type RouterInputs = inferRouterInputs<AppRouter>;
/**
* Inference helpers for output types
* @example type HelloOutput = RouterOutputs['example']['hello']
**/
export type RouterOutputs = inferRouterOutputs<AppRouter>;

37
packages/api/package.json Normal file
View File

@@ -0,0 +1,37 @@
{
"name": "@acme/api",
"version": "0.1.0",
"private": true,
"main": "./index.ts",
"types": "./index.ts",
"license": "MIT",
"scripts": {
"clean": "rm -rf .turbo node_modules",
"lint": "eslint .",
"format": "prettier --check . --ignore-path ../../.gitignore",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@acme/auth": "workspace:^0.1.0",
"@acme/db": "workspace:^0.1.0",
"@trpc/client": "next",
"@trpc/server": "next",
"superjson": "2.2.1",
"zod": "^3.22.2"
},
"devDependencies": {
"@acme/eslint-config": "workspace:^0.2.0",
"@acme/prettier-config": "workspace:^0.1.0",
"@acme/tsconfig": "workspace:^0.1.0",
"eslint": "^8.53.0",
"prettier": "^3.1.0",
"typescript": "^5.3.3"
},
"eslintConfig": {
"root": true,
"extends": [
"@acme/eslint-config/base"
]
},
"prettier": "@acme/prettier-config"
}

11
packages/api/src/root.ts Normal file
View File

@@ -0,0 +1,11 @@
import { authRouter } from "./router/auth";
import { postRouter } from "./router/post";
import { createTRPCRouter } from "./trpc";
export const appRouter = createTRPCRouter({
auth: authRouter,
post: postRouter,
});
// export type definition of API
export type AppRouter = typeof appRouter;

View File

@@ -0,0 +1,11 @@
import { createTRPCRouter, protectedProcedure, publicProcedure } from "../trpc";
export const authRouter = createTRPCRouter({
getSession: publicProcedure.query(({ ctx }) => {
return ctx.session;
}),
getSecretMessage: protectedProcedure.query(() => {
// testing type validation of overridden next-auth Session in @acme/auth package
return "you can see this secret message!";
}),
});

View File

@@ -0,0 +1,40 @@
import { z } from "zod";
import { desc, eq, schema } from "@acme/db";
import { createTRPCRouter, protectedProcedure, publicProcedure } from "../trpc";
export const postRouter = createTRPCRouter({
all: publicProcedure.query(({ ctx }) => {
// return ctx.db.select().from(schema.post).orderBy(desc(schema.post.id));
return ctx.db.query.post.findMany({ orderBy: desc(schema.post.id) });
}),
byId: publicProcedure
.input(z.object({ id: z.number() }))
.query(({ ctx, input }) => {
// return ctx.db
// .select()
// .from(schema.post)
// .where(eq(schema.post.id, input.id));
return ctx.db.query.post.findFirst({
where: eq(schema.post.id, input.id),
});
}),
create: protectedProcedure
.input(
z.object({
title: z.string().min(1),
content: z.string().min(1),
}),
)
.mutation(({ ctx, input }) => {
return ctx.db.insert(schema.post).values(input);
}),
delete: protectedProcedure.input(z.number()).mutation(({ ctx, input }) => {
return ctx.db.delete(schema.post).where(eq(schema.post.id, input));
}),
});

132
packages/api/src/trpc.ts Normal file
View File

@@ -0,0 +1,132 @@
/**
* 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
*/
import { initTRPC, TRPCError } from "@trpc/server";
import superjson from "superjson";
import { ZodError } from "zod";
import { auth } from "@acme/auth";
import type { Session } from "@acme/auth";
import { db } from "@acme/db";
/**
* 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
*
*/
interface 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,
db,
};
};
/**
* 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: {
req?: Request;
auth: Session | null;
}) => {
const session = opts.auth ?? (await auth());
const source = opts.req?.headers.get("x-trpc-source") ?? "unknown";
console.log(">>> tRPC Request from", source, "by", session?.user);
return createInnerTRPCContext({
session,
});
};
/**
* 2. INITIALIZATION
*
* This is where the trpc api is initialized, connecting the context and
* transformer
*/
const t = initTRPC.context<typeof createTRPCContext>().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 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?.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);

View File

@@ -0,0 +1,8 @@
{
"extends": "@acme/tsconfig/base.json",
"compilerOptions": {
"tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json"
},
"include": ["."],
"exclude": ["node_modules"]
}

28
packages/auth/env.mjs Normal file
View File

@@ -0,0 +1,28 @@
import { createEnv } from "@t3-oss/env-nextjs";
import { z } from "zod";
export const env = createEnv({
server: {
AUTH_DISCORD_ID: z.string().min(1),
AUTH_DISCORD_SECRET: z.string().min(1),
AUTH_SECRET:
process.env.NODE_ENV === "production"
? z.string().min(1)
: z.string().min(1).optional(),
AUTH_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(),
),
},
client: {},
runtimeEnv: {
AUTH_DISCORD_ID: process.env.AUTH_DISCORD_ID,
AUTH_DISCORD_SECRET: process.env.AUTH_DISCORD_SECRET,
AUTH_SECRET: process.env.AUTH_SECRET,
AUTH_URL: process.env.AUTH_URL,
},
skipValidation: !!process.env.CI || !!process.env.SKIP_ENV_VALIDATION,
});

38
packages/auth/index.ts Normal file
View File

@@ -0,0 +1,38 @@
/* eslint-disable @typescript-eslint/unbound-method */
/* @see https://github.com/nextauthjs/next-auth/pull/8932 */
import Discord from "@auth/core/providers/discord";
import type { DefaultSession } from "@auth/core/types";
import { DrizzleAdapter } from "@auth/drizzle-adapter";
import NextAuth from "next-auth";
import { db, tableCreator } from "@acme/db";
export type { Session } from "next-auth";
declare module "next-auth" {
interface Session {
user: {
id: string;
} & DefaultSession["user"];
}
}
export const {
handlers: { GET, POST },
auth,
signIn,
signOut,
} = NextAuth({
adapter: DrizzleAdapter(db, tableCreator),
providers: [Discord],
callbacks: {
session: ({ session, user }) => ({
...session,
user: {
...session.user,
id: user.id,
},
}),
},
});

View File

@@ -0,0 +1,40 @@
{
"name": "@acme/auth",
"version": "0.1.0",
"private": true,
"main": "./index.ts",
"types": "./index.ts",
"license": "MIT",
"scripts": {
"clean": "rm -rf .turbo node_modules",
"lint": "eslint .",
"format": "prettier --check . --ignore-path ../../.gitignore",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@acme/db": "workspace:^0.1.0",
"@auth/core": "^0.18.4",
"@auth/drizzle-adapter": "^0.3.9",
"@t3-oss/env-nextjs": "^0.7.1",
"next": "^14.0.3",
"next-auth": "5.0.0-beta.4",
"react": "18.2.0",
"react-dom": "18.2.0",
"zod": "^3.22.2"
},
"devDependencies": {
"@acme/eslint-config": "workspace:^0.2.0",
"@acme/prettier-config": "workspace:^0.1.0",
"@acme/tsconfig": "workspace:^0.1.0",
"eslint": "^8.53.0",
"prettier": "^3.1.0",
"typescript": "^5.3.3"
},
"eslintConfig": {
"root": true,
"extends": [
"@acme/eslint-config/base"
]
},
"prettier": "@acme/prettier-config"
}

View File

@@ -0,0 +1,8 @@
{
"extends": "@acme/tsconfig/base.json",
"compilerOptions": {
"tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json"
},
"include": ["."],
"exclude": ["node_modules"]
}

View File

@@ -0,0 +1,23 @@
import * as dotenv from "dotenv";
import type { Config } from "drizzle-kit";
dotenv.config({ path: "../../.env" });
const uri = [
"mysql://",
process.env.DB_USERNAME,
":",
process.env.DB_PASSWORD,
"@",
process.env.DB_HOST,
":3306/",
process.env.DB_NAME,
'?ssl={"rejectUnauthorized":true}',
].join("");
export default {
schema: "./schema",
driver: "mysql2",
dbCredentials: { uri },
tablesFilter: ["t3turbo_*"],
} satisfies Config;

20
packages/db/index.ts Normal file
View File

@@ -0,0 +1,20 @@
import { Client } from "@planetscale/database";
import { drizzle } from "drizzle-orm/planetscale-serverless";
import * as auth from "./schema/auth";
import * as post from "./schema/post";
export const schema = { ...auth, ...post };
export { mySqlTable as tableCreator } from "./schema/_table";
export * from "drizzle-orm";
export const db = drizzle(
new Client({
host: process.env.DB_HOST,
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
}).connection(),
{ schema },
);

37
packages/db/package.json Normal file
View File

@@ -0,0 +1,37 @@
{
"name": "@acme/db",
"version": "0.1.0",
"private": true,
"main": "./index.ts",
"types": "./index.ts",
"license": "MIT",
"scripts": {
"clean": "rm -rf .turbo node_modules",
"lint": "eslint .",
"format": "prettier --check . --ignore-path ../../.gitignore",
"push": "drizzle-kit push:mysql",
"studio": "drizzle-kit studio",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@planetscale/database": "^1.11.0",
"drizzle-orm": "^0.29.1"
},
"devDependencies": {
"@acme/eslint-config": "workspace:^0.2.0",
"@acme/prettier-config": "workspace:^0.1.0",
"@acme/tsconfig": "workspace:^0.1.0",
"dotenv-cli": "^7.3.0",
"drizzle-kit": "^0.20.6",
"eslint": "^8.53.0",
"prettier": "^3.1.0",
"typescript": "^5.3.3"
},
"eslintConfig": {
"root": true,
"extends": [
"@acme/eslint-config/base"
]
},
"prettier": "@acme/prettier-config"
}

View File

@@ -0,0 +1,9 @@
import { mysqlTableCreator } from "drizzle-orm/mysql-core";
/**
* This is an example of how to use the multi-project schema feature of Drizzle ORM. Use the same
* database instance for multiple projects.
*
* @see https://orm.drizzle.team/docs/goodies#multi-project-schema
*/
export const mySqlTable = mysqlTableCreator((name) => `t3turbo_${name}`);

View File

@@ -0,0 +1,84 @@
import type { AdapterAccount } from "@auth/core/adapters";
import { relations, sql } from "drizzle-orm";
import {
index,
int,
primaryKey,
text,
timestamp,
varchar,
} from "drizzle-orm/mysql-core";
import { mySqlTable } from "./_table";
export const users = mySqlTable("user", {
id: varchar("id", { length: 255 }).notNull().primaryKey(),
name: varchar("name", { length: 255 }),
email: varchar("email", { length: 255 }).notNull(),
emailVerified: timestamp("emailVerified", {
mode: "date",
fsp: 3,
}).default(sql`CURRENT_TIMESTAMP(3)`),
image: varchar("image", { length: 255 }),
});
export const usersRelations = relations(users, ({ many }) => ({
accounts: many(accounts),
}));
export const accounts = mySqlTable(
"account",
{
userId: varchar("userId", { length: 255 }).notNull(),
type: varchar("type", { length: 255 })
.$type<AdapterAccount["type"]>()
.notNull(),
provider: varchar("provider", { length: 255 }).notNull(),
providerAccountId: varchar("providerAccountId", { length: 255 }).notNull(),
refresh_token: varchar("refresh_token", { length: 255 }),
access_token: varchar("access_token", { length: 255 }),
expires_at: int("expires_at"),
token_type: varchar("token_type", { length: 255 }),
scope: varchar("scope", { length: 255 }),
id_token: text("id_token"),
session_state: varchar("session_state", { length: 255 }),
},
(account) => ({
compoundKey: primaryKey(account.provider, account.providerAccountId),
userIdIdx: index("userId_idx").on(account.userId),
}),
);
export const accountsRelations = relations(accounts, ({ one }) => ({
user: one(users, { fields: [accounts.userId], references: [users.id] }),
}));
export const sessions = mySqlTable(
"session",
{
sessionToken: varchar("sessionToken", { length: 255 })
.notNull()
.primaryKey(),
userId: varchar("userId", { length: 255 }).notNull(),
expires: timestamp("expires", { mode: "date" }).notNull(),
},
(session) => ({
userIdIdx: index("userId_idx").on(session.userId),
}),
);
export const sessionsRelations = relations(sessions, ({ one }) => ({
user: one(users, { fields: [sessions.userId], references: [users.id] }),
}));
export const verificationTokens = mySqlTable(
"verificationToken",
{
identifier: varchar("identifier", { length: 255 }).notNull(),
token: varchar("token", { length: 255 }).notNull(),
expires: timestamp("expires", { mode: "date" }).notNull(),
},
(vt) => ({
compoundKey: primaryKey(vt.identifier, vt.token),
}),
);

View File

@@ -0,0 +1,14 @@
import { sql } from "drizzle-orm";
import { serial, timestamp, varchar } from "drizzle-orm/mysql-core";
import { mySqlTable } from "./_table";
export const post = mySqlTable("post", {
id: serial("id").primaryKey(),
title: varchar("name", { length: 256 }).notNull(),
content: varchar("content", { length: 256 }).notNull(),
createdAt: timestamp("created_at")
.default(sql`CURRENT_TIMESTAMP`)
.notNull(),
updatedAt: timestamp("updatedAt").onUpdateNow(),
});

View File

@@ -0,0 +1,8 @@
{
"extends": "@acme/tsconfig/base.json",
"compilerOptions": {
"tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json"
},
"include": ["."],
"exclude": ["node_modules"]
}

13157
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

4
pnpm-workspace.yaml Normal file
View File

@@ -0,0 +1,4 @@
packages:
- apps/*
- packages/*
- tooling/*

46
tooling/eslint/base.js Normal file
View File

@@ -0,0 +1,46 @@
/** @type {import("eslint").Linter.Config} */
const config = {
extends: [
"turbo",
"eslint:recommended",
"plugin:@typescript-eslint/recommended-type-checked",
"plugin:@typescript-eslint/stylistic-type-checked",
"prettier",
],
env: {
es2022: true,
node: true,
},
parser: "@typescript-eslint/parser",
parserOptions: {
project: true,
},
plugins: ["@typescript-eslint", "import"],
rules: {
"turbo/no-undeclared-env-vars": "off",
"@typescript-eslint/no-unused-vars": [
"error",
{ argsIgnorePattern: "^_", varsIgnorePattern: "^_" },
],
"@typescript-eslint/consistent-type-imports": [
"warn",
{ prefer: "type-imports", fixStyle: "separate-type-imports" },
],
"@typescript-eslint/no-misused-promises": [
2,
{ checksVoidReturn: { attributes: false } },
],
"import/consistent-type-specifier-style": ["error", "prefer-top-level"],
},
ignorePatterns: [
"**/.eslintrc.cjs",
"**/*.config.js",
"**/*.config.cjs",
".next",
"dist",
"pnpm-lock.yaml",
],
reportUnusedDisableDirectives: true,
};
module.exports = config;

9
tooling/eslint/nextjs.js Normal file
View File

@@ -0,0 +1,9 @@
/** @type {import('eslint').Linter.Config} */
const config = {
extends: ["plugin:@next/next/recommended"],
rules: {
"@next/next/no-html-link-for-pages": "off",
},
};
module.exports = config;

View File

@@ -0,0 +1,42 @@
{
"name": "@acme/eslint-config",
"version": "0.2.0",
"private": true,
"license": "MIT",
"files": [
"./base.js",
"./nextjs.js",
"./react.js"
],
"scripts": {
"clean": "rm -rf .turbo node_modules",
"lint": "eslint .",
"format": "prettier --check . --ignore-path ../../.gitignore",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@next/eslint-plugin-next": "^14.0.3",
"@typescript-eslint/eslint-plugin": "^6.10.0",
"@typescript-eslint/parser": "^6.10.0",
"eslint-config-prettier": "^9.1.0",
"eslint-config-turbo": "^1.10.16",
"eslint-plugin-import": "^2.29.0",
"eslint-plugin-jsx-a11y": "^6.8.0",
"eslint-plugin-react": "^7.33.2",
"eslint-plugin-react-hooks": "^4.6.0"
},
"devDependencies": {
"@types/eslint": "^8.44.7",
"@acme/prettier-config": "workspace:^0.1.0",
"@acme/tsconfig": "workspace:^0.1.0",
"eslint": "^8.53.0",
"typescript": "^5.3.3"
},
"eslintConfig": {
"root": true,
"extends": [
"./base.js"
]
},
"prettier": "@acme/prettier-config"
}

24
tooling/eslint/react.js vendored Normal file
View File

@@ -0,0 +1,24 @@
/** @type {import('eslint').Linter.Config} */
const config = {
extends: [
"plugin:react/recommended",
"plugin:react-hooks/recommended",
"plugin:jsx-a11y/recommended",
],
rules: {
"react/prop-types": "off",
},
globals: {
React: "writable",
},
settings: {
react: {
version: "detect",
},
},
env: {
browser: true,
},
};
module.exports = config;

View File

@@ -0,0 +1,8 @@
{
"extends": "@acme/tsconfig/base.json",
"compilerOptions": {
"tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json"
},
"include": ["."],
"exclude": ["node_modules"]
}

View File

@@ -0,0 +1,3 @@
{
"name": "@acme/github"
}

View File

@@ -0,0 +1,17 @@
name: "Setup and install"
description: "Common setup steps for Actions"
runs:
using: composite
steps:
- uses: pnpm/action-setup@v2
- uses: actions/setup-node@v4
with:
node-version: 18
cache: "pnpm"
- shell: bash
run: pnpm add -g turbo
- shell: bash
run: pnpm install

View File

@@ -0,0 +1,32 @@
import { fileURLToPath } from "url";
/** @typedef {import("prettier").Config} PrettierConfig */
/** @typedef {import("prettier-plugin-tailwindcss").PluginOptions} TailwindConfig */
/** @typedef {import("@ianvs/prettier-plugin-sort-imports").PluginConfig} SortImportsConfig */
/** @type { PrettierConfig | SortImportsConfig | TailwindConfig } */
const config = {
plugins: [
"@ianvs/prettier-plugin-sort-imports",
"prettier-plugin-tailwindcss",
],
tailwindConfig: fileURLToPath(
new URL("../../tooling/tailwind/index.ts", import.meta.url),
),
importOrder: [
"^(react/(.*)$)|^(react$)|^(react-native(.*)$)",
"^(next/(.*)$)|^(next$)",
"^(expo(.*)$)|^(expo$)",
"<THIRD_PARTY_MODULES>",
"",
"^@acme/(.*)$",
"",
"^~/",
"^[../]",
"^[./]",
],
importOrderParserPlugins: ["typescript", "jsx", "decorators-legacy"],
importOrderTypeScriptVersion: "4.4.0",
};
export default config;

View File

@@ -0,0 +1,21 @@
{
"name": "@acme/prettier-config",
"private": true,
"version": "0.1.0",
"main": "index.mjs",
"scripts": {
"clean": "rm -rf .turbo node_modules",
"format": "prettier --check . --ignore-path ../../.gitignore",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@ianvs/prettier-plugin-sort-imports": "^4.1.1",
"prettier": "^3.1.0",
"prettier-plugin-tailwindcss": "^0.5.7"
},
"devDependencies": {
"@acme/tsconfig": "workspace:^0.1.0",
"typescript": "^5.3.3"
},
"prettier": "@acme/prettier-config"
}

View File

@@ -0,0 +1,8 @@
{
"extends": "@acme/tsconfig/base.json",
"compilerOptions": {
"tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json"
},
"include": ["."],
"exclude": ["node_modules"]
}

View File

@@ -0,0 +1,21 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"compilerOptions": {
"target": "ES2022",
"lib": ["dom", "dom.iterable", "ES2022"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "Bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"moduleDetection": "force",
"jsx": "preserve",
"incremental": true,
"noUncheckedIndexedAccess": true
},
"exclude": ["node_modules", "build", "dist", ".next", ".expo"]
}

View File

@@ -0,0 +1,8 @@
{
"name": "@acme/tsconfig",
"private": true,
"version": "0.1.0",
"files": [
"base.json"
]
}

50
turbo.json Normal file
View File

@@ -0,0 +1,50 @@
{
"$schema": "https://turborepo.org/schema.json",
"globalDependencies": ["**/.env"],
"pipeline": {
"topo": {
"dependsOn": ["^topo"]
},
"build": {
"dependsOn": ["^build"],
"outputs": [
".next/**",
"!.next/cache/**",
"next-env.d.ts",
".expo/**",
".output/**",
".vercel/output/**"
]
},
"dev": {
"persistent": true,
"cache": false
},
"format": {
"outputs": ["node_modules/.cache/.prettiercache"],
"outputMode": "new-only"
},
"lint": {
"dependsOn": ["^topo"],
"outputs": ["node_modules/.cache/.eslintcache"]
},
"typecheck": {
"dependsOn": ["^topo"],
"outputs": ["node_modules/.cache/tsbuildinfo.json"]
},
"clean": {
"cache": false
},
"//#clean": {
"cache": false
}
},
"globalEnv": [
"DATABASE_URL",
"AUTH_DISCORD_ID",
"AUTH_DISCORD_SECRET",
"AUTH_REDIRECT_PROXY_URL",
"AUTH_SECRET",
"AUTH_URL"
]
}

View File

@@ -0,0 +1,95 @@
import { execSync } from "node:child_process";
import type { PlopTypes } from "@turbo/gen";
interface PackageJson {
name: string;
scripts: Record<string, string>;
dependencies: Record<string, string>;
devDependencies: Record<string, string>;
}
export default function generator(plop: PlopTypes.NodePlopAPI): void {
plop.setGenerator("init", {
description: "Generate a new package for the Acme Monorepo",
prompts: [
{
type: "input",
name: "name",
message:
"What is the name of the package? (You can skip the `@acme/` prefix)",
},
{
type: "input",
name: "deps",
message:
"Enter a space separated list of dependencies you would like to install",
},
],
actions: [
(answers) => {
if ("name" in answers && typeof answers.name === "string") {
if (answers.name.startsWith("@acme/")) {
answers.name = answers.name.replace("@acme/", "");
}
}
return "Config sanitized";
},
{
type: "add",
path: "packages/{{ name }}/package.json",
templateFile: "templates/package.json.hbs",
},
{
type: "add",
path: "packages/{{ name }}/tsconfig.json",
templateFile: "templates/tsconfig.json.hbs",
},
{
type: "add",
path: "packages/{{ name }}/index.ts",
template: "export * from './src';",
},
{
type: "add",
path: "packages/{{ name }}/src/index.ts",
template: "export const name = '{{ name }}';",
},
{
type: "modify",
path: "packages/{{ name }}/package.json",
async transform(content, answers) {
if ("deps" in answers && typeof answers.deps === "string") {
const pkg = JSON.parse(content) as PackageJson;
for (const dep of answers.deps.split(" ").filter(Boolean)) {
const version = await fetch(
`https://registry.npmjs.org/-/package/${dep}/dist-tags`,
)
.then((res) => res.json())
.then((json) => json.latest);
if (!pkg.dependencies) pkg.dependencies = {};
pkg.dependencies[dep] = `^${version}`;
}
return JSON.stringify(pkg, null, 2);
}
return content;
},
},
async (answers) => {
/**
* Install deps and format everything
*/
if ("name" in answers && typeof answers.name === "string") {
// execSync("pnpm dlx sherif@latest --fix", {
// stdio: "inherit",
// });
execSync("pnpm i", { stdio: "inherit" });
execSync(
`pnpm prettier --write packages/${answers.name}/** --list-different`,
);
return "Package scaffolded";
}
return "Package not scaffolded";
},
],
});
}

View File

@@ -0,0 +1,35 @@
{
"name": "@acme/{{ name }}",
"private": true,
"version": "0.1.0",
"exports": {
".": "./index.ts"
},
"typesVersions": {
"*": {
"*": [
"src/*"
]
}
},
"license": "MIT",
"scripts": {
"clean": "rm -rf .turbo node_modules",
"lint": "eslint .",
"format": "prettier --check . --ignore-path ../../.gitignore",
"typecheck": "tsc --noEmit"
},
"devDependencies": {
"@acme/eslint-config": "workspace:^0.2.0",
"@acme/prettier-config": "workspace:^0.1.0",
"@acme/tsconfig": "workspace:^0.1.0",
"eslint": "^8.53.0",
"typescript": "^5.2.2"
},
"eslintConfig": {
"extends": [
"@acme/eslint-config/base"
]
},
"prettier": "@acme/prettier-config"
}

View File

@@ -0,0 +1,8 @@
{
"extends": "@acme/tsconfig/base.json",
"compilerOptions": {
"tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json"
},
"include": ["*.ts", "src"],
"exclude": ["node_modules"]
}

5
vercel.json Normal file
View File

@@ -0,0 +1,5 @@
{
"github": {
"silent": true
}
}