Cookies
This page contains hard-won advice on the use of cookies in MediaWiki code deployed to Wikimedia wikis.
First of all: if you can, do not use cookies. They bloat request sizes, can lead to concurrency issues when the user has multiple tabs open, and increase our privacy footprint.
Alternatives include:
- If you only care about logged-in users and need cross-device consistency, use MediaWiki user preferences (not though that they are included in every response so, like cookies, they bloat the HTTP payload size even when your feature is not being used).
- If you only need the data on the client side, use Local Storage with expiry set by using the
mw.storageAPI.- You can also use Session Storage via
mw.storage.session, but beware that web browsers scope Session Storage to the life of a specific browser tab. This means when a tab is closed the data is effectively lost. This is usually not what you want, but sometimes useful. On the other hand, it also means each tab can have its own unique, and each one does survive restoration from back-forward history cache, "Re-open closed tab", and browser/device restarts if open tabs are restored.
- You can also use Session Storage via
But if you must...
Only use cookies if you need to make the stored data available to PHP code too. Avoid cookies which have session or token in their name (case-insensitively) unless you understand how those interact with custom logic in the caching infrastructure.
Before deploying code that adds a new cookie, email the Privacy team at privacy@ so that they can verify that the new cookie complies with the cookie statement. Include the name of the cookie, its purpose, and its expiry time.
Use WebResponse::setCookie() / WebRequest::getCookie() in PHP, mw.cookie.set() / .get() in JS.
When setting a cookie on the server side, consider whether the response can get cached (together with the Set-Cookie header). MediaWiki tries to automatically make responses with Set-Cookie uncacheable, but the process is not always reliable and you should make sure to also do that in the code which sets the cookie (usually via OutputPage::disableClientCache()).
If the output for some page is cacheable and depends on the cookie value or presence, you need to add a Vary: Cookie header so caches are split (on Wikimedia wikis the header will probably be present anyway because authentication-related code almost always adds it, but in general you cannot rely on that!). If you set the Vary header on an URL sometimes, you must set it on that URL always (i.e. not just when the cookie is present).
Be aware of the SameSite flag if you need to read cookies in cross-site requests.
See also
- Incidents/20150527-Cookie
- Caching overview
- MediaWiki at WMF
- The
cache-cookieslog channel, which reports responses where someone has set a cookie but has not disabled caching.