How to Simulate Browser Cookies in WeChat Mini Programs: A Complete Guide
This article explains why WeChat Mini Programs need a custom cookie solution, details the browser cookie model, and provides a step‑by‑step implementation using the Mini Program Storage and Network APIs, including code samples, performance tips, testing, and security considerations.
Introduction
Early web sessions relied on the cookie mechanism standardized by W3C, where browsers store a cookie token after login and automatically send it with subsequent requests. WeChat Mini Programs lack built‑in cookie support, so developers must simulate it using the Mini Program's Storage and Network capabilities.
Browser Cookie Mechanism
Local storage: browsers allocate space to store cookies.
Request carry: each HTTP request appends stored cookies to the Cookie header.
Response set: servers send Set-Cookie headers which browsers parse and store.
Expiration: each cookie has its own expiry time and is removed automatically.
Read/write API: JavaScript can create, read, update, and delete cookies.
Scope: path and domain attributes limit cookie applicability.
Encoding: cookie values are URL‑encoded (or Base64‑encoded) for transmission.
Other flags: HttpOnly, Secure, SameSite.
In DevTools you can view the current site’s cookies.
Mini Program Cookie Implementation
Design Overview
The solution consists of five parts, focusing on a “Cookie core library” and a “Request wrapper”.
Local Storage
Mini Programs provide a Storage API similar to the browser’s LocalStorage. We store a single key cookies that holds an object of cookie items.
wx.setStorageSync('cookies', cookies) // store
wx.getStorageSync('cookies') // retrieveThe cookie item structure is:
cookies = {
cookie1: {
name: 'cookie1',
value: 'xxx',
expires: 'Fri, 17 Jan 2020 08:49:41 GMT'
}
}Read/Write Operations
1. Get Cookie
function getCookie(name = '') {
let cookies = wx.getStorageSync('cookies')
let { value, expires } = cookies[name] || {}
return (name && expires && !isExpired(expires)) ? decodeURIComponent(value) : ''
}2. Set Cookie
function setCookie(cookiesParam) {
let oldCookies = wx.getStorageSync('cookies')
let newCookies = {}
for (let name in cookiesParam) {
if (isObject(cookiesParam[name])) {
let { value, expires, maxAge } = cookiesParam[name]
newCookies[name] = getStandardCookieItem({ name, value, expires, maxAge })
} else {
newCookies[name] = getStandardCookieItem({ name, value: cookiesParam[name] })
}
}
saveCookiesToStorage(Object.assign({}, oldCookies, newCookies))
}3. Remove Cookie
function removeCookie(cookieName) {
let cookies = wx.getStorageSync('cookies')
delete cookies[cookieName]
saveCookiesToStorage(Object.assign({}, cookies))
}Cookie Transmission in Network Requests
When sending a request, the wrapper builds the Cookie header from stored cookies:
function requestPro({ url, data, header, method = 'GET' }) {
return new Promise((resolve, reject) => {
wx.request({
url,
data,
header: Object.assign({}, { 'Cookie': CookieLib.getCookiesStr() }, header),
success(res) {
let setCookieStr = header['Set-Cookie'] || header['set-cookie'] || ''
CookieLib.setCookieFromHeader(setCookieStr)
resolve(res.data)
},
fail(err) { reject(err) }
})
})
}Encoding follows RFC6265 recommendations: values are URL‑encoded (or Base64) by the server, stored as‑is, and sent without additional decoding.
Performance Optimization (High‑Frequency Read/Write)
To avoid frequent synchronous storage access, maintain an in‑memory copy _COOKIES. Initialize it from Storage once, then read/write directly to memory and sync back to Storage only when necessary, optionally throttling writes.
Unit Testing
WeChat’s miniprogram-automator SDK enables automated tests. Example for setCookie():
it('API test: setCookie()', async () => {
await miniProgram.evaluate(() => {
wx.CookieLib.setCookie({ cookie1: 12345 })
})
let { cookies } = await miniProgram.callWxMethod('getStorageSync', 'cookies')
expect(cookies['cookie1'].value).toBe(12345)
})Cookie Security
In Mini Programs, HTTPS, domain whitelisting, and Storage isolation already provide baseline security. Attributes like path, domain, HttpOnly, Secure, and SameSite have limited impact but can be used as needed.
Additional measures:
Whitelist cookie names to limit size and prevent illegal writes.
Backend gateway whitelist to filter incoming cookies.
Expose only deep‑cloned cookie data to avoid accidental mutation.
Prefer server‑side session mechanisms for stronger security.
Device fingerprint reporting for risk detection.
Complete Demo
Full source code is available at https://developers.weixin.qq.com/s/x4sFASmh7xdq .
Conclusion
The article dissected the browser cookie model and demonstrated how to recreate it in a WeChat Mini Program using Storage and Network APIs, providing a reusable cookie library, performance tips, testing guidance, and security considerations.
WecTeam
WecTeam (维C团) is the front‑end technology team of JD.com’s Jingxi business unit, focusing on front‑end engineering, web performance optimization, mini‑program and app development, serverless, multi‑platform reuse, and visual building.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
