Grid-aware Websites - Netlify Edge Plugin
This plugin provides some useful functions that can be used when setting up the @greenweb/grid-aware websites
library using Netlify Edge Functions.
After you have installed the @greenweb/grid-aware-websites
package (see steps), you can use this plugin to:
- Fetch the location of a user that is exposed by the Netlify Edge platform.
Fetching request country (getLocation()
)
The code below is a simplified demonstation of how to use this plugin to fetch the request location, and then use it with the gridAwarePower
function.
The code below shows the
import { getLocation } from "https://esm.sh/@greenweb/gaw-plugin-netlify-edge@latest";
export default async (request, context) => {
const location = getLocation(context);
if (location.status === "error") {
return new Response('There was an error');
}
const { country } = location;
return new Response(`The country is ${country}.`)
}
Fetch request latlon
By default, the getLocation()
function returns the geo.country.code
value. However, it can also be used to return the geo.latitude
and geo.longitude
values if desired.
import { getLocation } from "https://esm.sh/@greenweb/gaw-plugin-netlify-edge@latest";
export default async (request, context) => {
const location = getLocation(context, {
mode: "latlon"
});
if (location.status === "error") {
return new Response('There was an error');
}
const { lat, lon } = location;
return new Response(`The country is ${JSON.stringify({lat, lon})}.`)
}
[!NOTE]
Using latitude and longitude values is not yet supported in the @greenweb/grid-aware-websites
package.
Using this with the Grid-aware Websites library
The code below shows a simple implementation of this plugin alongside the Grid-aware Websites core library in a Netlify Edge Function.
import { gridAwarePower } from "https://esm.sh/@greenweb/grid-aware-websites@latest";
import { getLocation } from "https://esm.sh/@greenweb/gaw-plugin-netlify-edge@latest";
const apiKey = "you_api_key";
export default async (request, context) => {
const location = getLocation(context);
if (location.status === "error") {
return new Response('There was an error');
}
const { country } = location;
const gridData = await gridAwarePower(country, apiKey);
if (gridData.status === "error") {
return new Response('There was an error')
}
return new Response(gridData)
}