skip to content

Scheduled Article Publishing in Astro with Cloudflare Pages

/ 3 min read

Astro, a powerful framework for building modern websites, offers efficient static build capabilities. In collaboration with Cloudflare Pages, it provides a robust hosting solution. An intriguing feature I wanted to implement on my blog (hosted on Cloudflare Pages and built with Astro) was scheduled article publishing. This feature allows articles to be automatically published when the current date matches their predefined publication date.

Strategy for Scheduled Publishing

To achieve scheduled article publishing, I employed a two-step approach:

1. Adding publishDate Metadata to Content Collection

Firstly, I added a publishDate metadata field to the content collection. This date determines when an article should be published. By checking if this date matches the current date, the system decides whether to publish the post. Astro’s documentation on content collections and handling dates was instrumental in implementing this.

2. Modifying the Build Script for Date Comparison

Secondly, I modified the build script to include a function that compares the publishDate with the build date. This function filters out any posts that are marked as drafts or have a future publish date. The TypeScript code snippet below illustrates this process:

/** Filters out draft posts based on the environment and the post's publishDate **/
export async function getAllPosts() {
 return await getCollection("post", ({ data }) => {
  const isNotDraft = import.meta.env.PROD ? data.draft !== true : true;
  // Treat posts with a future publishDate as drafts
  const isNotFuture = import.meta.env.PROD
   ? data.publishDate.valueOf() <= new Date().valueOf()
   : true;

  return isNotDraft && isNotFuture;

Automating Deployment with Cloudflare Pages and GitHub Actions

To ensure that this scheduled publishing mechanism works effectively, I automated the build and deployment process of the site. Cloudflare Pages offers a feature called Deploy Webhook, which triggers the build and deployment of pages when it receives a POST request. I utilized GitHub Actions to send this POST request to the Deploy Webhook daily. Below is an example YAML configuration for the GitHub Actions workflow:

# Only articles with a past or present publishDate are displayed in the Astro build
# Thus, we perform a daily deployment with a date condition check

name: "Daily Deploy"

  # daily at 00:00 UTC
    - cron: "0 0 * * *"
  # for debugging purposes

  # Trigger deploy webhook with curl
    runs-on: ubuntu-latest
      - name: Deploy
        run: curl -X POST -d {} ${{ secrets.CLOUDFLARE_DEPLOY_WEBHOOK }}

This setup guarantees that the website is rebuilt daily, ensuring that any article with the current date as its publishDate gets published automatically. This approach leverages the static build performance of Astro while introducing dynamic elements like scheduled publishing, making the blog more efficient.