Skip to content
Documentation
Metadata

MetaData

Metadata functionality is essential in gRPC. In some scenarios, we need capabilities similar to HTTP headers, such as tracing, source of the request, and more. Metadata serves these purposes.

Client-Side Sending

To send metadata from the client, use loader.makeMetadata(). Here is an example:

const client = clients.get('test.helloworld.Greeter')
 
const meta = loader.makeMetadata({
    'x-cache-control': 'max-age=100',
    'x-business-id': ['grpcity', 'testing'],
    'x-timestamp-client': 'begin=' + new Date().toISOString()
})
const { status, metadata, response } = await client.sayGreet({ name: 'greeter' }, meta)
 
console.log(metadata)

Printing the metadata yields the following result:

Terminal
Metadata {
    internalRepr: Map(8) {
        'content-type' => [ 'application/grpc+proto' ],
        'x-cache-control' => [ 'max-age=100' ],
        'x-business-id' => [ 'grpcity, testing' ],
        'x-timestamp-client' => [ 'begin=2023-11-01T03:31:05.942Z' ],
        'x-client-hostname' => [ 'ChakhsudeAir' ],
        'user-agent' => [ 'grpc-node-js/1.9.7' ],
        'x-timestamp-server' => [ 'received=2023-11-01T03:31:06.987Z' ],
        'date' => [ 'Wed, 01 Nov 2023 03:31:06 GMT' ]
    },
    options: {}
}

The client defaults to sending the following metadata:

  • x-client-hostname: The value is the operating system’s hostname.

The server defaults to sending the following metadata:

  • content-type: The value is generally application/grpc+proto.
  • user-agent: The value is generally grpc-node-js/1.9.7.
  • date: The value is generally Wed, 01 Nov 2023 03:31:06 GMT.

Server-Side Receiving

To receive metadata on the server side, check for it in call.metadata. Before using it, clone it using clone(), and then retrieve values based on the key.

async sayGreet(call) {
    const { name } = call.request
 
    // Retrieve metadata information from the call
    const metadata = call.metadata.clone()
 
    // Get specific metadata key-value pairs
    const cacheAge = metadata.get('x-cache-control')
    const businessId = metadata.get('x-business-id')
    const clientTimestamp = metadata.get('x-timestamp-client')
 
    // Print metadata values
    console.log(cacheAge)
    console.log(businessId)
    console.log(clientTimestamp)
 
    return {
        message: `hello ${name || "world"} by Greeter in server1`
    }
}

The output is as follows:

Terminal
[ 'max-age=100' ]
[ 'grpcity, testing' ]
[ 'begin=2023-10-31T16:34:22.296Z' ]

Server-Side Sending

In some cases, the server needs to send metadata information back to the client. The method is as follows:

async SayHello (call) {
    const metadata = call.metadata.clone()
    metadata.add('x-timestamp-server', 'received=' + new Date().toISOString())
    call.sendMetadata(metadata)
 
    // Omitted...
}

The server sending metadata can be received by the client.