API Reference: Cache control plugin
Using the plugin
This article documents the options for the ApolloServerPluginCacheControl
plugin, which you can import from @apollo/server/plugin/cacheControl
.
This plugin enables your GraphQL server to specify a cache policy at the field level, either statically in your schema with the @cacheControl
directive, or dynamically in your resolvers via the info.cacheControl
API. It also sets the cache-control
HTTP response header by default. See Server-side caching for more information and examples.
To use the @cacheControl
directive, you must first define it in your schema.
Apollo Server installs this plugin by default in all servers, with its default configuration. You typically do not have to install this plugin yourself; you only need to do so if you want to provide non-default configuration.
If you want to configure the ApolloServerPluginCacheControl
plugin, import it and pass it to your ApolloServer
constructor's plugins
array:
import { ApolloServer } from '@apollo/server';import { ApolloServerPluginCacheControl } from '@apollo/server/plugin/cacheControl';const server = new ApolloServer({typeDefs,resolvers,plugins: [ApolloServerPluginCacheControl({// Cache everything for 1 second by default.defaultMaxAge: 1,// Don't send the `cache-control` response header.calculateHttpHeaders: false,}),],});
import { ApolloServer } from '@apollo/server';import { ApolloServerPluginCacheControl } from '@apollo/server/plugin/cacheControl';const server = new ApolloServer({typeDefs,resolvers,plugins: [ApolloServerPluginCacheControl({// Cache everything for 1 second by default.defaultMaxAge: 1,// Don't send the `cache-control` response header.calculateHttpHeaders: false,}),],});
If you don't want to use cache control at all, you can explicitly disable it with the ApolloServerPluginCacheControlDisabled
plugin:
import { ApolloServer } from '@apollo/server';import { ApolloServerPluginCacheControlDisabled } from '@apollo/server/plugin/disabled';const server = new ApolloServer({typeDefs,resolvers,plugins: [ApolloServerPluginCacheControlDisabled()],});
import { ApolloServer } from '@apollo/server';import { ApolloServerPluginCacheControlDisabled } from '@apollo/server/plugin/disabled';const server = new ApolloServer({typeDefs,resolvers,plugins: [ApolloServerPluginCacheControlDisabled()],});
The plugin doesn't affect your app much if you don't use the @cacheControl
directive or the info.cacheControl
API. If you don't currently use it, there might be a very slight performance improvement from disabling the plugin.
Options
Name / Type | Description |
---|---|
| By default, root fields and fields that return a composite type (object, interface, or union) are considered to be uncacheable ( This option was popular in Apollo Server 2 as a workaround for the problem solved by the |
| By default, the cache control plugin sets the |