Tuesday Tips

JamstackJavaScript

A very common blog logic is displaying posts or events on your website based on the date. We may want to not show a post if it is in the future or change how a past event is displayed. When looking at a Jamstack website this can be confusing as there are several places in the build lifecycle that this logic can occur. And each occurence comes with its own limitations.

Write the HTML

The first option is to hardcode the elements by physically adding or modifying them in the HTML files. This is the most reliable as it happens before the website is built. However, this is also less than optimal: who wants to change their website manually every time a post needs to be published or an event passes?

Structured Data with Logic at Build

The second option is to write structured data and do the logic at build time. Using a headless CMS or other ways to store data files, such as Markdown, we can utilize a static site generator to build our website. The generator would then use logic during the build process to display what we want. So, we could use conditional logic to say if the post is in the future do not display it or if the event has passed use the grayed out styles.

The issue with this process is that once the website is built it will not change until the next build. So, if we build the website today and have an event tomorrow, our website on the following day would still have it as an upcoming event. We could solve this issue by automating our build process every day or even every hour.

Logic at the Edge

A less readily available option would be to do the logic with edge workers that would execute on a CDN request. The render function for our website would then update the website files every time a user requests it. This feature is still in the works but the ideal end goal is that it would perform nearly as well as a static site but allow for updates on each request.

Logic at Run Time

The last option is to pass data to the front end and then execute the logic. For example, we might use an HTML data attribute for our event or post. Then, using this attribute, we could conditionally style the event using front-end JavaScript. This would not require a new build but could seem a bit clunky on the code side. However, if the performance is not affected and your user experience is working well then this might not be an issue.

In the end, it all comes down to the data you are trying to display, when it needs to be updated and how much manual work you are willing to put in each time.

Credit

Today’s Tuesday Tips was adapted from a post on CSS-Tricks.