Skip to content

Nuxt.js Adapter

Nuxt.js is a popular Vue.js framework for building server-side applications. For more details, see the HTTP Adapter guide.

Server

You set up an oRPC server inside Nuxt using its Server Routes.

ts
import { RPCHandler } from '@orpc/server/fetch'

const handler = new RPCHandler(router)

export default defineEventHandler(async (event) => {
  const request = toWebRequest(event)

  const { response } = await handler.handle(request, {
    prefix: '/rpc',
    context: {}, // Provide initial context if needed
  })

  if (response) {
    return response
  }

  setResponseStatus(event, 404, 'Not Found')
  return 'Not found'
})
ts
export { default } from './[...]'

INFO

The handler can be any supported oRPC handler, such as RPCHandler, OpenAPIHandler, or another custom handler.

Client

To make the oRPC client compatible with SSR, set it up inside a Nuxt Plugin.

plugins/orpc.ts
ts
export default defineNuxtPlugin(() => {
  const event = useRequestEvent()

  const link = new RPCLink({
    url: `${typeof window !== 'undefined' ? window.location.origin : 'http://localhost:3000'}/rpc`,
    headers: event?.headers,
  })

  const client: RouterClient<typeof router> = createORPCClient(link)

  return {
    provide: {
      client,
    },
  }
})

INFO

You can learn more about client setup in Client-Side Clients.

Optimize SSR

To reduce HTTP requests and improve latency during SSR, you can utilize a Server-Side Client during SSR. Below is a quick setup, see Optimize SSR for more details.

ts
export default defineNuxtPlugin(() => {
  const link = new RPCLink({
    url: `${window.location.origin}/rpc`,
    headers: () => ({}),
  })

  const client: RouterClient<typeof router> = createORPCClient(link)

  return {
    provide: {
      client,
    },
  }
})
ts
export default defineNuxtPlugin((nuxt) => {
  const event = useRequestEvent()

  const client = createRouterClient(router, {
    context: {
      headers: event?.headers, // provide headers if initial context required
    },
  })

  return {
    provide: {
      client,
    },
  }
})

Released under the MIT License.