@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.
npm install @grpc/grpc-jsNote: This documentation covers the stable public API. Experimental APIs in the grpc.experimental namespace are excluded as they may change in minor version updates.
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");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();
}
);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);
});@grpc/grpc-js is built around several key components:
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;
}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[];
}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;
};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;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;
}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>;
}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
}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;
}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;
}