Include content into templates at The Edge
The ability to transform the content of an HTTP response with Edge Functions enables you to substitute content into templates as you would with Edge Includes.
In this example, we look for an {{INCLUDE_PRICE_INFO}}
placeholder in our response, and replace it with some other content.
import { Context } from "netlify:edge";
export default async (request: Request, context: Context) => {
// Just return what was requested without transforming it,
// unless we fnd the query parameter for this demo
const url = new URL(request.url);
if (url.searchParams.get("include") !== "pricing") {
return;
}
console.log("Including pricing content into the page");
// Get the page content
const response = await context.next();
const page = await response.text();
// Search for the placeholder
const regex = /{{INCLUDE_PRICE_INFO}}/i;
// Replace the content
const pricingContent = "It's expensive, but buy it anyway.";
const updatedPage = page.replace(regex, pricingContent);
return new Response(updatedPage, response);
};
This include Edge Function is set up to run using the include=pricing
query parameter on any URL, using this entry in the netlify.toml file:
[[edge_functions]]
function = "include"
path = "/*"
See this in action
What are Edge Functions?
Using JavaScript and TypeScript, Netlify Edge Functions give you the power to modify network requests to localize content, serve relevant ads, authenticate visitors, A/B test content, and much more! And this all happens at the Edge — directly from the worldwide location closest to each user.
To use Edge Functions on Netlify, add JavaScript or TypeScript files to an edge-functions directory in your project, and add [[edge_functions]]
entries to your netlify.toml file.
Deploy this site to Netlify
Try out Edge Functions on Netlify today! Click the button below to deploy this site with all of its demos to your Netlify account.
Deploy to Netlify