Node HTTP Adapter
Use oRPC with Node HTTP, HTTPS, and HTTP2 servers via RPCHandler or OpenAPIHandler, with CORS and event stream options.
Server Usage
import { createServer } from 'node:http' // or 'node:https' or 'node:http2'
import { RPCHandler } from '@orpc/server/node'
import { CORSHandlerPlugin } from '@orpc/server/plugins'
import { onError } from '@orpc/server'
const handler = new RPCHandler(router, {
plugins: [new CORSHandlerPlugin()],
interceptors: [
onError((error) => {
console.error(error)
}),
],
})
const server = createServer(async (req, res) => {
const { matched } = await handler.handle(req, res, {
prefix: '/rpc',
context: {}, // Provide initial context if needed, can be an async function
})
if (matched) {
return
}
res.statusCode = 404
res.end('Not found')
})
server.listen(3000, '127.0.0.1', () => console.log('Listening on 127.0.0.1:3000'))import { createServer } from 'node:http' // or 'node:https' or 'node:http2'
import { OpenAPIHandler } from '@orpc/openapi/node'
import { CORSHandlerPlugin } from '@orpc/server/plugins'
import { onError } from '@orpc/server'
const handler = new OpenAPIHandler(router, {
plugins: [new CORSHandlerPlugin()],
interceptors: [
onError((error) => {
console.error(error)
}),
],
})
const server = createServer(async (req, res) => {
const { matched } = await handler.handle(req, res, {
prefix: '/api',
context: {}, // Provide initial context if needed, can be an async function
})
if (matched) {
return
}
res.statusCode = 404
res.end('Not found')
})
server.listen(3000, '127.0.0.1', () => console.log('Listening on 127.0.0.1:3000'))Event Stream Options
You can configure how an AsyncIteratorObject is streamed to the client using the sendStandardResponse.eventStream options when creating the handler.
const handler = new OpenAPIHandler(router, {
sendStandardResponse: {
eventStream: {
/**
* Initial comment sent immediately upon stream start to flush headers. This allows the
* receiving side to establish the connection without waiting for the first event.
*
* `false` disables it, an object customizes it.
*
* @default true
*/
initialComment: {
/**
* The content of the initial comment sent upon stream start. Must not include newline characters.
*
* @default ''
*/
comment: '',
},
/**
* Ping comment sent periodically to keep the connection alive.
*
* `false` disables it, an object customizes it.
*
* @default true
*/
keepAlive: {
/**
* Interval (in milliseconds) between ping comments sent after the last event.
*
* @default 15000
*/
interval: 15000,
/**
* The content of the ping comment. Must not include newline characters.
*
* @default ''
*/
comment: '',
},
},
},
})