This repository was archived by the owner on Mar 25, 2025. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathtrpc.ts
More file actions
72 lines (64 loc) · 2.15 KB
/
Copy pathtrpc.ts
File metadata and controls
72 lines (64 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { httpBatchLink, loggerLink } from '@trpc/client'
import { createTRPCNext } from '@trpc/next'
import { inferRouterInputs } from '@trpc/server'
import superjson from 'superjson'
import type { AppRouter } from '../server/routers/_app'
export type RouterOutput = inferRouterInputs<AppRouter>
export type RouterInput = inferRouterInputs<AppRouter>
function getBaseUrl() {
if (typeof window !== 'undefined')
// browser should use relative path
return ''
if (process.env.VERCEL_URL)
// reference for vercel.com
return `https://${process.env.VERCEL_URL}`
if (process.env.RENDER_INTERNAL_HOSTNAME)
// reference for render.com
return `http://${process.env.RENDER_INTERNAL_HOSTNAME}:${process.env.PORT}`
// assume localhost
return `http://localhost:${process.env.PORT ?? 3000}`
}
export const trpc = createTRPCNext<AppRouter>({
config(opts) {
const { ctx } = opts
return {
transformer: superjson,
links: [
loggerLink({
enabled: (opts) =>
process.env.NODE_ENV === 'development' ||
(opts.direction === 'down' && opts.result instanceof Error),
}),
httpBatchLink({
/**
* If you want to use SSR, you need to use the server's full URL
* @link https://trpc.io/docs/ssr
**/
url: `${getBaseUrl()}/api/trpc`,
headers() {
if (ctx?.req) {
// To use SSR properly, you need to forward the client's headers to the server
// This is so you can pass through things like cookies when we're server-side rendering
// If you're using Node 18, omit the "connection" header
const {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
connection: _connection,
...headers
} = ctx.req.headers
return {
...headers,
// Optional: inform server that it's an SSR request
'x-ssr': '1',
}
}
return {}
},
}),
],
}
},
/**
* @link https://trpc.io/docs/ssr
**/
ssr: true,
})