In GraphQL, a context is an object shared by all the resolvers of a specific execution. It's useful for keeping data such as authentication info, the current user, database connection, data sources and other things you need for running your business logic.
The context is available as the 3rd argument to each resolver:
You can read more about resolver in Apollo Server documentation.
Since modules are isolated (see why), there is no common context unless you explicitly create one. In the case of authentication for example, you need to create an authentication module that places the authenticated user into the context, then explicitly import that authentication module from each module that uses authentication.
GraphQL Modules also uses the context; it adds to the context a field called
injector, which you can use to get access to the dependency injection container of your
You can use the
injector from any resolver like that:
In addition to the added
injector, GraphQL Modules lets you add custom fields to the
Each module can have its own
context function, which takes the network session that contains the request, the current context and the injector and can extend the GraphQL
context with any field.
To add a custom
context to your
GraphQLModule, do the following:
Your custom context-building function should return either
Then, in any of your resolvers, you can access it this way:
You can also use this feature to implement authentication easily; you just access the network session, write async code, and return the current user, which is added to the
context. For example:
See also the article Authentication and Authorization in GraphQL (and how GraphQL-Modules can help).