How to set Cache-Control in emberjs


#1

Hi all. I’m looking for how to set Cache-Control in emberjs. Can you give me any suggestion?

Thank a lot.


#2

The Cache-Control header can be set on both requests and responses. I assume you’re asking about putting it on requests, because typically Ember is only running on the client* and you have some other server sending responses.

To set headers on requests, it depends how you are fetching data. Ember itself doesn’t dictate that, although the typical default choice is to use ember-data (people often miss that ember-data is a totally separate library that you can choose to include or not, and Ember works just as well with raw fetch or jQuery.ajax or graphQL/apollo, etc).

Assuming you are using ember-data, you can extend your Adapter so that it sets headers:

export default DS.JSONAPIAdapter.extend({
  ajaxOptions() {
    let hash = this._super(...arguments);
    hash.beforeSend = (xhr) => {
      xhr.setRequestHeader('Cache-Control',  'no-cache');
    };
    return hash;
  }
});

  • Unless you have a fastboot server, in which case I guess it does make sense to ask how to set headers on responses, and that is documented here.

#3

Thank you very much @ef4. I have a fastboot server this case. I will try to follow your suggestions, hope I can do this.