Using amp-list to Add Random Related Article Suggestions to a Next.js Static Site
TL;DR
I wanted to add random related articles at the bottom of blog posts, which is a common blog feature, but I wasn't sure how to do it on a static site. One approach would be to call ServersideProps every time, but I got confused about how to combine that with getStaticsProps. I didn't want to do server-side rendering every time since it would make things slower...
So the approach I took was to first implement an API in Next.js, then use amp-list to fetch from it and render the results.
amp-list and amp-mustache
amp-list is an AMP extension component that dynamically fetches data from a JSON endpoint and renders it using amp-mustache templates.
Here's an example from the official documentation (amp-list, amp-mustache):
The JSON being used:
Basically, you specify the layout and endpoint within <amp-list>, and define how to render inside <template type="amp-mustache">.
With amp-mustache, you can use variables as follows:
- Simple variables
{{variableName}}
- Render if variable exists
{{#section}}{{/section}}
- Render if variable does not exist
{{^section}}{{/section}}
Templates in JSX
Within JSX, these templates can be used like this:
Implementation Plan
Based on the above, I'll create an endpoint like /api/otherarticles that returns something like:
Then the amp-list implementation would look like:
API Implementation
In Next.js, you can create API endpoints by placing ts or other files under pages/api/.
pages/api/otherarticles.js
In the actual implementation, I create a cache similar to Adding Search Functionality to My Next.js Blog and then retrieve a specified number of files from a random array referencing that cache. The implementation for this blog can be found on GitHub.