This plugin provides useful helper functions that can be used when setting up the @greenweb/grid-aware websites
library using Cloudflare Workers.
After you have installed the @greenweb/grid-aware-websites
package (see steps), you can use this plugin to:
In your Cloudflare Workers project, install this plugin by running the following command:
npm install @greenweb/gaw-plugin-cloudflare-workers
You can use this plugin to fetch the country of a website visitor. This information can then be passed into the @greenweb/grid-aware-websites
library to enable it to retrieve data about the user's energy grid and make a determination if grid-aware website changes should be applied.
Import the library into your Cloudflare Workers code, and the use the getLocation
function to retrieve a users country based on the Cloudflare request object.
import { getLocation } from "@greenweb/gaw-plugin-cloudflare-workers";
export default {
async fetch(request, env, ctx) {
// Use the getLocation function to check for the user's country in the request object
const location = getLocation(request);
// If there's an error, process the request as normal
if (location.status === "error") {
return new Response('There was an error');
}
// Otherwise we can get the "country" variable
const { country } = location;
return new Response(`The country is ${country}.`)
},
};
The code below shows a simple implementation of this plugin alongside the Grid-aware Websites core library in a Cloudflare Worker.
import { gridAwarePower } from "@greenweb/grid-aware-websites";
import { getLocation } from "@greenweb/gaw-plugin-cloudflare-workers";
const apiKey = "you_api_key"; // Set your own Electricity Maps API key here.
export default {
async fetch(request, env, ctx) {
// Use the getLocation function to check for the user's country in the request object
const location = getLocation(request);
// If there's an error, return a message
if (location.status === "error") {
const response = await fetch(request.url);
return new Response('There was an error');
}
// Otherwise we can get the "country" variable
const { country } = location;
// Use the Grid-aware Websites library to fetch data for Taiwan, and check if grid-aware website changes should be applied.
const gridData = await gridAwarePower(country, apiKey);
// If we get an error, we can check for that and return nothing.
if (gridData.status === "error") {
return new Response('There was an error')
}
// If we've got data back using the Grid-aware Websites library, let's return that to the browser
return new Response(gridData)
},
};
Below are some examples of the Grid-aware Websites library and Cloudflare Workers plugin being used.