Skip to Content
🎉 gRPCity 3.0 is released. Read more →

Server

Server owns the server-side lifecycle: build it from a loader, register one or more service implementations, optionally wrap everything in middleware, then listen(). A single instance can host multiple services in the same process.

Initialization

const server = await loader.initServer(serverOptions)

serverOptions:

  • channelOptions (optional) — channel-level configuration for the underlying gRPC server.
  • credentials (optional) — server-side credentials for TLS.

See the Config Guide for channelOptions defaults and the Credentials Guide for TLS setup.

Binding a service

server.add(name, implementation, options)
  • name (required) — fully qualified service name from the proto, including the package.
  • implementation (required) — an object or class instance whose methods match the service’s RPCs.
  • options (optional)
    • exclude (string[]) — names of methods on implementation that should not be bound (e.g. private helpers).
    • inherit — when implementation inherits its handlers, pass the parent class so the inherited methods are still discovered.

Removing a service

server.remove(name)

name is the same fully qualified service name you passed to add().

Middleware

server.use() wraps every handler before and after it runs. See the Server Middleware Guide for the (ctx, next) shape.

// add one at a time server.use(f1) server.use(f2) server.use(f3) // or pass several positional middlewares server.use(f1, f2, f3) // or pass an array server.use([f1, f2, f3])

Middleware only runs around async handlers. The callback form bypasses it.

Returning errors from a handler

Just throw. gRPCity catches the thrown Error and turns it into a gRPC status on the wire for any of the four RPC kinds (unary, client stream, server stream, bidi).

For server-stream and bidi handlers in particular, throwing is the correct way to fail — gRPCity routes the error through the underlying server stream’s 'error' channel, so the client receives the status trailer immediately rather than waiting for its deadline. See the Error guide for what the client sees.

Certificates and startup

listen(addr, credentials?) starts the server.

  • addr (required) — host and port. Two shapes:
    • string in host:port form, e.g. '127.0.0.1:9099'.
    • object { host, port }, where port must be in [0, 65535].
  • credentials (optional) — built with loader.makeServerCredentials().
const credentials = loader.makeServerCredentials(rootCerts, keyCertPairs, checkClientCertificate) // either form is fine await server.listen('127.0.0.1:9099', credentials) await server.listen({ host: '127.0.0.1', port: 9099 }, credentials)

Credentials precedence: listen() > initServer() > built-in default.

Shutting down

// graceful — waits for in-flight calls to finish await server.shutdown() // forceful — closes everything immediately server.forceShutdown()
Last updated on