24. July 2023 By Ko Turk
Your frontend is ☠️ ⚠️ Let's measure its impact with CO2.js
How sustainable is your code? Ever thought about how many CO2 emissions your code is producing? Probably not! But nowadays the climate is changing harder, and we need to do something! Why are we not beginning with measuring the code we make? Let's start with checking the front-end code!
The Green Web Foudation created an open-source JavaScript library that enabled developers to calculate the CO2 emissions based in the number of bytes.
How to start?
To use the library we need to install version 14 of Node or higher, which you can install here
After installing node, we install the co2 package with npm version 6 or newer:
npm install @tgwf/co2
You’re now ready to use the library (server-side) with:
const {co2} = require("@tgwf/co2")
const emission = new co2();
This requires node, but you can also run it browser side with:
import { co2 } from 'node_modules/@tgwf/co2/src/index.js'
Models
As you can see in the previous example, we now have a freshly created co2Emission object. But how to proceed, how to calculate your emissions? For that, we can use one of the following models:
- The Sustainable Web Design (SWD) model, calculates the emission of data center usage, network transfer, end-user device usage, and the production of hardware (see listening 1). It’s calculating all the energy used and it’s converting it to carbon emission based on the Ember annual global electricity review (see listening 1).
- The OneByte Model (1Byte), narrows the emission to a data center and network only.
How to measure
At this point the fun starts, we can measure our co2 emissions by using the co2 model, where you can use one of following methods (a summary of the most important):
- Per byte, which is taking a number for the number of bytes and a boolean if the web host is green.
- Per visit, which is having the same parameters
- Per page, which will calculate based on page level.
The SWD model will always return more emissions as it is measuring more.
For more information about how to use the library, also see the link here
By default, the SWD model is chosen when creating a co2 object. Underwater you will see something like the following code:
if (options?.model = = = "1byte") {
this.model = new OneByte();
} else if (options?.model = = = "swd") {
this.model = new SusteinableWebDesign();
} else if (options?.model) {
throw new Erros(<error_descr>);
}
As you can see you need to instantiate the model if you want to use the 1byte model. You can do this with the following code:
const oneByte = new co2({model: "1byte"})
For now, those are the only models. GreenFrame is another model under discussion.
PerByte:
As already mentioned you could use the perByte method. By using (an object's) amount of bytes you can calculate the co2 emissions in grams. An example (of 1GB of co2 emissions):
const emissions_swd_per_byte = swd.perByte(1000000000)
const emissions_1byte_per_byte = oneByte.perByte(1000000000)
console.log(emissions_swd_per_byte)
console.log(emissions_1byte_per_byte)
This will print 353.15 and 290.81. So 1GB will produce these amounts (in grams) of co2 emissions if you look at both models.
If you’re hosting on a green domain (it will be exposing less emissions), you could add a boolean at the end like:
const emissions_swd_per_byte = swd.perByte(1000000000, true)
const emissions_1byte_per_byte = oneByte.perByte(1000000000, true)
PerVisit:
This one is only available for the swd model and it also calculates the grams of CO2 based on the amount of bytes. The difference is only that it is making some extra assumptions based on visitors and caching. More information can be found here.
PerPage (required node):
It’s also possible to calculate the co2 emissions by giving a HAR file. But what is a HAR file? HAR stands for HTTP Archive Format, which contains all the browser activity within a site. You can also generate such files, for example with Google Chrome's Developer Tools (see listening 2). Just open your network tab and right-click on the call you want to inspect and save it to a HAR file.
After downloading the HAR (or creating with another framework in your code), the code would be similar to this:
const fs = require("fs");
const pagexray = require("pagexray");
const har = JSON.parse(fs.readFileSync("/path/to/my.har"));
const pages = pagexray.convert(har);
const emissions_swd_per_page = swd.perPage(page, true)
const emissions_1byte_per_page = oneByte.perPage(page, true)
For more information about creating the pagexray with npm, check the Github of sitespeed.io
This website is by the way great, it measures the performance of your website and can also measure the emissions when you enable a plugin. It uses co2.js in the background.
Besides the above methods, you can also check the emissions per domain with the perDomain
method or per ContentType with perContentType.
Statistics
You can also use the statistics from co2.js. For example, you can get the yearly average grid intensity from the Netherlands like this:
import { co2 } from 'node_modules/@tgwf/co2/src/index.js'
const { data, type, year } = averageIntensity;
const { NLD } = data;
console.log({ NLD })
This will print {NLD: 354.988}
Check green hosting
To check if your host is running on green energy you can call the check method of the hosting object which is also defined in the library. A nice website where you can also check this is websitecarbon.com
But now, back to the code:
import { hosting } from 'node_modules/@tgwf/co2/src/index.js';
hosting.check('google.nl')
This will return a Promise, the result of it can be true if your host is green!
Summary (your todo list)
Because sustainability is a relatively new topic, you can now experiment with a great library like co2.js from the Green Web Foundation to measure your CO2 coding emissions. You can measure
- your emissions based on the number of bytes with the perByte function
- your emissions based on har log file with the perPage function
- your domain with the perDomain function.
- the content type with the perContentType function
- if your hosting is green with the check function!
Examples will be added at https://github.com/KoTurk/co2-code-measurer