# Digital sustainability and website carbon performance

> Estimate a web page's emissions with SWDM v4 and CO2.js, cut them with lighter pages, caching, images and green hosting, and avoid greenwashing.

- Autore / Author: Diego Betto (https://diegobetto.com/about/)
- Pubblicato / Published: 2026-12-01
- URL: https://diegobetto.com/en/digital-sustainability-web-carbon-performance/
- Tag: performance, sustainability, core-web-vitals, web-development

"How much does our website pollute?" is a question that can come from a client, from whoever writes the sustainability report, or from someone who has just spotted a green badge on a competitor's site. The tempting answer is to open the first online calculator, copy the number and move on.

You can do better, without becoming an energy expert. Every HTTP request uses electricity in three places: the **data center** that answers, the **network** that carries the response and the **device** that downloads, parses and paints it. In the estimation model we'll use here, the third one is the heaviest. The proxy for the total is bytes transferred: imperfect, but measurable in any pipeline.

The good news is that performance work and carbon work are mostly the same work. If you've already sorted out your [Core Web Vitals](https://diegobetto.com/en/core-web-vitals-lcp-cls-inp/), you're halfway there. What's missing is a repeatable way to turn bytes into an estimate, a limit enforced in CI and some care about what you can claim in public.

### How a page's CO2 is estimated

The reference is the **Sustainable Web Design Model** (SWDM), now at version 4 (v3 is archived). It starts from the gigabytes transferred and converts them into energy with a coefficient for each of three segments. For each one it separates **operational** energy (used while the system is running) from **embodied** energy (the share tied to manufacturing the hardware).

| Segment     | Operational (kWh/GB) | Embodied (kWh/GB) | Share of total |
| ----------- | -------------------- | ----------------- | -------------- |
| Data center | 0.055                | 0.012             | 22%            |
| Network     | 0.059                | 0.013             | 24%            |
| Device      | 0.080                | 0.081             | 54%            |

Energy becomes CO2 equivalent once multiplied by the **carbon intensity of the electricity grid**: the default is 494 gCO2e/kWh, Ember's world average. Three more inputs, all between 0 and 1, refine the estimate: the green hosting factor, the share of returning visitors and the share of data they download again compared with a first visit.

#### A back-of-the-envelope example

Adding up the table gives 0.300 kWh per gigabyte. So:

- 1 GB transferred ≈ 0.300 × 494 ≈ **148 g** of CO2e;
- a 2 MB page with no cache (2 MB = 0.002 GB) ≈ **0.3 g** per visit.

The model then maps the estimate to a grade, the **Digital Carbon Rating**. These are the SWDM v4 thresholds, in grams per pageview:

| Rating | Upper bound (g) |
| ------ | --------------- |
| A+     | 0.040           |
| A      | 0.079           |
| B      | 0.145           |
| C      | 0.209           |
| D      | 0.278           |
| E      | 0.359           |
| F      | above 0.359     |

Our 2 MB page lands in band **E**. Treat that as an order of magnitude: for precise figures use the library, which applies the formula without my rounding.

> This is a model, not a measurement. Nobody has attached a power meter to your servers or your
> users' phones: bytes are a proxy for energy. Two pages of the same weight with very different
> compute costs (one animates canvas and video, the other is plain text) get the same estimate. Use
> the number to compare before and after, not as an accounting figure.

### Measuring with CO2.js

[CO2.js](https://github.com/thegreenwebfoundation/co2.js) is the Green Web Foundation's open source library that implements these models. The package is `@tgwf/co2` (the examples below use 0.19.0), it supports two models, `swd` and `1byte`, and defaults to SWD v4.

```bash
pnpm add -D @tgwf/co2
```

The simplest case: how many grams does a visit that transfers a given number of bytes cost?

```js
import { co2 } from "@tgwf/co2";

const swd = new co2({ model: "swd", version: 4, rating: true });

const bytes = 2_000_000;
const isGreen = false;

const result = swd.perVisit(bytes, isGreen);
console.log(result); // { total: 0.2964, rating: "E" } (rounded)
```

The second argument says whether the site is served by a green host. With `rating: true` you get an object with `total` and `rating`; without it, just the number of grams. There's also `perByte(bytes, green)`, which looks at pure data transfer, and the `results: "segment"` option to see the split between data center, network and device.

With `isGreen = true` the same page drops to about 0.242 g, band D. That's a reduction of roughly 18%, not a reset to zero: we'll see why shortly.

#### Fitting the estimate to your traffic

`perVisit` assumes every visit is a first visit and uses the world average intensity. If you know your audience, `perVisitTrace` accepts more realistic values and also returns the variables it used, which are handy to attach to a report.

```js
import { co2 } from "@tgwf/co2";

const swd = new co2({ model: "swd", version: 4, rating: true });

const trace = swd.perVisitTrace(2_000_000, false, {
  firstVisitPercentage: 0.75, // 75% first visits
  returnVisitPercentage: 0.25, // 25% returning visitors
  dataReloadRatio: 0.02, // returning visitors re-download 2% of the bytes
  greenHostingFactor: 0, // 0 = no green share, 1 = fully green
  gridIntensity: {
    device: { country: "ITA" }, // ISO alpha-3 code
    // dataCenter and networks take a number (g/kWh) or { country }
  },
});

console.log(trace.co2); // about 0.199 g, rating "C"
console.log(trace.green, trace.variables);
```

Same 2 MB, but with a quarter of the visits served almost entirely from cache and devices running on the Italian grid: the estimate goes from about 0.30 to about 0.20 g. The lesson isn't that you can tweak the inputs until a nice grade shows up. It's the opposite: **always state your assumptions**, take them from your analytics and keep them fixed between measurements. The intensity data bundled with the library can change between releases, so pin the package version too.

#### Where the bytes come from

The estimate needs transferred weight, not size on disk. In the console, after reloading with the cache disabled in DevTools, the Resource Timing API gives you a total in seconds:

```js
const entries = [
  ...performance.getEntriesByType("navigation"), // the HTML document
  ...performance.getEntriesByType("resource"), // everything else
];

const bytes = entries.reduce((sum, entry) => sum + entry.transferSize, 0);
console.log(bytes);
```

Then pass the number to a small Node script:

```js
// estimate.mjs — usage: node estimate.mjs 1843000 [green]
import { co2 } from "@tgwf/co2";

const [bytesArg, greenArg] = process.argv.slice(2);
const bytes = Number(bytesArg);

if (!Number.isFinite(bytes) || bytes <= 0) {
  console.error("Usage: node estimate.mjs <bytes> [green]");
  process.exit(1);
}

const swd = new co2({ model: "swd", version: 4, rating: true });
const { total, rating } = swd.perVisit(bytes, greenArg === "green");

console.log(`${(bytes / 1e6).toFixed(2)} MB → ${total.toFixed(3)} g CO2e, rating ${rating}`);
```

Mind one limit of the snippet: cross-origin resources that don't send the `Timing-Allow-Origin` header report a `transferSize` of 0. With lots of third-party scripts the total is an **under-estimate**, often in exactly the heaviest part. Cross-check it against the total in the Network tab.

### Where you actually save bytes

Once you have a number, the question is where to act. The levers are the familiar ones, with a shift in perspective: what gets downloaded below the fold or in the background counts too, not only what delays the first render.

| Lever                            | Effect on bytes                | Effect on Core Web Vitals          |
| -------------------------------- | ------------------------------ | ---------------------------------- |
| Responsive AVIF/WebP images      | Often the biggest saving       | Better LCP                         |
| Lazy loading below the fold      | Avoids downloads nobody sees   | Less competition with the LCP      |
| Less JavaScript, partial hydration | Less transfer and less CPU   | Better INP                         |
| Subsetted, self-hosted fonts     | Smaller files, fewer origins   | More predictable LCP and CLS       |
| Fewer or deferred third parties  | Varies, sometimes huge         | INP and LCP                        |
| Long caching for hashed assets   | Close to zero on repeat visits | Faster repeat navigations          |

**Images.** Check the real on-screen dimensions, not just the format. A modern file served at twice the width it needs is still waste. And keep the LCP image out of lazy loading.

**JavaScript.** It's the most expensive byte, because after downloading it has to be parsed and executed on the device, the heaviest segment in the model. An islands architecture hydrates only what is interactive. Moving computation into a [Web Worker](https://diegobetto.com/en/web-worker-javascript/), on the other hand, frees the main thread and helps INP, but saves no bytes and doesn't by itself reduce CPU work: don't count it towards emissions.

**Fonts.** Every family and every weight is a download. Few files, subsets with only the characters you need, served from your own domain.

**Third parties.** Tag managers, chat widgets, social widgets and video embeds are often the least controlled item. For videos the simple fix is a placeholder: a static thumbnail, with the player loaded only on click.

**Caching.** In the model, return visits that download little weigh far less. For files with a hash in their name, this is the header:

```http
Cache-Control: public, max-age=31536000, immutable
```

HTML and dynamic responses need shorter lifetimes and revalidation: I covered that, along with CDNs and the edge, in the article on [HTTP/3 and edge computing](https://diegobetto.com/en/http3-quic-edge-computing-web-performance/). Architecture matters too: pages generated ahead of time, as in the [headless CMS and Jamstack](https://diegobetto.com/en/headless-cms-jamstack-ai-personalization/) approach, avoid repeating the same render on every request.

As for this blog: images go through `astro:assets`, which produces WebP (with `srcset` on the grid cards), React islands hydrate with `client:visible`, fonts are self-hosted and YouTube videos are a facade that creates the iframe only on click. To me these are performance optimizations first: the saved bytes come as a bonus.

### Green hosting: checking it with an API

"Our provider runs on renewable energy" is something you can check. The Green Web Foundation exposes a Greencheck endpoint: you pass the **bare hostname**, with no protocol or path, and the documentation requires no authentication.

```bash
curl https://api.thegreenwebfoundation.org/api/v3/greencheck/example.com
```

If the domain is green, the response contains `url`, `green`, `hosted_by`, `hosted_by_website`, `partner`, `hosted_by_id`, `modified` and the `supporting_documents` list, with `id`, `title` and `link` for each document. Otherwise it's much shorter: `url`, `green: false` and `data: false`.

In TypeScript it pays to model both cases as a discriminated union, so the compiler stops you from reading fields that aren't there:

```ts
type Greencheck =
  | {
      url: string;
      green: true;
      hosted_by: string;
      hosted_by_website: string;
      partner: string | null;
      hosted_by_id: number;
      modified: string;
      supporting_documents: { id: number; title: string; link: string }[];
    }
  | { url: string; green: false; data: false };

export async function greencheck(input: string): Promise<Greencheck> {
  // Accepts a full URL too, but only the hostname reaches the API
  const { hostname } = new URL(input.includes("://") ? input : `https://${input}`);

  const response = await fetch(
    `https://api.thegreenwebfoundation.org/api/v3/greencheck/${hostname}`,
  );
  if (!response.ok) throw new Error(`Greencheck: HTTP ${response.status}`);

  return (await response.json()) as Greencheck;
}

const result = await greencheck("example.com");

if (result.green) {
  console.log(`Green, hosted by ${result.hosted_by}`);
  for (const doc of result.supporting_documents) console.log(`- ${doc.title}: ${doc.link}`);
} else {
  console.log("No evidence of green hosting");
}
```

`green: true` rests on the provider's supporting documents: read them before quoting the result to a client. The documentation states no rate limits, but that's no reason to call the API on every request: the answer rarely changes, so check it in CI and store it.

The result plugs into CO2.js through the `green` boolean or, in v4, through `greenHostingFactor`, a value between 0 and 1 that helps when only part of the infrastructure is covered (green origin but not the CDN, for instance).

> Green hosting doesn't cancel network and device emissions. In the model the device takes 54% of
> the allocation, and in CO2.js the green factor only affects the data center's operational energy.
> With default values, moving to a green host removes about 18% of the estimate: worth having, but a
> heavy page is still heavy.

### A carbon budget in CI

A one-off measurement goes stale at the first redesign. If the site is static, the simplest check is to read the build folder, add up the weight of a page and the files it references, and fail the pipeline when the rating drops below a threshold.

```js
// carbon-budget.mjs — run after the build
import { readFile } from "node:fs/promises";
import { gzipSync } from "node:zlib";
import { join } from "node:path";
import { co2 } from "@tgwf/co2";

const DIST = "dist";
const PAGES = ["index.html", "blog/index.html"];
const WORST_ALLOWED = "C"; // up to 0.209 g per visit
const SCALE = ["A+", "A", "B", "C", "D", "E", "F"];
const ASSET = /(?:src|href)="(\/[^"?#]+\.(?:css|js|svg|png|jpe?g|webp|avif|woff2))"/g;
const TEXT = /\.(?:html|css|js|svg)$/;

async function transferBytes(path) {
  const content = await readFile(join(DIST, path));
  // Text files travel compressed: approximate with gzip
  return TEXT.test(path) ? gzipSync(content).length : content.length;
}

const swd = new co2({ model: "swd", version: 4, rating: true });
let failed = false;

for (const page of PAGES) {
  const html = await readFile(join(DIST, page), "utf8");
  const assets = new Set([...html.matchAll(ASSET)].map((match) => match[1]));

  let bytes = await transferBytes(page);
  for (const asset of assets) bytes += await transferBytes(asset);

  const { total, rating } = swd.perVisit(bytes, false);
  const ok = SCALE.indexOf(rating) <= SCALE.indexOf(WORST_ALLOWED);
  failed ||= !ok;

  console.log(
    `${ok ? "OK  " : "FAIL"} ${page}: ${(bytes / 1000).toFixed(0)} kB, ${total.toFixed(3)} g, ${rating}`,
  );
}

if (failed) process.exit(1);
```

```yaml
# sample GitHub Actions steps
- run: pnpm build
- run: node carbon-budget.mjs
```

With non-green hosting and default values, the C threshold works out to about 1.4 MB transferred.

The script is deliberately rough, and you should know what it misses: fonts and images referenced from CSS, `srcset` variants, dynamically loaded chunks, third parties. On the other hand it counts `lazy` images the user may never reach. Its value isn't the absolute number but the **comparison over time**: if a pull request adds 600 kB, you find out before merging.

If you already enforce a page weight budget in Lighthouse or another tool, you can get the same effect by translating the threshold in grams into a threshold in bytes and applying it there.

### Grid-aware and carbon.txt

The same Green Web Foundation runs two other projects worth watching. **Grid-aware Websites** explores sites that take the conditions of the electricity grid into account. **carbon.txt** is about publishing a website's sustainability information in a predictable place. I'm only pointing them out here: read the project's current documentation before adopting either.

### Regulation and market: why agencies are talking about it

Part of the interest comes from European rules, which changed in two directions in 2026.

**CSRD.** With the Omnibus I package (published in the Official Journal on 26 February 2026, in force since 18 March 2026) the sustainability reporting obligation narrowed to companies with **more than 1000 employees and more than €450 million** in net turnover. For non-EU groups the test is €450 million of turnover in the EU, plus a European subsidiary or branch above €200 million. Member states have until 19 March 2027 to transpose it.

For people building websites the consequence is this: direct obligations hit far fewer companies, but a large client within scope can still ask suppliers for data useful to its indirect (Scope 3) emissions. There's a ceiling, though: the so-called _value-chain cap_ limits requests to companies with fewer than 1000 employees. In practice a small agency gets fewer mandatory requests, and can use the topic as a commercial offer more than as compliance work.

**Greenwashing.** Directive (EU) 2024/825 on empowering consumers for the green transition applies from **27 September 2026** and bans claims of neutral, reduced or positive impact based on **offsetting** emissions: "carbon neutral" or "CO2 neutral" obtained by buying credits. A "zero impact website" badge built that way is a legal risk. What you can talk about is measured reductions: "the homepage went from X to Y estimated grams per visit, with this model and these assumptions".

**Guidelines.** The W3C has the **Web Sustainability Guidelines**, published by the Sustainable Web Interest Group as a _Group Note Draft_. They are not a Recommendation and don't carry formal W3C endorsement, but they work well as a project checklist, from design to infrastructure.

> The argument that sells isn't the green badge. It's "the site is faster, cheaper to serve and we
> can prove the improvement". Lower estimated emissions are the third column of the same report,
> with the advantage of surviving a follow-up question.

### Checklist

- [ ] Transferred weight measured on the main pages, with an empty and a warm cache
- [ ] CO2.js estimate, with model, version and assumptions written in the report
- [ ] Images in modern formats, sized for the layout, lazy below the fold
- [ ] JavaScript and third parties reviewed: what can go or load on interaction
- [ ] Fewer, subsetted, self-hosted fonts
- [ ] Long, `immutable` `Cache-Control` on hashed assets
- [ ] Hosting checked with Greencheck and supporting documents read
- [ ] Weight or carbon budget that blocks regressions in CI
- [ ] No neutrality claims based on offsetting

### Frequently asked questions

> **Does a lightweight site really pollute less?**
>
> For the same traffic, fewer bytes mean less estimated energy across data center, network and
> device, and usually less CPU work on the phone too. The exact ratio between bytes and energy is a
> simplification of the model, though: real savings can't be measured down to the gram.

> **How reliable is the A+ to F rating?**
>
> It's reliable for comparing versions of the same page, or different pages, with the same
> assumptions and the same model version. It isn't a certification and doesn't measure real
> consumption: pages with heavy processing and few bytes may get a better grade than they deserve.

> **Is green hosting enough?**
>
> No. It reduces the part tied to data center energy, but network, device and hardware manufacturing
> remain. With CO2.js default values the effect is around 18% of the estimate: worth doing, together
> with cutting page weight.

> **Can I say my website is carbon neutral?**
>
> If the neutrality relies on offsetting, no: from 27 September 2026 Directive (EU) 2024/825 bans
> that kind of claim. Report measured reductions, with method and limits, and get legal advice for
> specific cases.

### Conclusion

The most useful thing to do this week doesn't need a sustainability program: pick your most visited page, measure how many bytes it transfers, feed them to CO2.js and write the result next to your assumptions. Then remove the heaviest thing nobody will miss and measure again. You'll have a faster site and, when someone asks how much it pollutes, an answer you can defend because you know where every figure comes from.

**References:**

- [Sustainable Web Design: estimating digital emissions](https://sustainablewebdesign.org/estimating-digital-emissions/)
- [Digital Carbon Ratings](https://sustainablewebdesign.org/digital-carbon-ratings/)
- [CO2.js: documentation](https://developers.thegreenwebfoundation.org/co2js/overview/)
- [CO2.js: perVisitTrace](https://developers.thegreenwebfoundation.org/co2js/functions/pervisit-trace/)
- [Greencheck API: checking a single domain](https://developers.thegreenwebfoundation.org/api/greencheck/v3/check-single-domain/)
- [W3C: Web Sustainability Guidelines](https://www.w3.org/TR/web-sustainability-guidelines/)
- [W3C: WSG publication history](https://www.w3.org/standards/history/web-sustainability-guidelines)
- [Latham & Watkins: EU Sustainability Omnibus published in the Official Journal](https://www.lw.com/en/insights/EU-Sustainability-Omnibus-Published-in-the-Official-Journal)
- [Directive (EU) 2024/825 on EUR-Lex](https://eur-lex.europa.eu/eli/dir/2024/825/oj)
- [European Commission: document on Directive 2024/825](https://commission.europa.eu/document/download/3c257883-bb2a-4dd9-a6dc-501d587bb34f_en)
