create-lx2-app 0.11.5-beta.a94a9aa → 0.11.5-beta.b3548e3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/index.js +28 -26
  2. package/package.json +3 -1
  3. package/template/packages/config/biome.jsonc +46 -9
  4. package/template/packages/config/tsconfig/base.json +8 -2
  5. package/template/packages/config/tsconfig/with-payload.json +8 -2
  6. package/template/packages/src/app/api/trpc/[trpc]/route.ts +34 -0
  7. package/template/packages/src/app/layout/with-trpc.tsx +37 -0
  8. package/template/packages/src/app/page/base.tsx +4 -1
  9. package/template/packages/src/app/page/with-authjs-drizzle.tsx +4 -1
  10. package/template/packages/src/app/page/with-authjs-prisma.tsx +10 -1
  11. package/template/packages/src/app/page/with-authjs.tsx +4 -1
  12. package/template/packages/src/app/page/with-better-auth-drizzle.tsx +4 -1
  13. package/template/packages/src/app/page/with-better-auth-prisma.tsx +10 -1
  14. package/template/packages/src/app/page/with-better-auth.tsx +4 -1
  15. package/template/packages/src/app/page/with-drizzle.tsx +4 -1
  16. package/template/packages/src/app/page/with-payload.tsx +4 -1
  17. package/template/packages/src/app/page/with-prisma.tsx +10 -1
  18. package/template/packages/src/app/page/with-trpc.tsx +118 -0
  19. package/template/packages/src/components/greeting.tsx +21 -0
  20. package/template/packages/src/env/with-better-auth-db.js +2 -2
  21. package/template/packages/src/env/with-better-auth.js +2 -2
  22. package/template/packages/src/env/with-trpc-authjs-db.js +55 -0
  23. package/template/packages/src/env/with-trpc-authjs.js +53 -0
  24. package/template/packages/src/env/with-trpc-better-auth-db.js +52 -0
  25. package/template/packages/src/env/with-trpc-better-auth.js +50 -0
  26. package/template/packages/src/env/with-trpc-db.js +46 -0
  27. package/template/packages/src/env/with-trpc.js +44 -0
  28. package/template/packages/src/lib/api/client.tsx +85 -0
  29. package/template/packages/src/lib/api/query-client.ts +22 -0
  30. package/template/packages/src/lib/api/server.ts +31 -0
  31. package/template/packages/src/lib/auth/better-auth-client.ts +1 -1
  32. package/template/packages/src/lib/utils.ts +7 -0
  33. package/template/packages/src/server/api/init/base.ts +103 -0
  34. package/template/packages/src/server/api/init/with-authjs-db.ts +132 -0
  35. package/template/packages/src/server/api/init/with-authjs.ts +130 -0
  36. package/template/packages/src/server/api/init/with-betterauth-db.ts +134 -0
  37. package/template/packages/src/server/api/init/with-betterauth.ts +132 -0
  38. package/template/packages/src/server/api/init/with-db.ts +106 -0
  39. package/template/packages/src/server/api/root.ts +23 -0
  40. package/template/packages/src/server/api/routers/post/base.ts +46 -0
  41. package/template/packages/src/server/api/routers/post/with-auth-drizzle.ts +44 -0
  42. package/template/packages/src/server/api/routers/post/with-auth-prisma.ts +47 -0
  43. package/template/packages/src/server/api/routers/post/with-auth.ts +43 -0
  44. package/template/packages/src/server/api/routers/post/with-drizzle.ts +36 -0
  45. package/template/packages/src/server/api/routers/post/with-prisma.ts +37 -0
  46. package/template/packages/src/server/auth/better-auth-with-drizzle.ts +1 -1
  47. package/template/packages/src/server/auth/better-auth-with-prisma.ts +1 -1
  48. package/template/packages/src/server/auth/better-auth.ts +1 -0
  49. package/template/packages/src/server/auth/config/authjs-with-drizzle.ts +1 -1
  50. package/template/packages/src/server/auth/config/authjs-with-prisma.ts +1 -1
  51. package/template/packages/src/server/auth/config/authjs.ts +1 -1
  52. package/template/packages/src/server/db/prisma/with-mysql.ts +1 -1
  53. package/template/packages/src/server/db/prisma/with-postgresql.ts +1 -1
  54. package/template/packages/src/server/db/prisma/with-sqlite-bun.ts +1 -1
  55. package/template/packages/src/server/db/prisma/with-sqlite.ts +1 -1
  56. package/template/packages/src/server/db/schema-drizzle/with-authjs-mysql.ts +1 -1
  57. package/template/packages/src/server/db/schema-drizzle/with-authjs-postgresql.ts +1 -1
  58. package/template/packages/src/server/db/schema-drizzle/with-authjs-sqlite.ts +1 -1
@@ -0,0 +1,50 @@
1
+ import { createEnv } from "@t3-oss/env-nextjs"
2
+ import { z } from "zod"
3
+
4
+ export const env = createEnv({
5
+ /**
6
+ * Specify your server-side environment variables schema here. This way you can ensure the app
7
+ * isn't built with invalid env vars.
8
+ */
9
+ server: {
10
+ NODE_ENV: z
11
+ .enum(["development", "test", "production"])
12
+ .default("development"),
13
+ BETTER_AUTH_SECRET: z.string(),
14
+ DISCORD_CLIENT_ID: z.string(),
15
+ DISCORD_CLIENT_SECRET: z.string(),
16
+ },
17
+
18
+ /**
19
+ * Specify your client-side environment variables schema here. This way you can ensure the app
20
+ * isn't built with invalid env vars. To expose them to the client, prefix them with
21
+ * `NEXT_PUBLIC_`.
22
+ */
23
+ client: {
24
+ // NEXT_PUBLIC_CLIENTVAR: z.string(),
25
+ NEXT_PUBLIC_URL: z.url(),
26
+ },
27
+
28
+ /**
29
+ * You can't destruct `process.env` as a regular object in the Next.js edge runtimes (e.g.
30
+ * middlewares) or client-side so we need to destruct manually.
31
+ */
32
+ runtimeEnv: {
33
+ BETTER_AUTH_SECRET: process.env.BETTER_AUTH_SECRET,
34
+ DISCORD_CLIENT_ID: process.env.DISCORD_CLIENT_ID,
35
+ DISCORD_CLIENT_SECRET: process.env.DISCORD_CLIENT_SECRET,
36
+ NODE_ENV: process.env.NODE_ENV,
37
+ // NEXT_PUBLIC_CLIENTVAR: process.env.NEXT_PUBLIC_CLIENTVAR,
38
+ NEXT_PUBLIC_URL: process.env.NEXT_PUBLIC_URL,
39
+ },
40
+ /**
41
+ * Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. This is especially
42
+ * useful for Docker builds.
43
+ */
44
+ skipValidation: !!process.env.SKIP_ENV_VALIDATION,
45
+ /**
46
+ * Makes it so that empty strings are treated as undefined. `SOME_VAR: z.string()` and
47
+ * `SOME_VAR=''` will throw an error.
48
+ */
49
+ emptyStringAsUndefined: true,
50
+ })
@@ -0,0 +1,46 @@
1
+ import { createEnv } from "@t3-oss/env-nextjs"
2
+ import { z } from "zod"
3
+
4
+ export const env = createEnv({
5
+ /**
6
+ * Specify your server-side environment variables schema here. This way you can ensure the app
7
+ * isn't built with invalid env vars.
8
+ */
9
+ server: {
10
+ DATABASE_URL: z.url(),
11
+ NODE_ENV: z
12
+ .enum(["development", "test", "production"])
13
+ .default("development"),
14
+ },
15
+
16
+ /**
17
+ * Specify your client-side environment variables schema here. This way you can ensure the app
18
+ * isn't built with invalid env vars. To expose them to the client, prefix them with
19
+ * `NEXT_PUBLIC_`.
20
+ */
21
+ client: {
22
+ // NEXT_PUBLIC_CLIENTVAR: z.string(),
23
+ NEXT_PUBLIC_URL: z.url(),
24
+ },
25
+
26
+ /**
27
+ * You can't destruct `process.env` as a regular object in the Next.js edge runtimes (e.g.
28
+ * middlewares) or client-side so we need to destruct manually.
29
+ */
30
+ runtimeEnv: {
31
+ DATABASE_URL: process.env.DATABASE_URL,
32
+ NODE_ENV: process.env.NODE_ENV,
33
+ // NEXT_PUBLIC_CLIENTVAR: process.env.NEXT_PUBLIC_CLIENTVAR,
34
+ NEXT_PUBLIC_URL: process.env.NEXT_PUBLIC_URL,
35
+ },
36
+ /**
37
+ * Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. This is especially
38
+ * useful for Docker builds.
39
+ */
40
+ skipValidation: !!process.env.SKIP_ENV_VALIDATION,
41
+ /**
42
+ * Makes it so that empty strings are treated as undefined. `SOME_VAR: z.string()` and
43
+ * `SOME_VAR=''` will throw an error.
44
+ */
45
+ emptyStringAsUndefined: true,
46
+ })
@@ -0,0 +1,44 @@
1
+ import { createEnv } from "@t3-oss/env-nextjs"
2
+ import { z } from "zod"
3
+
4
+ export const env = createEnv({
5
+ /**
6
+ * Specify your server-side environment variables schema here. This way you can ensure the app
7
+ * isn't built with invalid env vars.
8
+ */
9
+ server: {
10
+ NODE_ENV: z
11
+ .enum(["development", "test", "production"])
12
+ .default("development"),
13
+ },
14
+
15
+ /**
16
+ * Specify your client-side environment variables schema here. This way you can ensure the app
17
+ * isn't built with invalid env vars. To expose them to the client, prefix them with
18
+ * `NEXT_PUBLIC_`.
19
+ */
20
+ client: {
21
+ // NEXT_PUBLIC_CLIENTVAR: z.string(),
22
+ NEXT_PUBLIC_URL: z.url(),
23
+ },
24
+
25
+ /**
26
+ * You can't destruct `process.env` as a regular object in the Next.js edge runtimes (e.g.
27
+ * middlewares) or client-side so we need to destruct manually.
28
+ */
29
+ runtimeEnv: {
30
+ NODE_ENV: process.env.NODE_ENV,
31
+ // NEXT_PUBLIC_CLIENTVAR: process.env.NEXT_PUBLIC_CLIENTVAR,
32
+ NEXT_PUBLIC_URL: process.env.NEXT_PUBLIC_URL,
33
+ },
34
+ /**
35
+ * Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. This is especially
36
+ * useful for Docker builds.
37
+ */
38
+ skipValidation: !!process.env.SKIP_ENV_VALIDATION,
39
+ /**
40
+ * Makes it so that empty strings are treated as undefined. `SOME_VAR: z.string()` and
41
+ * `SOME_VAR=''` will throw an error.
42
+ */
43
+ emptyStringAsUndefined: true,
44
+ })
@@ -0,0 +1,85 @@
1
+ "use client"
2
+
3
+ import { QueryClientProvider, type QueryClient } from "@tanstack/react-query"
4
+ import { httpBatchStreamLink, loggerLink } from "@trpc/client"
5
+ import { createTRPCReact } from "@trpc/react-query"
6
+ import { type inferRouterInputs, type inferRouterOutputs } from "@trpc/server"
7
+ import React from "react"
8
+ import superjson from "superjson"
9
+
10
+ import { getBaseUrl } from "@/lib/utils"
11
+ import { type AppRouter } from "@/server/api/root"
12
+
13
+ import { createQueryClient } from "./query-client"
14
+
15
+ let clientQueryClientSingleton: QueryClient | undefined = undefined
16
+ function getQueryClient() {
17
+ if (typeof window === "undefined") {
18
+ // Server: always make a new query client
19
+ return createQueryClient()
20
+ }
21
+
22
+ // Browser: use singleton pattern to keep the same query client
23
+ clientQueryClientSingleton ??= createQueryClient()
24
+ return clientQueryClientSingleton
25
+ }
26
+
27
+ export const api = createTRPCReact<AppRouter>()
28
+
29
+ /**
30
+ * Inference helper for inputs.
31
+ *
32
+ * @example type HelloInput = RouterInputs["helloWorld"]["hello"]
33
+ */
34
+ export type RouterInputs = inferRouterInputs<AppRouter>
35
+
36
+ /**
37
+ * Inference helper for outputs.
38
+ *
39
+ * @example type HelloOutput = RouterOutputs["helloWorld"]["hello"]
40
+ */
41
+ export type RouterOutputs = inferRouterOutputs<AppRouter>
42
+
43
+ export function TRPCReactProvider({ children }: React.PropsWithChildren) {
44
+ const queryClient = getQueryClient()
45
+
46
+ const [trpcClient] = React.useState(() =>
47
+ api.createClient({
48
+ links: [
49
+ /**
50
+ * The loggerLink is useful for debugging, but can be very noisy.
51
+ * You can disable Query logging by commenting out the process.env.NODE_ENV check.
52
+ *
53
+ * @example
54
+ * loggerLink({
55
+ * enabled: (opts) =>
56
+ * // process.env.NODE_ENV === "development" ||
57
+ * opts.direction === "down" && opts.result instanceof Error,
58
+ * }),
59
+ */
60
+ loggerLink({
61
+ enabled: (opts) =>
62
+ process.env.NODE_ENV === "development" ||
63
+ (opts.direction === "down" && opts.result instanceof Error),
64
+ }),
65
+ httpBatchStreamLink({
66
+ transformer: superjson,
67
+ url: `${getBaseUrl()}/api/trpc`,
68
+ headers() {
69
+ const headers = new Headers()
70
+ headers.set("x-trpc-source", "nextjs-react")
71
+ return headers
72
+ },
73
+ }),
74
+ ],
75
+ })
76
+ )
77
+
78
+ return (
79
+ <QueryClientProvider client={queryClient}>
80
+ <api.Provider client={trpcClient} queryClient={queryClient}>
81
+ {children}
82
+ </api.Provider>
83
+ </QueryClientProvider>
84
+ )
85
+ }
@@ -0,0 +1,22 @@
1
+ import { defaultShouldDehydrateQuery, QueryClient } from "@tanstack/react-query"
2
+ import superjson from "superjson"
3
+
4
+ export const createQueryClient = () =>
5
+ new QueryClient({
6
+ defaultOptions: {
7
+ queries: {
8
+ // With SSR, we usually want to set some default staleTime
9
+ // above 0 to avoid refetching immediately on the client
10
+ staleTime: 1000 * 30,
11
+ },
12
+ dehydrate: {
13
+ serializeData: superjson.serialize,
14
+ shouldDehydrateQuery: (query) =>
15
+ defaultShouldDehydrateQuery(query) ||
16
+ query.state.status === "pending",
17
+ },
18
+ hydrate: {
19
+ deserializeData: superjson.deserialize,
20
+ },
21
+ },
22
+ })
@@ -0,0 +1,31 @@
1
+ import "server-only"
2
+
3
+ import { createHydrationHelpers } from "@trpc/react-query/rsc"
4
+ import { headers } from "next/headers"
5
+ import React from "react"
6
+
7
+ import { createTRPCContext } from "@/server/api/init"
8
+ import { createCaller, type AppRouter } from "@/server/api/root"
9
+
10
+ import { createQueryClient } from "./query-client"
11
+
12
+ /**
13
+ * This wraps the `createTRPCContext` helper and provides the required context for the tRPC API when
14
+ * handling a tRPC call from a React Server Component.
15
+ */
16
+ const createContext = React.cache(async () => {
17
+ const heads = new Headers(await headers())
18
+ heads.set("x-trpc-source", "rsc")
19
+
20
+ return createTRPCContext({
21
+ headers: heads,
22
+ })
23
+ })
24
+
25
+ const caller = createCaller(createContext)
26
+ const getQueryClient = React.cache(createQueryClient)
27
+
28
+ export const { trpc: api, HydrateClient } = createHydrationHelpers<AppRouter>(
29
+ caller,
30
+ getQueryClient
31
+ )
@@ -3,7 +3,7 @@ import { createAuthClient } from "better-auth/react"
3
3
  import { env } from "@/env"
4
4
 
5
5
  export const authClient = createAuthClient({
6
- baseURL: env.NEXT_PUBLIC_BETTER_AUTH_URL,
6
+ baseURL: env.NEXT_PUBLIC_URL,
7
7
  })
8
8
 
9
9
  export const { signIn, signOut, useSession } = authClient
@@ -0,0 +1,7 @@
1
+ import { env } from "@/env"
2
+
3
+ export function getBaseUrl() {
4
+ if (typeof window !== "undefined") return window.location.origin
5
+ if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`
6
+ return env.NEXT_PUBLIC_URL
7
+ }
@@ -0,0 +1,103 @@
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
+ import { initTRPC } from "@trpc/server"
10
+ import superjson from "superjson"
11
+ import { z, ZodError } from "zod"
12
+
13
+ /**
14
+ * 1. CONTEXT
15
+ *
16
+ * This section defines the "contexts" that are available in the backend API.
17
+ *
18
+ * These allow you to access things when processing a request, like the database, the session, etc.
19
+ *
20
+ * This helper generates the "internals" for a tRPC context. The API handler and RSC clients each
21
+ * wrap this and provides the required context.
22
+ *
23
+ * @see https://trpc.io/docs/server/context
24
+ */
25
+ export async function createTRPCContext(opts: { headers: Headers }) {
26
+ return {
27
+ ...opts,
28
+ }
29
+ }
30
+
31
+ /**
32
+ * 2. INITIALIZATION
33
+ *
34
+ * This is where the tRPC API is initialized, connecting the context and transformer. We also parse
35
+ * ZodErrors so that you get typesafety on the frontend if your procedure fails due to validation
36
+ * errors on the backend.
37
+ */
38
+ const t = initTRPC.context<typeof createTRPCContext>().create({
39
+ transformer: superjson,
40
+ errorFormatter({ shape, error }) {
41
+ return {
42
+ ...shape,
43
+ data: {
44
+ ...shape.data,
45
+ zodError:
46
+ error.cause instanceof ZodError ? z.treeifyError(error.cause) : null,
47
+ },
48
+ }
49
+ },
50
+ })
51
+
52
+ /**
53
+ * Create a server-side caller.
54
+ *
55
+ * @see https://trpc.io/docs/server/server-side-calls
56
+ */
57
+ export const createCallerFactory = t.createCallerFactory
58
+
59
+ /**
60
+ * 3. ROUTER & PROCEDURE (THE IMPORTANT BIT)
61
+ *
62
+ * These are the pieces you use to build your tRPC API. You should import these a lot in the
63
+ * "/src/server/api/routers" directory.
64
+ */
65
+
66
+ /**
67
+ * This is how you create new routers and sub-routers in your tRPC API.
68
+ *
69
+ * @see https://trpc.io/docs/router
70
+ */
71
+ export const createTRPCRouter = t.router
72
+
73
+ /**
74
+ * Middleware for timing procedure execution and adding an artificial delay in development.
75
+ *
76
+ * You can remove this if you don't like it, but it can help catch unwanted waterfalls by simulating
77
+ * network latency that would occur in production but not in local development.
78
+ */
79
+ const timingMiddleware = t.middleware(async ({ next, path }) => {
80
+ const start = Date.now()
81
+
82
+ if (t._config.isDev) {
83
+ // artificial delay in dev
84
+ const waitMs = Math.floor(Math.random() * 400) + 100
85
+ await new Promise((resolve) => setTimeout(resolve, waitMs))
86
+ }
87
+
88
+ const result = await next()
89
+
90
+ const end = Date.now()
91
+ console.log(`[TRPC] ${path} took ${end - start}ms to execute`)
92
+
93
+ return result
94
+ })
95
+
96
+ /**
97
+ * Public (unauthenticated) procedure
98
+ *
99
+ * This is the base piece you use to build new queries and mutations on your tRPC API. It does not
100
+ * guarantee that a user querying is authorized, but you can still access user session data if they
101
+ * are logged in.
102
+ */
103
+ export const publicProcedure = t.procedure.use(timingMiddleware)
@@ -0,0 +1,132 @@
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
+ import { initTRPC, TRPCError } from "@trpc/server"
10
+ import superjson from "superjson"
11
+ import { z, ZodError } from "zod"
12
+
13
+ import { auth } from "@/server/auth"
14
+ import { db } from "@/server/db"
15
+
16
+ /**
17
+ * 1. CONTEXT
18
+ *
19
+ * This section defines the "contexts" that are available in the backend API.
20
+ *
21
+ * These allow you to access things when processing a request, like the database, the session, etc.
22
+ *
23
+ * This helper generates the "internals" for a tRPC context. The API handler and RSC clients each
24
+ * wrap this and provides the required context.
25
+ *
26
+ * @see https://trpc.io/docs/server/context
27
+ */
28
+ export async function createTRPCContext(opts: { headers: Headers }) {
29
+ const session = await auth()
30
+
31
+ return {
32
+ db,
33
+ session,
34
+ ...opts,
35
+ }
36
+ }
37
+
38
+ /**
39
+ * 2. INITIALIZATION
40
+ *
41
+ * This is where the tRPC API is initialized, connecting the context and transformer. We also parse
42
+ * ZodErrors so that you get typesafety on the frontend if your procedure fails due to validation
43
+ * errors on the backend.
44
+ */
45
+ const t = initTRPC.context<typeof createTRPCContext>().create({
46
+ transformer: superjson,
47
+ errorFormatter({ shape, error }) {
48
+ return {
49
+ ...shape,
50
+ data: {
51
+ ...shape.data,
52
+ zodError:
53
+ error.cause instanceof ZodError ? z.treeifyError(error.cause) : null,
54
+ },
55
+ }
56
+ },
57
+ })
58
+
59
+ /**
60
+ * Create a server-side caller.
61
+ *
62
+ * @see https://trpc.io/docs/server/server-side-calls
63
+ */
64
+ export const createCallerFactory = t.createCallerFactory
65
+
66
+ /**
67
+ * 3. ROUTER & PROCEDURE (THE IMPORTANT BIT)
68
+ *
69
+ * These are the pieces you use to build your tRPC API. You should import these a lot in the
70
+ * "/src/server/api/routers" directory.
71
+ */
72
+
73
+ /**
74
+ * This is how you create new routers and sub-routers in your tRPC API.
75
+ *
76
+ * @see https://trpc.io/docs/router
77
+ */
78
+ export const createTRPCRouter = t.router
79
+
80
+ /**
81
+ * Middleware for timing procedure execution and adding an artificial delay in development.
82
+ *
83
+ * You can remove this if you don't like it, but it can help catch unwanted waterfalls by simulating
84
+ * network latency that would occur in production but not in local development.
85
+ */
86
+ const timingMiddleware = t.middleware(async ({ next, path }) => {
87
+ const start = Date.now()
88
+
89
+ if (t._config.isDev) {
90
+ // artificial delay in dev
91
+ const waitMs = Math.floor(Math.random() * 400) + 100
92
+ await new Promise((resolve) => setTimeout(resolve, waitMs))
93
+ }
94
+
95
+ const result = await next()
96
+
97
+ const end = Date.now()
98
+ console.log(`[TRPC] ${path} took ${end - start}ms to execute`)
99
+
100
+ return result
101
+ })
102
+
103
+ /**
104
+ * Public (unauthenticated) procedure
105
+ *
106
+ * This is the base piece you use to build new queries and mutations on your tRPC API. It does not
107
+ * guarantee that a user querying is authorized, but you can still access user session data if they
108
+ * are logged in.
109
+ */
110
+ export const publicProcedure = t.procedure.use(timingMiddleware)
111
+
112
+ /**
113
+ * Protected (authenticated) procedure
114
+ *
115
+ * If you want a query or mutation to ONLY be accessible to logged in users, use this. It verifies
116
+ * the session is valid and guarantees `ctx.session.user` is not null.
117
+ *
118
+ * @see https://trpc.io/docs/procedures
119
+ */
120
+ export const protectedProcedure = t.procedure
121
+ .use(timingMiddleware)
122
+ .use(({ ctx, next }) => {
123
+ if (!ctx.session?.user) {
124
+ throw new TRPCError({ code: "UNAUTHORIZED" })
125
+ }
126
+ return next({
127
+ ctx: {
128
+ // infers the `session` as non-nullable
129
+ session: { ...ctx.session, user: ctx.session.user },
130
+ },
131
+ })
132
+ })
@@ -0,0 +1,130 @@
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
+ import { initTRPC, TRPCError } from "@trpc/server"
10
+ import superjson from "superjson"
11
+ import { z, ZodError } from "zod"
12
+
13
+ import { auth } from "@/server/auth"
14
+
15
+ /**
16
+ * 1. CONTEXT
17
+ *
18
+ * This section defines the "contexts" that are available in the backend API.
19
+ *
20
+ * These allow you to access things when processing a request, like the database, the session, etc.
21
+ *
22
+ * This helper generates the "internals" for a tRPC context. The API handler and RSC clients each
23
+ * wrap this and provides the required context.
24
+ *
25
+ * @see https://trpc.io/docs/server/context
26
+ */
27
+ export async function createTRPCContext(opts: { headers: Headers }) {
28
+ const session = await auth()
29
+
30
+ return {
31
+ session,
32
+ ...opts,
33
+ }
34
+ }
35
+
36
+ /**
37
+ * 2. INITIALIZATION
38
+ *
39
+ * This is where the tRPC API is initialized, connecting the context and transformer. We also parse
40
+ * ZodErrors so that you get typesafety on the frontend if your procedure fails due to validation
41
+ * errors on the backend.
42
+ */
43
+ const t = initTRPC.context<typeof createTRPCContext>().create({
44
+ transformer: superjson,
45
+ errorFormatter({ shape, error }) {
46
+ return {
47
+ ...shape,
48
+ data: {
49
+ ...shape.data,
50
+ zodError:
51
+ error.cause instanceof ZodError ? z.treeifyError(error.cause) : null,
52
+ },
53
+ }
54
+ },
55
+ })
56
+
57
+ /**
58
+ * Create a server-side caller.
59
+ *
60
+ * @see https://trpc.io/docs/server/server-side-calls
61
+ */
62
+ export const createCallerFactory = t.createCallerFactory
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 a lot in the
68
+ * "/src/server/api/routers" directory.
69
+ */
70
+
71
+ /**
72
+ * This is how you create new routers and sub-routers in your tRPC API.
73
+ *
74
+ * @see https://trpc.io/docs/router
75
+ */
76
+ export const createTRPCRouter = t.router
77
+
78
+ /**
79
+ * Middleware for timing procedure execution and adding an artificial delay in development.
80
+ *
81
+ * You can remove this if you don't like it, but it can help catch unwanted waterfalls by simulating
82
+ * network latency that would occur in production but not in local development.
83
+ */
84
+ const timingMiddleware = t.middleware(async ({ next, path }) => {
85
+ const start = Date.now()
86
+
87
+ if (t._config.isDev) {
88
+ // artificial delay in dev
89
+ const waitMs = Math.floor(Math.random() * 400) + 100
90
+ await new Promise((resolve) => setTimeout(resolve, waitMs))
91
+ }
92
+
93
+ const result = await next()
94
+
95
+ const end = Date.now()
96
+ console.log(`[TRPC] ${path} took ${end - start}ms to execute`)
97
+
98
+ return result
99
+ })
100
+
101
+ /**
102
+ * Public (unauthenticated) procedure
103
+ *
104
+ * This is the base piece you use to build new queries and mutations on your tRPC API. It does not
105
+ * guarantee that a user querying is authorized, but you can still access user session data if they
106
+ * are logged in.
107
+ */
108
+ export const publicProcedure = t.procedure.use(timingMiddleware)
109
+
110
+ /**
111
+ * Protected (authenticated) procedure
112
+ *
113
+ * If you want a query or mutation to ONLY be accessible to logged in users, use this. It verifies
114
+ * the session is valid and guarantees `ctx.session.user` is not null.
115
+ *
116
+ * @see https://trpc.io/docs/procedures
117
+ */
118
+ export const protectedProcedure = t.procedure
119
+ .use(timingMiddleware)
120
+ .use(({ ctx, next }) => {
121
+ if (!ctx.session?.user) {
122
+ throw new TRPCError({ code: "UNAUTHORIZED" })
123
+ }
124
+ return next({
125
+ ctx: {
126
+ // infers the `session` as non-nullable
127
+ session: { ...ctx.session, user: ctx.session.user },
128
+ },
129
+ })
130
+ })