or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

client-operations.mdconstants.mdcredentials.mdindex.mdinterceptors.mdmetadata.mdserver-operations.mdservice-definitions.md
tile.json

tessl/npm-grpc--grpc-js

Pure JavaScript gRPC implementation for Node.js with comprehensive client-server communication capabilities

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@grpc/grpc-js@1.13.x

To install, run

npx @tessl/cli install tessl/npm-grpc--grpc-js@1.13.0

index.mddocs/

@grpc/grpc-js

@grpc/grpc-js is a pure JavaScript implementation of gRPC for Node.js that operates without requiring C++ addons or native dependencies. It serves as a comprehensive communication framework enabling high-performance remote procedure calls between distributed systems, supporting both client and server functionality with features including automatic reconnection, streaming capabilities, metadata handling, compression support, multiple load balancing policies, client and server interceptors, connection keepalives, and HTTP proxy support.

Package Information

  • Package Name: @grpc/grpc-js
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @grpc/grpc-js

Note: This documentation covers the stable public API. Experimental APIs in the grpc.experimental namespace are excluded as they may change in minor version updates.

Core Imports

import * as grpc from "@grpc/grpc-js";

For specific imports:

import {
  Server,
  ServerCredentials,
  Client,
  credentials,
  Metadata,
  loadPackageDefinition,
  makeClientConstructor
} from "@grpc/grpc-js";

CommonJS:

const grpc = require("@grpc/grpc-js");
const { Server, ServerCredentials, Client, credentials } = require("@grpc/grpc-js");

Basic Usage

Creating a gRPC Server

import { Server, ServerCredentials } from "@grpc/grpc-js";

const server = new Server();

// Add service implementation
server.addService(serviceDefinition, {
  sayHello: (call, callback) => {
    callback(null, { message: `Hello ${call.request.name}` });
  }
});

// Bind and start server
server.bindAsync(
  "localhost:50051",
  ServerCredentials.createInsecure(),
  (error, port) => {
    if (error) {
      console.error("Server bind failed:", error);
      return;
    }
    console.log(`Server running on port ${port}`);
    server.start();
  }
);

Creating a gRPC Client

import { credentials, makeClientConstructor, loadPackageDefinition } from "@grpc/grpc-js";
import { loadSync } from "@grpc/proto-loader";

// Load service definition
const packageDefinition = loadSync("path/to/service.proto");
const protoDescriptor = loadPackageDefinition(packageDefinition);

// Create client constructor
const ClientConstructor = makeClientConstructor(
  protoDescriptor.mypackage.MyService,
  "MyService"
);

// Create client instance
const client = new ClientConstructor(
  "localhost:50051",
  credentials.createInsecure()
);

// Make a call
client.sayHello({ name: "World" }, (error, response) => {
  if (error) {
    console.error("Call failed:", error);
    return;
  }
  console.log("Response:", response.message);
});

Architecture

@grpc/grpc-js is built around several key components:

  • Channel Management: Low-level connection handling with automatic reconnection and load balancing
  • Client System: High-level client abstraction with support for all call types (unary, streaming)
  • Server System: Flexible server implementation supporting service registration and middleware
  • Credentials System: Comprehensive security model supporting both channel and call-level authentication
  • Interceptor Framework: Request/response interception for both client and server sides
  • Metadata System: Header and trailer management for cross-cutting concerns
  • Service Configuration: Dynamic configuration for load balancing, retries, and service policies

Capabilities

Client Operations

Complete client-side gRPC functionality including call types, credentials, and interceptors. Supports unary, client streaming, server streaming, and bidirectional streaming calls.

class Client {
  constructor(address: string, credentials: ChannelCredentials, options?: Partial<ClientOptions>);
  close(): void;
  waitForReady(deadline: Date | number, callback: (error?: Error) => void): void;
  getChannel(): Channel;
}

interface ClientOptions {
  interceptors?: Interceptor[];
  interceptor_providers?: InterceptorProvider[];
  channelOverride?: Channel;
  channelFactoryOverride?: (address: string, credentials: ChannelCredentials, options: ChannelOptions) => Channel;
}

Client Operations

Server Operations

Server-side gRPC functionality including service registration, handler functions, and server lifecycle management.

class Server {
  constructor(options?: Partial<ServerOptions>);
  addService<UntypedServiceImplementation>(
    service: ServiceDefinition,
    implementation: UntypedServiceImplementation
  ): void;
  bindAsync(
    port: string,
    creds: ServerCredentials,
    callback: (error: Error | null, port: number) => void
  ): void;
  start(): void;
  tryShutdown(callback: (error?: Error) => void): void;
  forceShutdown(): void;
}

interface ServerOptions extends ChannelOptions {
  interceptors?: ServerInterceptor[];
}

Server Operations

Credentials and Security

Comprehensive security system supporting SSL/TLS, OAuth2, metadata-based authentication, and custom credential providers.

const credentials: {
  createInsecure(): ChannelCredentials;
  createSsl(
    rootCerts?: Buffer | null,
    privateKey?: Buffer | null,
    certChain?: Buffer | null,
    verifyOptions?: VerifyOptions
  ): ChannelCredentials;
  combineChannelCredentials(
    channelCredentials: ChannelCredentials,
    ...callCredentials: CallCredentials[]
  ): ChannelCredentials;
  combineCallCredentials(
    first: CallCredentials,
    ...additional: CallCredentials[]
  ): CallCredentials;
  createFromMetadataGenerator(metadataGenerator: CallMetadataGenerator): CallCredentials;
  createFromGoogleCredential(googleCredential: OAuth2Client): CallCredentials;
};

Credentials System

Metadata Management

Header and trailer management system for passing cross-cutting concerns and request context between client and server.

class Metadata {
  constructor(options?: MetadataOptions);
  set(key: string, value: MetadataValue): void;
  add(key: string, value: MetadataValue): void;
  remove(key: string): void;
  get(key: string): MetadataValue[];
  getMap(): { [key: string]: MetadataValue };
  clone(): Metadata;
  merge(other: Metadata): void;
}

interface MetadataOptions {
  idempotentRequest?: boolean;
  waitForReady?: boolean;
  cacheableRequest?: boolean;
  corked?: boolean;
}

type MetadataValue = string | Buffer;

Metadata System

Service Definitions and Code Generation

Tools for loading Protocol Buffer definitions and generating client constructors for type-safe service communication.

function loadPackageDefinition(packageDef: PackageDefinition): GrpcObject;

function makeClientConstructor(
  methods: ServiceDefinition,
  serviceName: string,
  classOptions?: {}
): ServiceClientConstructor;

interface ServiceDefinition {
  [methodName: string]: MethodDefinition<any, any>;
}

interface MethodDefinition<RequestType, ResponseType> {
  path: string;
  requestStream: boolean;
  responseStream: boolean;
  requestSerialize: Serialize<RequestType>;
  responseDeserialize: Deserialize<ResponseType>;
  originalName?: string;
}

Service Definitions

Interceptors

Request/response interception framework for implementing cross-cutting concerns like logging, authentication, and metrics on both client and server sides.

interface Interceptor {
  (options: InterceptorOptions, nextCall: NextCall): InterceptingCall;
}

interface ServerInterceptor {
  <ReqType, RespType>(
    methodDescriptor: ServerMethodDefinition<ReqType, RespType>,
    call: ServerInterceptingCallInterface<ReqType>
  ): ServerInterceptingCall<ReqType, RespType>;
}

Interceptors

Constants and Enums

Core gRPC constants including status codes, connectivity states, compression algorithms, and other enumerated values.

enum status {
  OK = 0,
  CANCELLED = 1,
  UNKNOWN = 2,
  INVALID_ARGUMENT = 3,
  DEADLINE_EXCEEDED = 4,
  NOT_FOUND = 5,
  ALREADY_EXISTS = 6,
  PERMISSION_DENIED = 7,
  RESOURCE_EXHAUSTED = 8,
  FAILED_PRECONDITION = 9,
  ABORTED = 10,
  OUT_OF_RANGE = 11,
  UNIMPLEMENTED = 12,
  INTERNAL = 13,
  UNAVAILABLE = 14,
  DATA_LOSS = 15,
  UNAUTHENTICATED = 16
}

enum connectivityState {
  IDLE = 0,
  CONNECTING = 1,
  READY = 2,
  TRANSIENT_FAILURE = 3,
  SHUTDOWN = 4
}

Constants and Enums

Types

Core Interface Types

interface StatusObject {
  code: status;
  details: string;
  metadata: Metadata;
}

interface CallOptions {
  deadline?: Date | number;
  host?: string;
  parent?: Call;
  propagate_flags?: number;
  credentials?: CallCredentials;
  interceptors?: Interceptor[];
  interceptor_providers?: InterceptorProvider[];
}

type Deadline = Date | number;

type Call = ClientUnaryCall | ClientReadableStream<any> | ClientWritableStream<any> | ClientDuplexStream<any, any>;

interface ServiceError extends Error {
  code: status;
  details: string;
  metadata: Metadata;
}

Stream Types

interface ClientUnaryCall extends EventEmitter {
  cancel(): void;
  getPeer(): string;
}

interface ClientReadableStream<ResponseType> extends Readable {
  cancel(): void;
  getPeer(): string;
}

interface ClientWritableStream<RequestType> extends Writable {
  cancel(): void;
  getPeer(): string;
}

interface ClientDuplexStream<RequestType, ResponseType> extends Duplex {
  cancel(): void;
  getPeer(): string;
}