├── .env.example ├── .eslintrc.json ├── .gitignore ├── README.md ├── next.config.mjs ├── package-lock.json ├── package.json ├── postcss.config.cjs ├── prettier.config.cjs ├── public └── favicon.ico ├── src ├── env │ ├── client.mjs │ ├── schema.mjs │ └── server.mjs ├── pages │ ├── [[...rest]].tsx │ ├── _app.tsx │ └── api │ │ └── trpc │ │ └── [trpc].ts ├── router │ └── index.tsx ├── server │ └── api │ │ ├── root.ts │ │ ├── routers │ │ └── example.ts │ │ └── trpc.ts ├── styles │ └── globals.css └── utils │ └── api.ts ├── tailwind.config.cjs └── tsconfig.json /.env.example: -------------------------------------------------------------------------------- 1 | # Since .env is gitignored, you can use .env.example to build a new `.env` file when you clone the repo. 2 | # Keep this file up-to-date when you add new variables to `.env`. 3 | 4 | # This file will be committed to version control, so make sure not to have any secrets in it. 5 | # If you are cloning this repo, create a copy of this file named `.env` and populate it with your secrets. 6 | 7 | # When adding additional env variables, the schema in /env/schema.mjs should be updated accordingly 8 | # Example: 9 | # SERVERVAR=foo 10 | # NEXT_PUBLIC_CLIENTVAR=bar 11 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "overrides": [ 3 | { 4 | "extends": [ 5 | "plugin:@typescript-eslint/recommended-requiring-type-checking" 6 | ], 7 | "files": ["*.ts", "*.tsx"], 8 | "parserOptions": { 9 | "project": "tsconfig.json" 10 | } 11 | } 12 | ], 13 | "parser": "@typescript-eslint/parser", 14 | "parserOptions": { 15 | "project": "./tsconfig.json" 16 | }, 17 | "plugins": ["@typescript-eslint"], 18 | "extends": ["next/core-web-vitals", "plugin:@typescript-eslint/recommended"], 19 | "rules": { 20 | "@typescript-eslint/consistent-type-imports": "warn" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # database 12 | /prisma/db.sqlite 13 | /prisma/db.sqlite-journal 14 | 15 | # next.js 16 | /.next/ 17 | /out/ 18 | next-env.d.ts 19 | 20 | # production 21 | /build 22 | 23 | # misc 24 | .DS_Store 25 | *.pem 26 | 27 | # debug 28 | npm-debug.log* 29 | yarn-debug.log* 30 | yarn-error.log* 31 | .pnpm-debug.log* 32 | 33 | # local env files 34 | # 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 35 | .env 36 | .env*.local 37 | 38 | # vercel 39 | .vercel 40 | 41 | # typescript 42 | *.tsbuildinfo 43 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Create T3 App 2 | 3 | This is a [T3 Stack](https://create.t3.gg/) project bootstrapped with `create-t3-app`. 4 | 5 | ## What's next? How do I make an app with this? 6 | 7 | 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. 8 | 9 | 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. 10 | 11 | - [Next.js](https://nextjs.org) 12 | - [NextAuth.js](https://next-auth.js.org) 13 | - [Prisma](https://prisma.io) 14 | - [Tailwind CSS](https://tailwindcss.com) 15 | - [tRPC](https://trpc.io) 16 | 17 | ## Learn More 18 | 19 | To learn more about the [T3 Stack](https://create.t3.gg/), take a look at the following resources: 20 | 21 | - [Documentation](https://create.t3.gg/) 22 | - [Learn the T3 Stack](https://create.t3.gg/en/faq#what-learning-resources-are-currently-available) — Check out these awesome tutorials 23 | 24 | You can check out the [create-t3-app GitHub repository](https://github.com/t3-oss/create-t3-app) — your feedback and contributions are welcome! 25 | 26 | ## How do I deploy this? 27 | 28 | 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. 29 | -------------------------------------------------------------------------------- /next.config.mjs: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | /** 3 | * Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. 4 | * This is especially useful for Docker builds. 5 | */ 6 | !process.env.SKIP_ENV_VALIDATION && (await import("./src/env/server.mjs")); 7 | 8 | /** @type {import("next").NextConfig} */ 9 | const config = { 10 | reactStrictMode: true, 11 | /* If trying out the experimental appDir, comment the i18n config out 12 | * @see https://github.com/vercel/next.js/issues/41980 */ 13 | i18n: { 14 | locales: ["en"], 15 | defaultLocale: "en", 16 | }, 17 | }; 18 | export default config; 19 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "tanrotuer", 3 | "version": "0.1.0", 4 | "private": true, 5 | "scripts": { 6 | "build": "next build", 7 | "dev": "next dev", 8 | "lint": "next lint", 9 | "start": "next start" 10 | }, 11 | "dependencies": { 12 | "@tanstack/react-query": "^4.20.0", 13 | "@tanstack/react-router": "^0.0.1-beta.57", 14 | "@trpc/client": "^10.8.1", 15 | "@trpc/next": "^10.8.1", 16 | "@trpc/react-query": "^10.8.1", 17 | "@trpc/server": "^10.8.1", 18 | "next": "13.1.2", 19 | "react": "18.2.0", 20 | "react-dom": "18.2.0", 21 | "superjson": "1.9.1", 22 | "zod": "^3.20.2" 23 | }, 24 | "devDependencies": { 25 | "@types/node": "^18.11.18", 26 | "@types/prettier": "^2.7.2", 27 | "@types/react": "^18.0.26", 28 | "@types/react-dom": "^18.0.10", 29 | "@typescript-eslint/eslint-plugin": "^5.47.1", 30 | "@typescript-eslint/parser": "^5.47.1", 31 | "autoprefixer": "^10.4.7", 32 | "eslint": "^8.30.0", 33 | "eslint-config-next": "13.1.2", 34 | "postcss": "^8.4.14", 35 | "prettier": "^2.8.1", 36 | "prettier-plugin-tailwindcss": "^0.2.1", 37 | "tailwindcss": "^3.2.0", 38 | "typescript": "^4.9.4" 39 | }, 40 | "ct3aMetadata": { 41 | "initVersion": "7.3.2" 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /postcss.config.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | plugins: { 3 | tailwindcss: {}, 4 | autoprefixer: {}, 5 | }, 6 | }; 7 | -------------------------------------------------------------------------------- /prettier.config.cjs: -------------------------------------------------------------------------------- 1 | /** @type {import("prettier").Config} */ 2 | module.exports = { 3 | plugins: [require.resolve("prettier-plugin-tailwindcss")], 4 | }; 5 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/t3dotgg/next-tanstack-router-example/f610f4f14a403e3339e2f3fa2b19c629e727fc07/public/favicon.ico -------------------------------------------------------------------------------- /src/env/client.mjs: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | import { clientEnv, clientSchema } from "./schema.mjs"; 3 | 4 | const _clientEnv = clientSchema.safeParse(clientEnv); 5 | 6 | export const formatErrors = ( 7 | /** @type {import('zod').ZodFormattedError,string>} */ 8 | errors, 9 | ) => 10 | Object.entries(errors) 11 | .map(([name, value]) => { 12 | if (value && "_errors" in value) 13 | return `${name}: ${value._errors.join(", ")}\n`; 14 | }) 15 | .filter(Boolean); 16 | 17 | if (!_clientEnv.success) { 18 | console.error( 19 | "❌ Invalid environment variables:\n", 20 | ...formatErrors(_clientEnv.error.format()), 21 | ); 22 | throw new Error("Invalid environment variables"); 23 | } 24 | 25 | for (let key of Object.keys(_clientEnv.data)) { 26 | if (!key.startsWith("NEXT_PUBLIC_")) { 27 | console.warn( 28 | `❌ Invalid public environment variable name: ${key}. It must begin with 'NEXT_PUBLIC_'`, 29 | ); 30 | 31 | throw new Error("Invalid public environment variable name"); 32 | } 33 | } 34 | 35 | export const env = _clientEnv.data; 36 | -------------------------------------------------------------------------------- /src/env/schema.mjs: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | import { z } from "zod"; 3 | 4 | /** 5 | * Specify your server-side environment variables schema here. 6 | * This way you can ensure the app isn't built with invalid env vars. 7 | */ 8 | export const serverSchema = z.object({ 9 | NODE_ENV: z.enum(["development", "test", "production"]), 10 | }); 11 | 12 | /** 13 | * You can't destruct `process.env` as a regular object in the Next.js 14 | * middleware, so you have to do it manually here. 15 | * @type {{ [k in keyof z.infer]: z.infer[k] | undefined }} 16 | */ 17 | export const serverEnv = { 18 | NODE_ENV: process.env.NODE_ENV, 19 | }; 20 | 21 | /** 22 | * Specify your client-side environment variables schema here. 23 | * This way you can ensure the app isn't built with invalid env vars. 24 | * To expose them to the client, prefix them with `NEXT_PUBLIC_`. 25 | */ 26 | export const clientSchema = z.object({ 27 | // NEXT_PUBLIC_CLIENTVAR: z.string(), 28 | }); 29 | 30 | /** 31 | * You can't destruct `process.env` as a regular object, so you have to do 32 | * it manually here. This is because Next.js evaluates this at build time, 33 | * and only used environment variables are included in the build. 34 | * @type {{ [k in keyof z.infer]: z.infer[k] | undefined }} 35 | */ 36 | export const clientEnv = { 37 | // NEXT_PUBLIC_CLIENTVAR: process.env.NEXT_PUBLIC_CLIENTVAR, 38 | }; 39 | -------------------------------------------------------------------------------- /src/env/server.mjs: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | /** 3 | * This file is included in `/next.config.mjs` which ensures the app isn't built with invalid env vars. 4 | * It has to be a `.mjs`-file to be imported there. 5 | */ 6 | import { serverSchema, serverEnv } from "./schema.mjs"; 7 | import { env as clientEnv, formatErrors } from "./client.mjs"; 8 | 9 | const _serverEnv = serverSchema.safeParse(serverEnv); 10 | 11 | if (!_serverEnv.success) { 12 | console.error( 13 | "❌ Invalid environment variables:\n", 14 | ...formatErrors(_serverEnv.error.format()), 15 | ); 16 | throw new Error("Invalid environment variables"); 17 | } 18 | 19 | for (let key of Object.keys(_serverEnv.data)) { 20 | if (key.startsWith("NEXT_PUBLIC_")) { 21 | console.warn("❌ You are exposing a server-side env-variable:", key); 22 | 23 | throw new Error("You are exposing a server-side env-variable"); 24 | } 25 | } 26 | 27 | export const env = { ..._serverEnv.data, ...clientEnv }; 28 | -------------------------------------------------------------------------------- /src/pages/[[...rest]].tsx: -------------------------------------------------------------------------------- 1 | import dynamic from "next/dynamic"; 2 | 3 | const AppRouter = dynamic(() => import("../router/index"), { ssr: false }); 4 | 5 | const Main = () => { 6 | return ; 7 | }; 8 | 9 | export default Main; 10 | -------------------------------------------------------------------------------- /src/pages/_app.tsx: -------------------------------------------------------------------------------- 1 | import { type AppType } from "next/app"; 2 | 3 | import { api } from "../utils/api"; 4 | 5 | import "../styles/globals.css"; 6 | 7 | const MyApp: AppType = ({ Component, pageProps }) => { 8 | return ; 9 | }; 10 | 11 | export default api.withTRPC(MyApp); 12 | -------------------------------------------------------------------------------- /src/pages/api/trpc/[trpc].ts: -------------------------------------------------------------------------------- 1 | import { createNextApiHandler } from "@trpc/server/adapters/next"; 2 | 3 | import { env } from "../../../env/server.mjs"; 4 | import { createTRPCContext } from "../../../server/api/trpc"; 5 | import { appRouter } from "../../../server/api/root"; 6 | 7 | // export API handler 8 | export default createNextApiHandler({ 9 | router: appRouter, 10 | createContext: createTRPCContext, 11 | onError: 12 | env.NODE_ENV === "development" 13 | ? ({ path, error }) => { 14 | console.error( 15 | `❌ tRPC failed on ${path ?? ""}: ${error.message}`, 16 | ); 17 | } 18 | : undefined, 19 | }); 20 | -------------------------------------------------------------------------------- /src/router/index.tsx: -------------------------------------------------------------------------------- 1 | import React, { StrictMode } from "react"; 2 | import ReactDOM from "react-dom/client"; 3 | import { 4 | Outlet, 5 | RouterProvider, 6 | Link, 7 | ReactRouter, 8 | createRouteConfig, 9 | } from "@tanstack/react-router"; 10 | 11 | const rootRoute = createRouteConfig({ 12 | component: () => ( 13 | <> 14 |
15 | Home About 16 |
17 |
18 | 19 | 20 | ), 21 | }); 22 | 23 | const indexRoute = rootRoute.createRoute({ 24 | path: "/", 25 | component: Index, 26 | }); 27 | 28 | const aboutRoute = rootRoute.createRoute({ 29 | path: "/about", 30 | component: About, 31 | }); 32 | 33 | const routeConfig = rootRoute.addChildren([indexRoute, aboutRoute]); 34 | 35 | const router = new ReactRouter({ routeConfig }); 36 | 37 | export default function App() { 38 | return ; 39 | } 40 | 41 | function Index() { 42 | return ( 43 |
44 |

Welcome Home!

45 |
46 | ); 47 | } 48 | 49 | function About() { 50 | return
Hello from About!
; 51 | } 52 | 53 | declare module "@tanstack/react-router" { 54 | interface RegisterRouter { 55 | router: typeof router; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/server/api/root.ts: -------------------------------------------------------------------------------- 1 | import { createTRPCRouter } from "./trpc"; 2 | import { exampleRouter } from "./routers/example"; 3 | 4 | /** 5 | * This is the primary router for your server. 6 | * 7 | * All routers added in /api/routers should be manually added here 8 | */ 9 | export const appRouter = createTRPCRouter({ 10 | example: exampleRouter, 11 | }); 12 | 13 | // export type definition of API 14 | export type AppRouter = typeof appRouter; 15 | -------------------------------------------------------------------------------- /src/server/api/routers/example.ts: -------------------------------------------------------------------------------- 1 | import { z } from "zod"; 2 | 3 | import { createTRPCRouter, publicProcedure } from "../trpc"; 4 | 5 | export const exampleRouter = createTRPCRouter({ 6 | hello: publicProcedure 7 | .input(z.object({ text: z.string() })) 8 | .query(({ input }) => { 9 | return { 10 | greeting: `Hello ${input.text}`, 11 | }; 12 | }), 13 | }); 14 | -------------------------------------------------------------------------------- /src/server/api/trpc.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * YOU PROBABLY DON'T NEED TO EDIT THIS FILE, UNLESS: 3 | * 1. You want to modify request context (see Part 1) 4 | * 2. You want to create a new middleware or type of procedure (see Part 3) 5 | * 6 | * tl;dr - this is where all the tRPC server stuff is created and plugged in. 7 | * The pieces you will need to use are documented accordingly near the end 8 | */ 9 | 10 | /** 11 | * 1. CONTEXT 12 | * 13 | * This section defines the "contexts" that are available in the backend API 14 | * 15 | * These allow you to access things like the database, the session, etc, when 16 | * processing a request 17 | * 18 | */ 19 | import { type CreateNextContextOptions } from "@trpc/server/adapters/next"; 20 | 21 | /** 22 | * Replace this with an object if you want to pass things to createContextInner 23 | */ 24 | type CreateContextOptions = Record; 25 | 26 | /** 27 | * This helper generates the "internals" for a tRPC context. If you need to use 28 | * it, you can export it from here 29 | * 30 | * Examples of things you may need it for: 31 | * - testing, so we dont have to mock Next.js' req/res 32 | * - trpc's `createSSGHelpers` where we don't have req/res 33 | * @see https://create.t3.gg/en/usage/trpc#-servertrpccontextts 34 | */ 35 | const createInnerTRPCContext = (_opts: CreateContextOptions) => { 36 | return {}; 37 | }; 38 | 39 | /** 40 | * This is the actual context you'll use in your router. It will be used to 41 | * process every request that goes through your tRPC endpoint 42 | * @see https://trpc.io/docs/context 43 | */ 44 | export const createTRPCContext = (_opts: CreateNextContextOptions) => { 45 | return createInnerTRPCContext({}); 46 | }; 47 | 48 | /** 49 | * 2. INITIALIZATION 50 | * 51 | * This is where the trpc api is initialized, connecting the context and 52 | * transformer 53 | */ 54 | import { initTRPC } from "@trpc/server"; 55 | import superjson from "superjson"; 56 | 57 | const t = initTRPC.context().create({ 58 | transformer: superjson, 59 | errorFormatter({ shape }) { 60 | return shape; 61 | }, 62 | }); 63 | 64 | /** 65 | * 3. ROUTER & PROCEDURE (THE IMPORTANT BIT) 66 | * 67 | * These are the pieces you use to build your tRPC API. You should import these 68 | * a lot in the /src/server/api/routers folder 69 | */ 70 | 71 | /** 72 | * This is how you create new routers and subrouters in your tRPC API 73 | * @see https://trpc.io/docs/router 74 | */ 75 | export const createTRPCRouter = t.router; 76 | 77 | /** 78 | * Public (unauthed) procedure 79 | * 80 | * This is the base piece you use to build new queries and mutations on your 81 | * tRPC API. It does not guarantee that a user querying is authorized, but you 82 | * can still access user session data if they are logged in 83 | */ 84 | export const publicProcedure = t.procedure; 85 | -------------------------------------------------------------------------------- /src/styles/globals.css: -------------------------------------------------------------------------------- 1 | @tailwind base; 2 | @tailwind components; 3 | @tailwind utilities; 4 | -------------------------------------------------------------------------------- /src/utils/api.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This is the client-side entrypoint for your tRPC API. 3 | * It's used to create the `api` object which contains the Next.js App-wrapper 4 | * as well as your typesafe react-query hooks. 5 | * 6 | * We also create a few inference helpers for input and output types 7 | */ 8 | import { httpBatchLink, loggerLink } from "@trpc/client"; 9 | import { createTRPCNext } from "@trpc/next"; 10 | import { type inferRouterInputs, type inferRouterOutputs } from "@trpc/server"; 11 | import superjson from "superjson"; 12 | 13 | import { type AppRouter } from "../server/api/root"; 14 | 15 | const getBaseUrl = () => { 16 | if (typeof window !== "undefined") return ""; // browser should use relative url 17 | if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`; // SSR should use vercel url 18 | return `http://localhost:${process.env.PORT ?? 3000}`; // dev SSR should use localhost 19 | }; 20 | 21 | /** 22 | * A set of typesafe react-query hooks for your tRPC API 23 | */ 24 | export const api = createTRPCNext({ 25 | config() { 26 | return { 27 | /** 28 | * Transformer used for data de-serialization from the server 29 | * @see https://trpc.io/docs/data-transformers 30 | **/ 31 | transformer: superjson, 32 | 33 | /** 34 | * Links used to determine request flow from client to server 35 | * @see https://trpc.io/docs/links 36 | * */ 37 | links: [ 38 | loggerLink({ 39 | enabled: (opts) => 40 | process.env.NODE_ENV === "development" || 41 | (opts.direction === "down" && opts.result instanceof Error), 42 | }), 43 | httpBatchLink({ 44 | url: `${getBaseUrl()}/api/trpc`, 45 | }), 46 | ], 47 | }; 48 | }, 49 | /** 50 | * Whether tRPC should await queries when server rendering pages 51 | * @see https://trpc.io/docs/nextjs#ssr-boolean-default-false 52 | */ 53 | ssr: false, 54 | }); 55 | 56 | /** 57 | * Inference helper for inputs 58 | * @example type HelloInput = RouterInputs['example']['hello'] 59 | **/ 60 | export type RouterInputs = inferRouterInputs; 61 | /** 62 | * Inference helper for outputs 63 | * @example type HelloOutput = RouterOutputs['example']['hello'] 64 | **/ 65 | export type RouterOutputs = inferRouterOutputs; 66 | -------------------------------------------------------------------------------- /tailwind.config.cjs: -------------------------------------------------------------------------------- 1 | /** @type {import('tailwindcss').Config} */ 2 | module.exports = { 3 | content: ["./src/**/*.{js,ts,jsx,tsx}"], 4 | theme: { 5 | extend: {}, 6 | }, 7 | plugins: [], 8 | }; 9 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2017", 4 | "lib": ["dom", "dom.iterable", "esnext"], 5 | "allowJs": true, 6 | "skipLibCheck": true, 7 | "strict": true, 8 | "forceConsistentCasingInFileNames": true, 9 | "noEmit": true, 10 | "esModuleInterop": true, 11 | "module": "esnext", 12 | "moduleResolution": "node", 13 | "resolveJsonModule": true, 14 | "isolatedModules": true, 15 | "jsx": "preserve", 16 | "incremental": true, 17 | "noUncheckedIndexedAccess": true 18 | }, 19 | "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "**/*.cjs", "**/*.mjs"], 20 | "exclude": ["node_modules"] 21 | } 22 | --------------------------------------------------------------------------------