unofficial-weightwatchers-mcp is also a Node.js library: the same client that the CLI and the MCP
server use, with typed methods, pluggable session storage and no side effects on import. Use it in
scripts, Express and Next.js backends, serverless functions or n8n code nodes.
Install
npm install unofficial-weightwatchers-mcpNode.js 20 or newer. ESM only (import). TypeScript types are included, no @types package needed.
Quick start
import { WeightWatchers, MemoryStorage, today } from 'unofficial-weightwatchers-mcp';
const ww = await WeightWatchers.login({
email: 'you@example.com',
password: process.env.WW_PASSWORD,
region: 'de',
storage: new MemoryStorage(), // nothing is written to disk
});
const day = await ww.daySummary(today());
console.log(day.pointsDetails.dailyPointsRemaining);examples/basic.mjs runs the same offline against a mock: node examples/basic.mjs --mock.
Sign-in and sessions
WW signs in in two steps (see architecture). The library keeps the session, not the password:
| Piece | Lifetime | Stored |
|---|---|---|
tokenId (WW session) | a few hours | yes, in the storage |
jwt (access token) | minutes | yes, renewed from the tokenId |
| password | never (unless you opt in, see below) |
When the JWT has expired, the next call renews it from the tokenId by itself. When the session has
expired, the call fails with a WWAuthError (code login_required); then sign in again.
Patterns
1. Sign in once, keep the session, resume later (web services, one user per session):
// at login time
const ww = await WeightWatchers.login({ email, password, storage: userStorage });
// the password is out of scope now; the session is in userStorage
// on later requests, in any process
const ww = new WeightWatchers({ storage: userStorage }); // reads the session on the first call2. Resume from a tokenId you saved yourself:
const saved = await ww.session(); // { region, email, tokenId, memberId, ... } (no JWT)
const again = await WeightWatchers.resume({ ...saved, storage: new MemoryStorage() });resume fetches a JWT right away, so an expired session fails there with a WWAuthError.
3. Unattended renewal on a server you control: set WW_EMAIL and WW_PASSWORD in the environment
(or pass env). When the session dies, the client signs in again by itself. Only do this for your
own account on your own server. Never ask users for a password you will keep.
4. Node CLI defaults: new WeightWatchers() with no options uses the file storage
($WW_HOME/auth.json) and the system credential store, exactly like the ww command. A script on
your own machine can reuse the session from ww login.
Session storage
A storage is an object with two methods (a third is optional):
interface SessionStorage {
load(): Session | null | Promise<Session | null>;
save(session: Session | null): void | Promise<void>;
clear?(): void | Promise<void>; // without it, logout() calls save(null)
}loadruns when the session is needed;saveafter each sign-in and each token renewal.- A
Sessionis plain JSON:{ region, email, tokenId, jwt, memberId, jwtExpiresAt, savedAt }. - Asynchronous storages are read once per client instance; create a client per request (cheap) or per user. Synchronous ones (memory, file) are re-read before every call.
- Race conditions: two requests of the same user may both renew the token. The last
savewins and both sessions stay valid. Use your database's usual atomic update if it matters.
Shipped storages:
| Storage | Where | Import |
|---|---|---|
MemoryStorage | process memory; one instance per user | main entry and /web |
FileStorage | JSON file, mode 600, atomic write; default of the Node entry | main entry (Node only) |
Your own, for example on top of a database (see examples/session-store.mjs for an encrypting one):
const storage = {
load: async () => (await db.get('ww_session', userId)) ?? null,
save: async (session) => (session ? db.put('ww_session', userId, session) : db.delete('ww_session', userId)),
};Reacting to renewals
onSessionChange is called with the stored session after every sign-in and renewal, for audit logs
or to write the session somewhere that is not a storage (a cookie, a queue):
const ww = new WeightWatchers({ storage, onSessionChange: (session) => metrics.increment('ww.renewed') });Do not log the session: it contains tokens.
Security of sessions
A stored session is access to the member's health data. Treat it like a password:
- Encrypt it at rest (application-level encryption or a managed secret store); never put it in
localStorage, URLs, logs, analytics or error reports. - Keep one session per user. Never share a client between users.
- Never store the password. This library does not. If you must support unattended re-login, keep the password in a secrets manager, not in your database.
- Delete the session on logout:
await ww.auth.logout()clears the storage. - Health data about a person is special category data under GDPR Art. 9. A service that holds other people's WW sessions needs a legal basis, consent and a deletion path. This project does not offer a hosted service for that reason (see the roadmap).
Options
new WeightWatchers({
region?: 'de' | 'com' | 'co.uk' | 'fr' | 'nl' | 'be' | 'ch' | 'com.au' | 'ca', // default: WW_REGION, stored session, 'de'
storage?: SessionStorage, // default: FileStorage (Node entry) / MemoryStorage (/web)
fetchImpl?: typeof fetch, // default: global fetch, looked up at call time
onSessionChange?: (session) => void | Promise<void>,
keychain?: Keychain, // Node default: system credential store; /web: none
env?: Record<string, string>, // WW_REGION, WW_EMAIL, WW_PASSWORD are read from here (default process.env)
timeoutMs?: number, // per request, default 30000, 0 = none
warn?: (message) => void,
})- Region: only the listed WW markets are accepted, so credentials can never go to a look-alike domain. Only
deis tested. - fetch: inject your own for tests, proxies or tracing. Redirects are never followed with credentials.
- The host allowlist stays on: the client only talks to
cmx.weightwatchers.<region>,auth.weightwatchers.<region>andapi.ww.com.
Methods
All methods return promises. Dates are YYYY-MM-DD strings and are validated before any request
(today() gives the local date). IDs come from earlier results. The full types are in
types/web.d.ts.
Client and session
| Method | Description |
|---|---|
WeightWatchers.login({ email, password, region?, storage?, ... }) | Sign in and return a client. The password is used once. |
WeightWatchers.resume({ tokenId, region?, email?, storage?, ... }) | Continue a saved session; fails with WWAuthError if it has expired. |
ww.session() | The session without the JWT, to keep in your storage. |
ww.memberId() | Member ID. |
ww.auth.status() | Sign-in state (no tokens). |
ww.auth.logout({ keychain? }) | Clear the storage (and the stored password with keychain: true). |
ww.call(path, { method?, body?, query? }) | Raw call to any endpoint, for what has no method yet. ~ is the member. |
Day and diary
| Method | Description |
|---|---|
daySummary(date) | Points used, target, remaining, weekly allowance, nutrition, weight. |
day(date) | The full day including tracked foods. |
tracked(date) | Tracked entries grouped by morning, midday, evening, anytime, with totalPoints. |
track(date, items) | Add entries: food references (_id, versionId, sourceType, portionId, portionSize, timeOfDay) or quick adds ({ name, points, timeOfDay, isQuickAdd: true }). |
untrack(date, entries) | Remove entries by entryId. |
updateTracked(date, entries) | Change amount or slot of entries. |
copyTracked({ fromDate, toDate, slot?, toSlot?, entryIds? }) | Copy entries to another day (read + track, not atomic). |
trackedEntry(date, entryId) | One entry with all details. |
frequentAndRecent() | Frequently and recently tracked foods (carry all IDs needed for track). |
Search, foods and points
| Method | Description |
|---|---|
search(query, { limit?, facetFilters? }) | Foods, vendor foods and WW recipes. |
searchRecipes(query, { limit? }) | WW recipes only. |
foodDetail({ sourceType, id }) | Details and nutrition of a food or recipe. |
calculatePoints({ nutrition, name?, program? }) | Points from nutrition per portion. Changes nothing. |
Own recipes, foods and meals
| Method | Description |
|---|---|
memberRecipes(paging), memberRecipe(id), createMemberRecipe(body), updateMemberRecipe(id, body), deleteMemberRecipe(id), calculateRecipePoints(body) | Own recipes. Bodies follow the WW API (docs/api.md); the MCP tools take friendlier input. |
memberFoods(paging), memberFood(id), createMemberFood(body), updateMemberFood(id, body), deleteMemberFood(id) | Own foods. |
memberMeals(paging), memberMeal(id), createMemberMeal(body), updateMemberMeal(id, body), deleteMemberMeal(id) | Saved meals. |
paging is { limit?, offset?, program? }. Updates replace the whole object (PUT).
Favorites, water, activity, weight
| Method | Description |
|---|---|
favoriteFoods(paging), addFavoriteFood(...), removeFavoriteFood(...) | Favorite foods. |
water(date), setWater(date, { amount, servingSize?, unit? }), deleteWater(date) | Water. setWater replaces the day's value. |
searchActivities(query), activity(id), calculateActivityPoints(...), exercisesWeekly(startDate), logExercise(...), updateExercise(id, ...), deleteExercise(id) | Activity. Future dates are refused. |
weightEntries(), weightStatus(), weightSettings() | Weight, read only. |
profileOptions(), healthProviders() | Account. |
Errors
All errors extend WWError and have a stable code. Messages never contain tokens or passwords.
| Class | When | code |
|---|---|---|
WWAuthError | Sign-in refused or no usable session | auth_failed, login_required |
WWApiError | WW answered non-2xx: has status, body, url | unauthorized, forbidden, not_found, rate_limited, upstream_error, http_error |
WWError | Network failure, timeout, blocked by CORS | network_error, timeout, cors_blocked |
import { WWApiError, WWAuthError } from 'unofficial-weightwatchers-mcp';
try {
await ww.daySummary('2026-01-15');
} catch (err) {
if (err instanceof WWAuthError) redirectToWwLogin(); // session gone
else if (err instanceof WWApiError && err.status === 429) retryLater();
else throw err;
}A 401 from the API is retried once with a fresh token; everything else is not retried. Invalid
arguments (bad dates, unknown source types) throw a plain Error before any request. The older
names AuthError and WwError still work.
Browser and bundlers
- Browser pages cannot use this API.
cmx.weightwatchers.*andauth.weightwatchers.*do not allow cross-origin requests, the sign-in needs aCookieheader and a manual redirect (both forbidden in browsers). Calls fail with aWWError(cors_blocked) that says so. - What works: your server talks to WW; your page talks to your server. Examples:
examples/express-backend.mjs,examples/nextjs-route.ts, or runww serveand call its REST routes from your backend. - Bundlers do not break. The
exportsmap sends the conditionsbrowser,worker,workerdandedge-lighttosrc/lib.web.js, which imports nonode:*module (nofs, no keychain). It is also available explicitly asunofficial-weightwatchers-mcp/web. A test checks the import graph and runs the entry withnode:fsblocked. - Edge runtimes (Cloudflare Workers, Vercel Edge, Deno):
unofficial-weightwatchers-mcp/webwith your ownstorage(KV, a database). They have no CORS limit, since the code runs on a server. FileStorageand the keychain exist only in the Node entry.
Framework notes
- Next.js: use a route handler on the Node runtime, never in a client component. See
examples/nextjs-route.ts. - Express and similar: one storage per user, one client per request. See
examples/express-backend.mjsandexamples/session-store.mjs. - Serverless: nothing lives between invocations, so the session must be in a storage you control (KV, database). Construct the client inside the handler.
- n8n: in a Code node, enable external modules (
NODE_FUNCTION_ALLOW_EXTERNAL=unofficial-weightwatchers-mcp), then use the library as above with aMemoryStorageseeded from a credential, or runww servenext to n8n and use the HTTP Request node (HTTP API). The HTTP route is the simpler one and keeps the session out of the workflow. - Scripts and cron:
ww login --save-passwordonce, thennew WeightWatchers()uses the stored session and renews it.
Stability
The methods and types listed here are the supported interface. They follow semver once the project
reaches 1.0; until then a minor version may change them (see the changelog). The
shape of WW's responses is not under this project's control: types list the fields seen so far and
stay open for the rest. ww.call() is the escape hatch for endpoints without a method.