When not to use context values

April 17, 2025

Storing values in a context is quite flexible, but comes without strict type safety, and obscures the API. So what can we do about this?

First, for type safety, we’re limited to runtime assertions:

userID := ctx.Value(userIDKey).(string)

But this can panic if we ever get an unexpected value (or even nil). So to make it safer, we can use the two-variable assignment form, which yields a bool indicating success:

userID, ok := ctx.Value(userIDKey).(string)
if !ok {
	return errors.New("userID not found in context")
}

But for the obscure API problem, what can we do?

This may be anti-climactic, but the best solution I’ve found is to simply avoid using context values. Of course that’s not always practical, so it means we have to choose between trade-offs.

But this brings me finally to answer the question: Should request-scoped “access objects” be included in a context?

My answer: No.

Don’t pass a logger, database handle, or other such object, even when specifically configured per request, via context, unless there’s really no other way. Instead, my advice, is to pass them to an object constructor, then pass your context to a method.

Let me illustrate.

Don’t do this:

func Foo(ctx context.Context, /* ... */) {
	logger := ctx.Value(loggerKey).(*slog.Logger)
	logger.Info(/* ... */)
	/* ... */
}

Instead do this:

type Controller struct {
	logger *slog.Logger
}

func New(logger *slog.Logger) Controller {
	return Controller{logger: logger}
}

func (c *Controller) Foo(ctx context.Context, /* ... */) {
  c.logger.Info(/* ... */)
}

It’s a bit more verbose in this simple case, but it makes the API explicit, and it provides compile-time type safety. There’s no risk of receiving a nil logger.

This particular approach doesn’t actually solve the issue of propagating a request-scoped logger, however. Addressing that issue is more involved than I can fully address today. It’s also well beyond the scope of the context package, which is itself a clue to the answer: It’s rare to actually need request-scoped loggers (or databases, or other objects). There’s probably a better way. (If you need help finding that better way, feel free to send me an email, and I can talk about it in an upcoming email.)


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Related Content


slog Handler methods

slog.Handler is an interface type. We’re going to look at each method on that interface in turn. Understanding these methods is valuable if you’re ever implementing your own handler. If you’re only using slog to produce logs using existing handlers, you could skip this part… though maybe you’ll learn something interesting anyway! type Handler type Handler interface { // Enabled reports whether the handler handles records at the given level. // The handler ignores records whose level is lower.


Contexts

[**Idiomatic Testing in Go**](/idiomatic-testing/) starts TOMORROW! My my, how time flies! There are still a few seats available, and there’s still time to sign up. Learn how to get the most out of the tests in your Go app! One feature I often see overlooked capability of the log/slog package, is to extract log key/value pairs from context: Contexts Some handlers may wish to include information from the context.Context that is available at the call site.


Anatomy of a log/slog logger

Unlike the older log package, which provides a single *log.Logger type as its primary interface, log/slog has a two-tiered architecture. This is roughly the same architecture used by the database/sql package: One interface implements a handler (or “driver” for database/sql), and another interface is consumed. The package itself provides the intermediate translation. This is essentially a localized example of ports-and-adaptors or hexagonal architecture. Here’s how the GoDoc for the package explains it:

Get daily content like this in your inbox!

Subscribe