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


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:


context.WithoutCancel

This is it! The last of the context package functions that we will cover in this series. Well, almost. I actually have a couple reader feedback and question emails to respond to, which I’ll do next, before startinga a new series. Speak of a new series: I’m still looking for suggestions! I have a couple ideas, but I’d rather do something you’re itching to learn about, than whatever random idea I come up with.


context.WithValue

func WithValue func WithValue(parent Context, key, val any) Context WithValue returns a derived context that points to the parent Context. In the derived context, the value associated with key is val. Use context Values only for request-scoped data that transits processes and APIs, not for passing optional parameters to functions. The provided key must be comparable and should not be of type string or any other built-in type to avoid collisions between packages using context.

Get daily content like this in your inbox!

Subscribe