> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/grafana/k6/llms.txt
> Use this file to discover all available pages before exploring further.

# k6/net/grpc

> gRPC client for testing gRPC services.

The `k6/net/grpc` module provides a gRPC client for testing gRPC services.

## Client

The Client class is used to interact with gRPC services.

### Constructor

```javascript theme={null}
import grpc from 'k6/net/grpc';

const client = new grpc.Client();
```

## Methods

### load(importPaths, ...protoFiles)

Loads protocol buffer definitions from proto files.

<ParamField path="importPaths" type="array">
  Array of import paths for proto files
</ParamField>

<ParamField path="protoFiles" type="...string">
  Proto file paths to load
</ParamField>

```javascript theme={null}
import grpc from 'k6/net/grpc';

const client = new grpc.Client();
client.load(['./protos'], 'service.proto');
```

<Warning>
  The `load()` method must be called in the init context.
</Warning>

### loadProtoset(protosetPath)

Loads a compiled protoset file.

<ParamField path="protosetPath" type="string">
  Path to the protoset file
</ParamField>

```javascript theme={null}
client.loadProtoset('service.protoset');
```

### connect(address, \[params])

Connects to a gRPC server.

<ParamField path="address" type="string">
  Server address (host:port)
</ParamField>

<ParamField path="params" type="object" optional>
  Connection parameters
</ParamField>

<ResponseField name="result" type="boolean">
  Returns `true` on successful connection
</ResponseField>

```javascript theme={null}
import grpc from 'k6/net/grpc';

const client = new grpc.Client();
client.load([], 'service.proto');

export default () => {
  client.connect('localhost:50051', {
    plaintext: true,
  });
};
```

#### Connection Parameters

<ParamField path="plaintext" type="boolean" optional default={false}>
  Use plaintext connection (no TLS)
</ParamField>

<ParamField path="timeout" type="string" optional default="60s">
  Connection timeout
</ParamField>

<ParamField path="maxReceiveSize" type="number" optional>
  Maximum message size to receive (bytes)
</ParamField>

<ParamField path="maxSendSize" type="number" optional>
  Maximum message size to send (bytes)
</ParamField>

<ParamField path="tls" type="object" optional>
  TLS configuration
</ParamField>

<ParamField path="reflect" type="boolean" optional>
  Use server reflection protocol
</ParamField>

<ParamField path="authority" type="string" optional>
  Override the :authority pseudo-header
</ParamField>

### invoke(method, request, \[params])

Invokes a unary gRPC method.

<ParamField path="method" type="string">
  Fully qualified method name (e.g., "package.Service/Method")
</ParamField>

<ParamField path="request" type="object">
  Request message object
</ParamField>

<ParamField path="params" type="object" optional>
  Request parameters
</ParamField>

<ResponseField name="response" type="object">
  Response object containing status, message, headers, and trailers
</ResponseField>

```javascript theme={null}
const response = client.invoke('main.RouteGuide/GetFeature', {
  latitude: 409146138,
  longitude: -746188906,
});

console.log(JSON.stringify(response.message));
```

#### Response Object

<ResponseField name="status" type="number">
  gRPC status code
</ResponseField>

<ResponseField name="message" type="object">
  Response message
</ResponseField>

<ResponseField name="headers" type="object">
  Response headers metadata
</ResponseField>

<ResponseField name="trailers" type="object">
  Response trailers metadata
</ResponseField>

<ResponseField name="error" type="object">
  Error information if request failed
</ResponseField>

### asyncInvoke(method, request, \[params])

Invokes a unary gRPC method asynchronously.

<ParamField path="method" type="string">
  Fully qualified method name
</ParamField>

<ParamField path="request" type="object">
  Request message object
</ParamField>

<ParamField path="params" type="object" optional>
  Request parameters
</ParamField>

<ResponseField name="promise" type="Promise">
  Promise that resolves with the response
</ResponseField>

```javascript theme={null}
const promise = client.asyncInvoke('main.RouteGuide/GetFeature', {
  latitude: 409146138,
  longitude: -746188906,
});

promise.then(response => {
  console.log(JSON.stringify(response.message));
});
```

### close()

Closes the gRPC connection.

```javascript theme={null}
client.close();
```

## Constants

### Status Codes

* `grpc.StatusOK` - 0
* `grpc.StatusCanceled` - 1
* `grpc.StatusUnknown` - 2
* `grpc.StatusInvalidArgument` - 3
* `grpc.StatusDeadlineExceeded` - 4
* `grpc.StatusNotFound` - 5
* `grpc.StatusAlreadyExists` - 6
* `grpc.StatusPermissionDenied` - 7
* `grpc.StatusResourceExhausted` - 8
* `grpc.StatusFailedPrecondition` - 9
* `grpc.StatusAborted` - 10
* `grpc.StatusOutOfRange` - 11
* `grpc.StatusUnimplemented` - 12
* `grpc.StatusInternal` - 13
* `grpc.StatusUnavailable` - 14
* `grpc.StatusDataLoss` - 15
* `grpc.StatusUnauthenticated` - 16

## Examples

### Basic gRPC Test

```javascript theme={null}
import grpc from 'k6/net/grpc';
import { check } from 'k6';

const GRPC_ADDR = '127.0.0.1:10000';
const GRPC_PROTO_PATH = './proto/route_guide.proto';

let client = new grpc.Client();
client.load([], GRPC_PROTO_PATH);

export default () => {
  client.connect(GRPC_ADDR, { plaintext: true });

  const response = client.invoke('main.FeatureExplorer/GetFeature', {
    latitude: 410248224,
    longitude: -747127767,
  });

  check(response, {
    'status is OK': (r) => r && r.status === grpc.StatusOK,
  });

  console.log(JSON.stringify(response.message));

  client.close();
};
```

### With TLS

```javascript theme={null}
import grpc from 'k6/net/grpc';

const client = new grpc.Client();
client.load([], 'service.proto');

export default () => {
  client.connect('api.example.com:443', {
    tls: {
      cert: open('./client.crt'),
      key: open('./client.key'),
      cacerts: [open('./ca.crt')],
    },
  });

  const response = client.invoke('service.MyService/MyMethod', {
    field: 'value',
  });

  console.log(response.message);
  client.close();
};
```

### With Metadata

```javascript theme={null}
import grpc from 'k6/net/grpc';

const client = new grpc.Client();
client.load([], 'service.proto');

export default () => {
  client.connect('localhost:50051', { plaintext: true });

  const params = {
    metadata: {
      'authorization': 'Bearer token123',
      'x-custom-header': 'value',
    },
    timeout: '10s',
  };

  const response = client.invoke('service.MyService/MyMethod', 
    { field: 'value' },
    params
  );

  console.log(response.message);
  client.close();
};
```

### Server Reflection

```javascript theme={null}
import grpc from 'k6/net/grpc';

const client = new grpc.Client();

export default () => {
  // Use server reflection to discover services
  client.connect('localhost:50051', {
    plaintext: true,
    reflect: true,
  });

  const response = client.invoke('service.MyService/MyMethod', {
    field: 'value',
  });

  console.log(response.message);
  client.close();
};
```

<Warning>
  gRPC connections cannot be used in the init context. Connect to the server in the VU context (default function).
</Warning>
