Should I add Cache-Control: no-cache to GET endpoints of my REST API?
Asked Answered
H

1

8

When creating REST API working with POST/PUT is simple. They are non-idempotent and thus are NOT cached by browsers by default.

However when creating a GET endpoint, things get tricker. I have this fear that browsers(or a particular one) by default will try to cache GET requests whenever they can and I will end up with stale data.

Is this fear of aggressive caching real?

Let's take example of an endpoint GET /articles/123/comments.

Despite this endpoint being a GET endpoint, each request can return different content, as comments for the article get submitted.

  • Will this this be cached?
  • Will it be cached by particular aggressive browser?

Let's assume there are no headers related to cache served with the response.

content-length: 2518
content-type: application/json
date: Thu, 17 Oct 2019 07:51:59 GMT
status: 200

What is the best practice for avoiding stale data for GET requests?

There seem to be different strategies to solve this problem, but what would be the best way?

  • cache-busting my GET calls via unique query string?

    eg. GET /articles/123/comments?nonce=12312310980923409

  • adding Cache-Control: no-cache (will this always be respected?)

  • adding ETag: xyz_HASH_OF_MY_LIST_OF_COMMENTS?

  • adding Cache-Control: max-age=0 (to disable caching)

  • adding Cache-Control: max-age=60 (to reduce max duration of caching)

  • just don't worry and assume that without headers like ETag, Last-Modified the GET request won't be cached by any of the browsers?

Hereditament answered 17/10, 2019 at 9:3 Comment(0)
P
3

To a browser GET requests look the same, no matter if they originated by JavaScript to your REST API or by you entering an URL in the address bar.

What happens if you don't set the caching headers?

The spec allows the browser to do whatever it wants.

By default, browsers cache responses to GET requests and use a "best guess" approach for the duration.

You should always set the caching explicitly to get consistent behavior.

For more details, see

How to avoid stale content?

There is no simple answer to this. It depends how often your resource changes. If it never changes, you can cache it for a long time, for example a blog post. If it changes sometimes, you can cache it for a shorter time, for example a news API. If it changes "always", you shouldn't cache it, for example a social media news feed, stock price API, etc.

Pharmaceutical answered 1/2, 2021 at 18:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.