Skip to content

Nuxt.js Adapter

Nuxt.js is a popular Vue.js framework for building server-side applications. It built on top of Nitro server a lightweight, high-performance Node.js runtime. 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/node'

const handler = new RPCHandler(router)

export default defineEventHandler(async (event) => {
  const { matched } = await handler.handle(
    event.node.req,
    event.node.res,
    {
      prefix: '/rpc',
      context: {}, // Provide initial context if needed
    }
  )

  if (matched) {
    return
  }

  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: () => Object.fromEntries(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.