DEV Community

Cover image for I hand-rolled 41 GitHub README badges. Here is what actually breaks.
Bharat Malhotra
Bharat Malhotra

Posted on

I hand-rolled 41 GitHub README badges. Here is what actually breaks.

Key Takeaways

  • Generating SVG badges server-side removes all browser safety nets: invalid CSS properties like unitless font sizes silently fail back to 16px.
  • SVGs that rely solely on SMIL animations (opacity="0") render as blank rectangles in raster pipelines, link previews, and cached frames.
  • Measuring rendered DOM rects using getBoundingClientRect() rather than untransformed getBBox() catches overlapping labels across custom layouts.
  • Serving badges at scale requires a single upstream GraphQL query, 60-second in-memory deduplication, and a 6-hour edge cache with ETag/304 validation.

Your profile README is a landing page you never A/B test. Mine used to be a stack of external image URLs hosted by third-party services. When one of those shared hosts encountered reliability issues or temporary pauses, my profile quietly displayed broken image icons to recruiters, and nothing threw an error in my logs.

That is the fragility of an image-url README. So I decided to build and render them myself.

I ended up building ReadmeCraft — a dual-mode README studio that supports 41 self-rendered SVG badge types, 63 aesthetic themes, 16 community persona templates, and 3 profile layouts (Bento / Minimalist / Titan) behind a single endpoint:

![Streak](https://readme.bharatdn.com/api/badges?username=ErBharatMalhotra&type=streak&theme=tokyonight)
![Heatmap](https://readme.bharatdn.com/api/badges?username=ErBharatMalhotra&type=heatmap&theme=gta6)
Enter fullscreen mode Exit fullscreen mode

Self-rendered SVG badges

Here are the six engineering bugs that cost the most time during development, in the exact order they bit me.


1. The Unitless Number That Silently Became 16px

My badges looked terrible for an embarrassingly long time: every label overlapping every other label, with numerical values sitting directly on top of titles. Not "slightly cramped"—a complete pile of text sharing identical coordinates.

The culprit was four lines in a lightweight styling helper:

// before — joins values straight into CSS
function css(cls: string, props: Record<string, string | number>) {
  const body = Object.entries(props).map(([k, v]) => `${k}: ${v};`).join(' ');
  return `.${cls} { ${body} }`;
}

css('label', { fill: '#ffb399', 'font-family': FONT_MONO, 'font-size': 9 });
// -> .label { fill: #ffb399; font-family: ...; font-size: 9; }
Enter fullscreen mode Exit fullscreen mode

In standard CSS, font-size: 9 is invalid. CSS lengths require a unit (px, em, rem), whereas SVG presentation attributes (<text font-size="9">) do not. Because the CSS declaration was invalid, the browser silently rejected it and every text element inherited the default 16px.

My layout engine assumed 9px font metrics, but the browser rendered 16px glyphs. Because text truncation calculations relied on the estimated 9px width, strings overflowed their bounding boxes completely.

The nasty part: nothing logs, nothing warns, and the HTTP response returns 200 OK. The only symptom is visual. Measuring it with browser devtools is what proves it:

getComputedStyle(labelEl).fontSize;
// Returns "16px" when you expected "9px"
Enter fullscreen mode Exit fullscreen mode

The fix requires appending px to numerical values except for explicitly unitless properties:

const UNITLESS = new Set([
  'font-weight', 'opacity', 'fill-opacity', 'stroke-opacity', 'z-index', 'line-height', 'flex',
]);

const value = typeof v === 'number' && !UNITLESS.has(k) ? `${v}px` : v;
Enter fullscreen mode Exit fullscreen mode

If you take one lesson from this article: whenever you generate SVG strings with embedded CSS, assert the computed styles programmatically. A one-line assertions check would have saved me a week of tweaking coordinates that were never broken.


2. opacity="0" Plus an Animation Equals a Blank Badge

Fade-in transitions are inexpensive and make static SVG images feel alive:

<g opacity="0">
  <animate attributeName="opacity" values="0;1" dur="0.6s" fill="freeze"/>
  <!-- badge content -->
</g>
Enter fullscreen mode Exit fullscreen mode

This renders perfectly in a standard browser tab. However, when viewed in an environment that does not execute SMIL animations — such as a screenshot generation pipeline, an image rasterizer, a link preview card on X or LinkedIn, or a reader with reduced motion enabled — the group renders as completely empty. Not broken-looking, but transparent. Just a title on an empty canvas.

The rule I follow now: the static initial frame must be fully visible and correct; animation is strictly an enhancement.

<!-- content is visible with zero animation support -->
<g opacity="1">
  <animate attributeName="opacity" values="0;1" dur="0.6s" fill="freeze"/>
  <!-- badge content -->
</g>
Enter fullscreen mode Exit fullscreen mode

Same visual fade-in where animation runs, and a fully legible badge where animation is unsupported.


3. You Have to Measure Text Yourself

An API route rendering SVG has no built-in layout engine. Nothing tells you that "Architecture 80%" occupies 93px at 9px monospace until a browser actually draws it — and by then, GitHub's image proxy has already cached the asset.

To prevent overflow, you maintain a font metrics table and estimate character widths prior to layout:

const FONT_METRICS = {
  mono:    { 9: 5.5, 10: 6, 11: 6.6, 12: 7.2, 14: 8.4, 16: 9.6 },
  display: { 14: 8.5, 16: 9.7, 18: 10.9 },
};

function estimateTextWidth(text: string, size: number, family = 'mono') {
  return text.length * (FONT_METRICS[family][size] ?? 7);
}
Enter fullscreen mode Exit fullscreen mode

That approximation is fine — it only needs to be slightly pessimistic. What caused silent failures was passing unexpected data types. My code-pulse card rendered numbers like 3,902, 90, and 50 perfectly, until two cards rendered nothing but .... The values were numbers instead of strings, triggering a cascade failure:

estimateTextWidth(90, 14);
// text.length is undefined for a number
// -> undefined * 8.4 === NaN

// truncateText() then executes:
if (estimateTextWidth(text, ...) <= maxWidth) return text; // NaN <= 50 is false
let high = text.length;           // undefined
while (low <= high) { ... }       // 0 <= undefined is false, loop never runs
return result || ellipsis;        // '' || '...' -> '...'
Enter fullscreen mode Exit fullscreen mode

The badge appeared unable to fetch commit data, when in reality it had the numbers all along. One typeof mismatch at the boundary turned valid statistics into ellipses, bypassing TypeScript compilation checks when call sites used any. Coercion at input solves this permanently:

safeText({ content: String(stat.value), ... });
Enter fullscreen mode Exit fullscreen mode

4. The 40 Lines That Caught 90 Overlapping Labels

Eyeballing thumbnail previews does not scale across 41 badge types and 63 themes. What does scale is programmatic DOM measurement: render the SVG in a hidden container, query every <text> element, normalize coordinates by the viewBox scale, and detect intersections.

getBBox() is the intuitive choice, but it is incorrect here — it returns coordinates in the element's own untransformed coordinate space, so labels inside nested <g transform="translate(...)"> groups report identical coordinates. Instead, use getBoundingClientRect() on a rendered SVG DOM:

const svg = document.querySelector('svg');
const vb = svg.viewBox.baseVal;
const root = svg.getBoundingClientRect();
const scale = root.width / vb.width; // badges are scaled via CSS

const boxes = [...svg.querySelectorAll('text')].map((el) => {
  const r = el.getBoundingClientRect();
  return {
    text: el.textContent.trim(),
    x: (r.left - root.left) / scale,
    y: (r.top - root.top) / scale,
    x2: (r.right - root.left) / scale,
    y2: (r.bottom - root.top) / scale,
  };
}).filter((b) => b.text && b.x2 - b.x > 0.5);

const outOfBounds = boxes.filter(
  (b) => b.x < -1 || b.y < -1 || b.x2 > vb.width + 1 || b.y2 > vb.height + 1,
);
Enter fullscreen mode Exit fullscreen mode

Pairwise intersection detection with a tolerance handles glyph bounding boxes:

const overlaps = [];
for (let i = 0; i < boxes.length; i++) {
  for (let j = i + 1; j < boxes.length; j++) {
    const a = boxes[i], b = boxes[j];
    const w = Math.min(a.x2, b.x2) - Math.max(a.x, b.x);
    const h = Math.min(a.y2, b.y2) - Math.max(a.y, b.y);
    if (w > 3 && h > 3) overlaps.push(`${a.text} <> ${b.text} (${w}x${h})`);
  }
}
Enter fullscreen mode Exit fullscreen mode

On our first automated audit run, 12 of 19 badge types showed overlapping or out-of-bounds text. After fixing the unitless font-size bug, opacity groups, and text truncation helpers, 18 of 19 passed cleanly. The single exception was the typing badge, where phrases overlap intentionally to achieve a CSS cross-fade animation.


5. The Open Graph Image Must Be a PNG

An architectural oversight unrelated to badges: I initially shipped our social preview image as an SVG. It looked immaculate in local browser testing, but produced a blank white card when shared on X, LinkedIn, and Slack, because their scrapers do not execute SVG rendering pipelines.

Switching to a 1200×630 PNG asset, setting type: 'image/png', and configuring metadataBase in Next.js so relative /og.png paths resolve to absolute URLs resolved the issue.


6. Rendering Is the Easy Half — Serving Is the Hard Half

An API route that renders dynamic SVGs acts as a public proxy in front of GitHub's rate limits. To ensure high availability and sub-second response times, our architecture relies on:

  1. A Single GraphQL Query: Profile metadata, repositories, language percentages, contribution calendars, and pinned repositories are fetched in one unified GraphQL request rather than dozens of REST calls.
  2. 60-Second In-Memory Deduplication: Concurrent requests for multiple badges from the same profile do not duplicate upstream API calls.
  3. 6-Hour Edge Caching: Cache-Control: public, max-age=21600, stale-while-revalidate=21600 combined with ETag/304 validation ensures cache hits cost zero quota.
  4. Deterministic Fallbacks: When rate limits are exhausted, badges serve cached historical data or clean fallback states rather than throwing rendering errors.

Try ReadmeCraft Studio

ReadmeCraft is the dual-mode README studio built on top of these learnings:

  • Profile Mode: Enter any GitHub handle to generate an optimized profile README with real language breakdown bytes and contribution stats.
  • Project Mode: Enter any public repository URL to auto-generate a project README by parsing package.json or Cargo.toml.
  • Customization: 41 badge types, 63 themes, 16 community persona templates, and 3 profile presets.

ReadmeCraft studio: section blocks, markdown editor and GitHub preview

If you test your handle and encounter any rendering issues, open an issue on GitHub with your username. And if you take only one takeaway from this post: inspect the computed font size of your rendered SVG badges today. They might not be rendering at the size you wrote.

Top comments (0)