Skip to content

Commit

Permalink
feat: use globalThis.$fetch to call API handler directly on server-side
Browse files Browse the repository at this point in the history
  • Loading branch information
robinWongM committed Sep 16, 2022
1 parent cdf29be commit ee3ee48
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 3 deletions.
2 changes: 1 addition & 1 deletion playground/nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import Module from '../src/module'
export default defineNuxtConfig({
modules: [Module],
runtimeConfig: {
baseURL: 'http://localhost:3000',
baseURL: '',
},
typescript: {
strict: true,
Expand Down
2 changes: 1 addition & 1 deletion src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export default defineNuxtModule<ModuleOptions>({
configKey: 'trpc',
},
defaults: {
baseURL: 'http://localhost:3000',
baseURL: '',
endpoint: '/trpc',
},
async setup(options, nuxt) {
Expand Down
9 changes: 8 additions & 1 deletion src/runtime/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,21 @@ export default defineNuxtPlugin((nuxtApp) => {
const config = useRuntimeConfig().public.trpc
const headers = useRequestHeaders()
const otherHeaders = useClientHeaders()

const baseURL = process.server ? '' : config.baseURL
const client = trpc.createTRPCClient<AppRouter>({
url: `${config.baseURL}${config.endpoint}`,
url: `${baseURL}${config.endpoint}`,
headers: () => {
return {
...unref(otherHeaders),
...headers,
}
},
fetch: (input, options) =>
globalThis.$fetch.raw(input.toString(), options).then(response => ({
...response,
json: () => Promise.resolve(response._data),
}))
})

nuxtApp.provide('client', client)
Expand Down

0 comments on commit ee3ee48

Please sign in to comment.