Plugins

Plugins enable you to extend Apollo Server’s core functionality by performing custom operations in response to certain events. Currently, these events correspond to individual phases of the GraphQL request lifecycle, and to the startup of Apollo Server itself (read more here). For example, a basic logging plugin might log the GraphQL query string associated with each request that’s sent to Apollo Server.

Custom plugins

To create a plugin, declare a class annotated with the @Plugin decorator exported from the @nestjs/graphql package. Also, for better code autocompletion, implement the ApolloServerPlugin interface from the apollo-server-plugin-base package.

  1. import { Plugin } from '@nestjs/graphql';
  2. import {
  3. ApolloServerPlugin,
  4. GraphQLRequestListener,
  5. } from 'apollo-server-plugin-base';
  6. @Plugin()
  7. export class LoggingPlugin implements ApolloServerPlugin {
  8. requestDidStart(): GraphQLRequestListener {
  9. console.log('Request started');
  10. return {
  11. willSendResponse() {
  12. console.log('Will send response');
  13. },
  14. };
  15. }
  16. }

With this in place, we can register the LoggingPlugin as a provider.

  1. @Module({
  2. providers: [LoggingPlugin],
  3. })
  4. export class CommonModule {}

Nest will automatically instantiate a plugin and apply it to the Apollo Server.

Using external plugins

There are several plugins provided out-of-the-box. To use an existing plugin, simply import it and add it to the plugins array:

  1. GraphQLModule.forRoot({
  2. // ...
  3. plugins: [ApolloServerOperationRegistry({ /* options */})]
  4. }),

info Hint The ApolloServerOperationRegistry plugin is exported from the apollo-server-plugin-operation-registry package.