Create a New Cache on Every GraphQL Request Using Apollo Context

Jacob Paris
InstructorJacob Paris
Share this video with your friends

Social Share Links

Send Tweet

If a cache persists between requests, a logged-in user could cache some sensitive data that guest users could access by mistake

An easy way to prevent this is to make new DataLoaders on every request using Apollo's context method, which also makes it easy to inject the DataLoader into any resolver

Instructor: [0:00] Right now, we're creating userLoader when the server starts, and we don't have any code to purge the cache between requests, so a second query for the same item is still served from the cache. Network caches like this are a good idea, but this isn't the place for them. Server RAM is expensive, and this implementation can cause major security risks.

[0:20] We can eliminate all of that by using a cache that only exists for the duration of a single network request. We're going to do that by making new DataLoaders on every request using Apollo's context method. Copy the userLoader directly from its declaration into the Apollo context. It'll be available as the third argument to every single resolver.

[0:44] Now, we can see the caching and batching working flawlessly on a per-request level.