gRPC Interceptors and Metadata
Auth, logging middleware and gRPC metadata
gRPC Interceptors and Metadata is a free Go Academy lesson on CoddyKit. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, and your progress syncs across the web and the CoddyKit app. The Go Academy course includes 4 lessons in total.
What are interceptors?
gRPC interceptors (middleware) run before or after RPC handlers. They add cross-cutting concerns: logging, auth token validation, metrics, panic recovery, and tracing.
Unary server interceptor
A unary server interceptor wraps the handler with additional logic:
func LoggingInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
log.Printf("RPC: %s", info.FullMethod)
resp, err := handler(ctx, req)
log.Printf("done: %v", err)
return resp, err
}
grpcSrv := grpc.NewServer(grpc.UnaryInterceptor(LoggingInterceptor))Stream server interceptor
Similar to unary but wraps the stream handler:
func StreamLogging(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
log.Printf("stream: %s", info.FullMethod)
return handler(srv, ss)
}Chaining interceptors
Use grpc.ChainUnaryInterceptor (Go gRPC v1.38+) to apply multiple interceptors in order:
grpcSrv := grpc.NewServer(
grpc.ChainUnaryInterceptor(LoggingInterceptor, AuthInterceptor, MetricsInterceptor),
)Client interceptors
Client-side unary interceptors wrap outgoing calls — useful for injecting auth tokens, retries, or tracing headers:
conn, _ := grpc.NewClient(addr,
grpc.WithUnaryInterceptor(ClientAuthInterceptor),
grpc.WithTransportCredentials(insecure.NewCredentials()),
)gRPC metadata
Metadata is key-value pairs sent alongside an RPC, analogous to HTTP headers. Use metadata.New and metadata.NewOutgoingContext on the client.
md := metadata.New(map[string]string{"authorization": "Bearer " + token})
ctx := metadata.NewOutgoingContext(context.Background(), md)Reading metadata on server
Extract incoming metadata with metadata.FromIncomingContext:
md, ok := metadata.FromIncomingContext(ctx)
if !ok { return nil, status.Error(codes.Unauthenticated, "no metadata") }
token := md["authorization"]Sending metadata from server
Send response headers and trailers from the server with grpc.SetHeader and grpc.SetTrailer:
grpc.SetHeader(ctx, metadata.Pairs("x-request-id", requestID))go-grpc-middleware
The github.com/grpc-ecosystem/go-grpc-middleware/v2 library provides ready-made interceptors: recovery, logging (zap/logrus), auth, and more.
Auth interceptor pattern
Extract and validate a token in an interceptor; attach the user to the context for downstream handlers:
func AuthInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
md, _ := metadata.FromIncomingContext(ctx)
if !validateToken(md["authorization"]) {
return nil, status.Error(codes.Unauthenticated, "invalid token")
}
return handler(ctx, req)
}Panic recovery interceptor
Wrap handlers to recover from panics and return an Internal error instead of crashing:
defer func() {
if r := recover(); r != nil {
err = status.Errorf(codes.Internal, "panic: %v", r)
}
}()Quick Check
How do you pass authentication tokens between a gRPC client and server?
Recap: gRPC Interceptors and Metadata
Key points:
- Unary interceptor: func(ctx, req, info, handler) (resp, error)
- grpc.ChainUnaryInterceptor for multiple interceptors
- Metadata is key-value pairs; analogous to HTTP headers
- Auth interceptor: extract metadata → validate → add user to context
Learn Go with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 51
- Lessons
- 203
Frequently Asked Questions
Is the “gRPC Interceptors and Metadata” lesson free?
Yes — any 3 lessons of the Go Academy learning path, including “gRPC Interceptors and Metadata”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Go Academy course includes 4 lessons in total.
What will I learn in “gRPC Interceptors and Metadata”?
Auth, logging middleware and gRPC metadata You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Go Academy?
No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.
How long does the “gRPC Interceptors and Metadata” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Go Academy lesson?
Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Protocol Buffers and .proto Files
- Implementing a Unary gRPC Service
- Server and Client Streaming
- gRPC Interceptors and Metadata