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
Published 3 years ago
Updated 3 years ago

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.

egghead
egghead
~ a minute ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today