Design Systems and Tokens: One Source of Truth, Generated and Verified
Store design decisions as tokens in one JSON file, resolve aliases, generate CSS custom properties, and check automatically that every text colour passes contrast and every spacing value is on the scale, with an independent parse of the output.
In this lesson you will
- Define design tokens
- Resolve aliases and detect cycles
- Generate CSS from tokens
- Validate tokens automatically
About 28 minutes
Change the colour once
The studio’s site now has dozens of pages, and the owner wants the main colour a little darker. If the colour was typed in a hundred places, that is a hundred edits and a few missed ones. A design system fixes this by storing decisions as design tokens: named values, such as color.text, space.3 or font.size.2, kept in one file. Components refer to the names, never to raw values, so a change is made once. Tokens come in layers. Base tokens hold raw values, such as the palette from lesson 4. Semantic tokens give them roles, such as color.text or color.action, and may refer to a base token by an alias like {color.deep}. Components use only the semantic ones, so a theme, such as a dark mode, only needs a different mapping.
Because tokens are data, programs can process them. A small build step resolves the aliases, so that {color.deep} becomes its hex value, and detects cycles, where A refers to B and B refers to A. It writes CSS custom properties, which any style sheet can use with var(–color-text). And it validates the rules of the design: every text and background pair must pass contrast, and every spacing value must be on the scale. A design system that checks itself cannot drift, which is the most valuable property of the whole idea.
const tokens = JSON.parse(`{
"color": {
"water": "#2a6b78", "mist": "#eaf3f5", "deep": "#0f2a30", "accent": "#a8472f",
"text": "{color.deep}", "background": "{color.mist}", "action": "{color.accent}", "action-text": "#ffffff", "link": "{color.water}"
},
"space": { "1": "4px", "2": "8px", "3": "16px", "4": "24px", "5": "32px", "6": "48px" },
"font": { "size-0": "16px", "size-1": "20px", "size-2": "25px", "size-3": "31.25px" },
"radius": { "card": "8px" }
}`);
function flatten(o, p = []) { return Object.entries(o).flatMap(([k, v]) => typeof v === 'object' ? flatten(v, [...p, k]) : [[[...p, k].join('.'), v]]); }
const flat = Object.fromEntries(flatten(tokens));
function resolve(name, seen = []) {
if (seen.includes(name)) throw new Error('cycle: ' + [...seen, name].join(' -> '));
const v = flat[name];
if (v === undefined) throw new Error('unknown token ' + name);
const m = v.match(/^\{(.+)\}$/);
return m ? resolve(m[1], [...seen, name]) : v;
}
const resolved = Object.fromEntries(Object.keys(flat).map(k => [k, resolve(k)]));
const css = ':root {\n' + Object.entries(resolved).map(([k, v]) => ' --' + k.replace(/\./g, '-') + ': ' + v + ';').join('\n') + '\n}';
console.log(css);
const lum = hex => { const c = [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16) / 255).map(x => x <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4)); return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; };
const ratio = (a, b) => { const [x, y] = [lum(a), lum(b)].sort((p, q) => q - p); return (x + 0.05) / (y + 0.05); };
const pairs = [['color.text', 'color.background'], ['color.link', 'color.background'], ['color.action-text', 'color.action']];
const checks = pairs.map(([f, b]) => ({ pair: f + ' on ' + b, ratio: Number(ratio(resolved[f], resolved[b]).toFixed(2)) }));
const SCALE = [0, 4, 8, 12, 16, 24, 32, 48, 64];
const badSpace = Object.entries(resolved).filter(([k]) => k.startsWith('space.')).filter(([, v]) => !SCALE.includes(parseFloat(v)));
let cycle = null; try { flat['color.a'] = '{color.b}'; flat['color.b'] = '{color.a}'; resolve('color.a'); } catch (e) { cycle = e.message; }
console.log('--- checks');
checks.forEach(c => console.log(c.pair.padEnd(40), c.ratio.toFixed(2), c.ratio >= 4.5 ? 'passes AA' : 'FAILS'));
console.log('off-scale spacing tokens:', badSpace.length, '| cycle detection says:', cycle);
console.log('DATA ' + JSON.stringify({ resolved, checks, cycle, css }));
:root {
--color-water: #2a6b78;
--color-mist: #eaf3f5;
--color-deep: #0f2a30;
--color-accent: #a8472f;
--color-text: #0f2a30;
--color-background: #eaf3f5;
--color-action: #a8472f;
--color-action-text: #ffffff;
--color-link: #2a6b78;
--space-1: 4px;
--space-2: 8px;
--space-3: 16px;
--space-4: 24px;
--space-5: 32px;
--space-6: 48px;
--font-size-0: 16px;
--font-size-1: 20px;
--font-size-2: 25px;
--font-size-3: 31.25px;
--radius-card: 8px;
}
--- checks
color.text on color.background 13.37 passes AA
color.link on color.background 5.37 passes AA
color.action-text on color.action 5.82 passes AA
off-scale spacing tokens: 0 | cycle detection says: cycle: color.a -> color.b -> color.a
{
"color": {
"water": "#2a6b78", "mist": "#eaf3f5", "deep": "#0f2a30", "accent": "#a8472f",
"text": "{color.deep}", "background": "{color.mist}", "action": "{color.accent}", "action-text": "#ffffff", "link": "{color.water}"
},
"space": { "1": "4px", "2": "8px", "3": "16px", "4": "24px", "5": "32px", "6": "48px" },
"font": { "size-0": "16px", "size-1": "20px", "size-2": "25px", "size-3": "31.25px" },
"radius": { "card": "8px" }
}
The build step flattened the nested tokens to names such as color.text, resolved every alias, and wrote one CSS custom property for each. Look at what happened to color.text: it was written in the file as {color.deep}, and the CSS has –color-text: #0f2a30, the value of color.deep. Components use only var(–color-text), so if the owner wants a darker deep colour, the designer changes one line of the JSON, rebuilds, and the text, the headings and the footer all change together. A dark theme would be a second mapping of the same semantic names to different base values.
The validation step checked the contrast of the three text and background pairs that the design uses: color.text on color.background is 13.37 to 1; color.link on color.background is 5.37 to 1; color.action-text on color.action is 5.82 to 1. All pass AA for normal text, and the build would fail with a message if any pair did not. The spacing tokens were checked against the scale and none is off it. The cycle test shows a different safety net: when two tokens were made to refer to each other, the resolver stopped with the message “cycle: color.a -> color.b -> color.a” instead of looping for ever, which would otherwise hang the build in a way that is hard to diagnose.
Independent check: the same tokens were resolved a second time in Python, and the generated CSS text was parsed back with a regular expression and compared with the Python resolution, so the custom properties in the output file are exactly the values that the aliases point to, with no property missing or extra. The contrast ratios of the three pairs were recomputed with Python’s own implementation of the formula and agree to two decimals. This checks the generator from the outside, the way a user of the CSS would meet it.
Check by hand: color.text points to color.deep, #0f2a30, and color.background points to color.mist, #eaf3f5. A very dark colour on a very light one gives a high ratio, above 12 to 1. The white text on the accent colour #a8472f has a lower ratio but still above 4.5, since the accent is a dark red-brown.
A raw hex code typed into a component bypasses the system. Add a lint rule that rejects raw colours and spacing values in component styles, as lesson 5 showed.
Base tokens say what a value is, and semantic tokens say what it is for. Components use only semantic ones, and themes only change the mapping.
Every calculation in this lesson was run while the course was written, in JavaScript (Node.js 22) and checked independently in Python 3.13 (and, where it says so, with simulations or real files). Design guidelines are rules of thumb and tools change, so check current documentation, and test your own designs with real people. Large teams use token tools and formats such as the W3C design tokens draft. The ideas in this lesson are the same, so check the current specification before choosing one.
Practice
Add a dark theme as a second JSON mapping and generate a second CSS file. Add a token for the focus ring and a rule that its contrast on the background is at least 3 to 1. Make the build fail on an unknown alias, and test it.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What is a design token?
- A login key
- A font file
- A named design value kept in one place
- A kind of image
color.text, space.3.
What is an alias token?
- A copy of a file
- A token that refers to another token
- A comment
- A browser setting
{color.deep}.
Why detect cycles?
- Cycles are decorative
- A cycle would make the build loop forever
- Browsers need them
- They speed up CSS
A refers to B and B to A.
Why validate contrast in the build?
- A bad pair then cannot ship unnoticed
- It makes CSS shorter
- It changes hues
- It is required by HTML
The system checks itself.
Why parse the generated CSS in a second language?
- To check the output from the outside
- To translate it
- To compress it
- It is the only way to read CSS
Independent verification.
Summary
- Tokens store design decisions once, by role.
- A build resolves aliases, detects cycles and writes CSS custom properties.
- Validate contrast and spacing in the build.
- Verify the generator’s output independently.
Questions
Do I need a design system for a small site?
Not a big one. Even a single tokens file for colour, type and spacing pays off, because it makes changes and consistency easy.
What are CSS custom properties?
Variables in CSS, written --name and read with var(--name). They cascade like other properties, so they can change by theme or by component.
How do tokens reach the design tool?
Many design tools can import tokens from JSON through plugins, so designers and developers share one source. Check your tool's documentation.
