Interceptors in gRPC are a mechanism to intercept incoming and outgoing calls, providing an opportunity for preprocessing and post-processing. They can be used for various purposes such as logging, monitoring, message transformation, authentication, and more.
In the client-side, interceptors are invoked before the call is dispatched by the stub, allowing manipulation of parameters or headers. On the server side, they’re invoked before the method implementation is executed, enabling similar manipulations.
For example, consider an authentication scenario where you need to validate tokens in each request. Instead of implementing this logic in every service method, you could use an interceptor to check the token validity before the actual method execution.
To implement an interceptor, one must create a class that implements either
ClientInterceptor
or
ServerInterceptor
, depending on the use case. The key methods to override are
interceptCall
for server-side and
interceptUnaryCall
,
interceptClientStreamingCall
, etc., for client-side.