Implementing Link Previews with Cloudflare Pages & Functions

Background

How do link previews work?

Examples of Formfunction link previews on various platforms.

Cloudflare Pages, SPAs, and Client-side Rendering

Unlike traditional web apps, SPAs often serve the same HTML for all requests

Guide

Simplified overview of what we’ll be setting up

Step 1: Set up Functions

  1. Create a /functions directory at the root of your Cloudflare Pages project.
  2. For the purpose of this guide, we want our Function to match all URLs so we’ll create a file called [[index]].ts in the /functions directory we just created. (Please refer to the documentation for more advanced routing)
  3. Paste the following code into [[index]].ts
  • NOTE: you can install @cloudflare/workers-types as a dev dependency to get relevant types installed in your dev environment
# Install Wrangler
npm install wrangler@beta
# Run Functions locally using Wrangler
npx wrangler pages dev -- npx react-scripts start

Step 2: Implement a custom ElementHandler

Step 3: Set up API to fetch preview data

  • URL
  • Type (will be ”website” in this case)
  • Title
  • Description
  • Image
{
"image": "<asset URL>",
"username": "<username>"
}

Step 4: Wire everything up

  • We fetch the data from our backend by making a GET request to <API_URL>
  • We feed the data in to MetaTagInjector which now accepts MetaTagInjectorInput (in this case, the data has the same shape as what is returned from our example API)
  • MetaTagInjector populates the <meta> tags with the data, and appends <meta> tags to the <head> element
  • We return the transformed HTML to the client

Step 5: Productionize

  • Route matching — in our example, we’re calling the API for every request which can be expensive. For production use, you’ll likely want to conditionally call the appropriate API based on the request URL (in request.url). For example, we use a Regex pattern to see if a URL is requesting a user profile before trying to fetch the image and username.
  • Error handling & safe defaults — your API request might fail so it’s important that your Functions code can fallback to a set of safe default values.
  • Cache the API data — the API data fetch can add significant time to your overall request roundtrip time. In most cases, the data being fetched will not be changing frequently so making use of caching with a reasonable TTL will drastically improve performance of this method. Try making use of Cloudflare’s KV binding to cache your fetched data between requests!

Step 6: Deploy

Gotchas

  • Beta — as noted above, Cloudflare Functions are still in beta so please keep that in mind when choosing this setup for your production use-case. Be sure to consult the documentation or the Cloudflare Discord if you need assistance!
  • Invocation limit — Cloudflare Functions currently has a 400,000 daily invocation limit that can only be changed via requesting an increase. Once a Function reaches this limit, it will simply stop running and fallback to serving static assets. See the docs for more info.
  • Computation limit — there is a (unstated?) computation limit of 50ms and any Function invocation that exceeds the 50ms of processing time will result in an error. It is worth noting that async operations like I/O or network requests do not count towards this processing time limit! In our case, we ran into this due to a bug in one of our Regexes that caused our processing time to exceed the 50ms limit.

Final Thoughts

--

--

--

The 1/1 Solana NFT marketplace, designed for independent creators.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to Create a Fuzzy Search in React JS Using Fuse.JS

How to build Phone Number-Based Authentication with React, Altogic and Twilio

TextFormField with ReactJS

How to limit the number of components in Container Components?

Compiling and bundling TypeScript libraries with Webpack

CRUD Application in React.js with Redux and Hooks.

Creating Type-safe JSON in Swift

Make Use Of Reduce

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Formfunction Engineering

Formfunction Engineering

The 1/1 Solana NFT marketplace, designed for independent creators.

More from Medium

ESlint Shareable configs for Vue

How to build a custom Range input with Svelte

How To Display TwicPics Images When Working Offline With Nuxt.js

Dynamic SVG components for vue3

An image of javascript code making use of the component we plan to use in this tutorial.