🎨 Design Engineering

Design Systems in Code: Harmonizing Token Architectures Between Figma & CSS

By Visual Computing & Brand Identity Review Board•

Creative & Technical Insights

Bridging visual design and engineering: automating design token extraction from Figma variables into Style Dictionary JSON, CSS custom properties, and Tailwind tokens.

In modern enterprise product organizations, the chasm between design tools and engineering codebases has historically been a primary source of technical debt, visual inconsistency, and wasted developer hours. Designers author pixel-perfect mockups in Figma using custom color swatches and manual auto-layout paddings, only for frontend engineers to manually transcribe those values into fragmented CSS variables, Sass maps, or hardcoded Tailwind utility classes. Within weeks, the design tool and the production codebase drift apart. Design Token Architecture bridges this divide permanently. By establishing design tokens as the single, authoritative contract between design files and production code, engineering teams can construct automated Continuous Integration (CI/CD) pipelines that synchronize Figma Variables directly with CSS Custom Properties, TypeScript interfaces, and native mobile codebases.

Design System Architecture Advisory: Three-Tier Token Model

Authored by the Visual Computing & Brand Identity Review Board. Reference frameworks: W3C Design Tokens Community Group (DTCG) Specification, Figma REST API v1, and Style Dictionary v4 Architecture. Objective: Eliminating design drift through automated git-driven token pipelines with 100% compile-time TypeScript type safety.

1. The Three-Tier Design Token Architecture

A fatal mistake made by early design systems was creating a flat, one-dimensional token list (e.g., exposing --color-blue-500: #2563eb directly to UI components). If the brand re-brands from blue to terracotta, engineers must search and replace hundreds of references across the codebase. Modern enterprise design systems enforce a Three-Tier Token Hierarchy:

  • Tier 1: Global Tokens (Primitives): Raw, immutable values describing physical design choices without semantic context (e.g., color.palette.terracotta.500: #c2410c, space.16: 16px, font.family.display: 'Fraunces'). UI components are strictly forbidden from referencing Global Tokens directly.
  • Tier 2: Semantic Tokens (Aliases): Context-aware tokens that map primitives to functional meaning (e.g., color.background.primary: {color.palette.terracotta.500}, color.text.body: {color.palette.stone.800}). Semantic tokens enable effortless theming: switching to Dark Mode or High Contrast Mode requires altering only the semantic aliases while leaving primitive palettes untouched.
  • Tier 3: Component-Specific Tokens: Granular scoped tokens bound to individual component primitives (e.g., button.primary.bg.default: {color.background.primary}, modal.header.padding.bottom: {space.16}). Component tokens allow engineering squads to tweak a button's border radius without risking accidental regressions across unrelated card components.

2. Automated Synchronization: The Figma-to-Code Pipeline

To eliminate manual transcription errors, enterprise design systems implement automated Git-Driven Token Pipelines:

  1. Design Authoring in Figma: Designers define brand tokens using native Figma Variables (Color, Number, String, Boolean) organized into Collections (Primitives, Semantics, Modes).
  2. Webhook / GitHub Action Trigger: When the design library is published or updated, a GitHub Action dispatches a scheduled webhook or executes a script leveraging the Figma REST API (GET /v1/files/:file_key/variables/local).
  3. AST Normalization: The pipeline extracts raw Figma variable values and normalizes them into standard W3C DTCG JSON format (tokens.json).
  4. Transformation via Style Dictionary: Style Dictionary processes the JSON tokens, transforming values into platform-specific targets: CSS Custom Properties (tokens.css), TypeScript declarations (tokens.d.ts), Tailwind theme configurations, and iOS Swift structs.
  5. Automated Pull Request: The pipeline creates an automated GitHub PR with visual snapshot diffs, allowing engineering leads to review design token changes alongside automated unit tests.

3. End-to-End TypeScript Type Safety for Design Tokens

By compiling design tokens into strongly typed TypeScript const assertions (as const), front-end teams achieve compile-time verification across React MVC views:

Instead of passing unvalidated raw strings to styling props (e.g., <Box color="terracotta-rust" />), TypeScript infers the exact union of allowed semantic token keys (type ColorToken = keyof typeof designTokens.colors). If a developer mistypes a token name or references an obsolete alias, the TypeScript compiler immediately halts the build with an actionable error.

4. Technical Matrix: Token Representation Across Platforms

Platform / Environment Compiled Output Format Code Syntax Example Runtime Performance
Web / Modern Browsers CSS Custom Properties --color-brand-primary: #c2410c; Instant native browser cascade lookup
TypeScript / React MVC TypeScript Types & Const Objects tokens.colors.primary Zero runtime cost (Inlined at build)
iOS Native (SwiftUI) Swift Struct / Color Asset Catalog Color.brandPrimary Native binary compilation
Android Native (Compose) Kotlin Object (Jetpack Compose) BrandTokens.Colors.Primary Native binary compilation

5. Production Implementation: Automated Figma Token Fetcher in TypeScript

The following Node.js script demonstrates how enterprise pipelines fetch variables from the Figma REST API and transform them into normalized DTCG tokens:

// scripts/fetchFigmaTokens.ts
import fs from 'fs/promises';
import path from 'path';

const FIGMA_API_TOKEN = process.env.FIGMA_ACCESS_TOKEN || '';
const FIGMA_FILE_KEY = process.env.FIGMA_FILE_KEY || '';

interface FigmaVariable {
  id: string;
  name: string;
  resolvedType: 'COLOR' | 'FLOAT' | 'STRING';
  valuesByMode: Record<string, any>;
}

async function syncFigmaTokens() {
  const url = `https://api.figma.com/v1/files/${FIGMA_FILE_KEY}/variables/local`;
  const response = await fetch(url, {
    headers: { 'X-Figma-Token': FIGMA_API_TOKEN }
  });

  if (!response.ok) {
    throw new Error(`Figma API responded with status: ${response.status}`);
  }

  const data = await response.json();
  const variables: Record<string, FigmaVariable> = data.meta.variables;
  const tokenDictionary: Record<string, any> = {};

  for (const id in variables) {
    const variable = variables[id];
    // Convert Figma variable slash path (e.g. "color/brand/primary") to nested object
    const parts = variable.name.split('/');
    let current = tokenDictionary;

    for (let i = 0; i < parts.length - 1; i++) {
      current[parts[i]] = current[parts[i]] || {};
      current = current[parts[i]];
    }

    const leafKey = parts[parts.length - 1];
    const defaultModeId = Object.keys(variable.valuesByMode)[0];
    const rawVal = variable.valuesByMode[defaultModeId];

    current[leafKey] = {
      $value: rawVal,
      $type: variable.resolvedType.toLowerCase(),
      $description: `Synced from Figma Variable: ${variable.name}`
    };
  }

  const outputPath = path.resolve(process.cwd(), 'tokens/dtcg-tokens.json');
  await fs.writeFile(outputPath, JSON.stringify(tokenDictionary, null, 2), 'utf8');
  console.log(`Successfully synced ${Object.keys(variables).length} tokens to ${outputPath}`);
}

Frequently Asked Questions: Design Systems in Code

What is the W3C Design Tokens Community Group (DTCG) specification?

The DTCG is an official W3C working group establishing open, standardized JSON formats for design tokens. The specification mandates standard prefixes like $value and $type (e.g., color, dimension, duration), ensuring that design tools (Figma, Penpot), transformation engines (Style Dictionary), and codebases can exchange tokens without vendor lock-in.

How do design tokens handle Dark Mode and multi-brand themes?

Theming is handled at Tier 2 (Semantic Tokens). Rather than redefining every component, developers map semantic tokens to different global primitives based on a theme selector (e.g., [data-theme="dark"]). In Light Mode, --color-bg-canvas points to Linen (#f4f1ea); in Dark Mode, it points to Charcoal (#1c1917). Components reference only the semantic token, switching themes instantly.

Should design tokens include complex composite properties like typography and box-shadows?

Yes. DTCG format supports composite tokens that bundle related values together. A typography composite token encapsulates fontFamily, fontSize, fontWeight, lineHeight, and letterSpacing into a single structured object, which transformation engines compile into complete CSS class utilities or mixins.

How can teams detect accidental design token drift between releases?

Automate token linting in CI/CD using tools like Stylelint or custom TypeScript compiler passes. Prohibit hardcoded hex colors or pixel values in component CSS files. Any PR containing arbitrary literals (e.g., color: #ff0000; or padding: 17px;) fails automated CI checks until the developer replaces them with an approved semantic design token.

A&K

Visual Computing & Brand Identity Review Board

Our team of creative directors and print specialists establishes benchmarks for color accuracy, custom typography, and physical press craftsmanship.

Commission High-Fidelity Brand Engineering

Collaborate with our atelier to design bespoke brand identity systems, packaging, and custom typography.

Inquire Studio Brief →