12

In graphQLOptions, what is the difference between context and rootvalue?

When should I use one, and when should I use the other?

At the moment I'm attaching connectors and other sensitive data to the context, is this safe? Can the user read the context or the rootvalue of his queries?

Mascarpone
  • 2,516
  • 4
  • 25
  • 46
  • I found that answer, https://stackoverflow.com/a/53054134/37706, to a similar question, much clearer and very helpful to understand this question – PowerKiKi Jul 27 '19 at 22:15

2 Answers2

10

RootValue is an initial value passed in to the entry point of a query. Its undefined by default, but Apollo allows you to seed the query with some values if thats appropriate for your use case. It's accessible as the first parameter in the resolver function signature.

context is a shared reference available to all resolvers. Typically its an object of key/val pairs containing handles to stateful external connections or meta concerns like users/auth/etc.

Users (I'm assuming you mean clients) can only read what you return from resolvers; context is not represented in the introspection query. It's safe to put sensitive data and connectors (in the Apollo paradigm) there if your resolvers need access to fulfill their responsibilities.

danronmoon
  • 3,814
  • 5
  • 34
  • 56
Justin Mandzik
  • 245
  • 2
  • 5
  • 1
    Some extra info: `context` is set up once per graphql connection. `root` starts out as `{}` but can be mutated by resolvers, and subresolvers actually get the resolved object from the parent resolver. – w00t Jun 21 '17 at 09:56
8

GraphQL types/fields concept is quite recursive. The usually called RootQuery is as much a custom type as any other type in your schema. Usually, though, this RootQuery type contains only dynamically resolved fields, but this is no limitation. If you want people to access a string scalar name field on a User type you don't need to write a resolver function for it, as long as the object resolved to any User returning field contains that name property; this works just the same way with the RootValue, but that object will be the object provided via rootValue.

Context, in the other hand, is something that will be made available to every resolver, but will never be queriable by any user sending queries against the GraphQL server - thus making context the perfect place for keeping sensitive data, such as session information.

Sample: here goes a sample usage of rootValue: https://runkit.com/lucasconstantino/graphql-root-value-sample

  • Just an example of possible real-world usage: a library system could have the own library object as root... therefore one could ask (query) for the library's "name" or "address" info on that root directly, as much as he could ask for the libraries "books" – Lucas Constantino Silva Jun 21 '17 at 23:14
  • The `rootValue` is made available to every resolver as well, as part of the `resolveInfo` object. – Bergi Sep 19 '19 at 01:56