Building Ecommerce and Content Sites with Astro
Jun 05, 2024

I like to say that we're performance obsessed at Perspect particularly as it relates to end-users experiencing websites hosted on Perspect. This obsession with performance led us to using Astro in other projects. But to fully utilize Astro, we needed to modify the Perspect build process a bit.   We now will provide content in the form of JSON files at the very beginning of the build process, so that you can read the files and build out the pages in Astro as you would like. No API call or other fetch mechanism is required. Simply read a file from the file system, parse it as JSON and then use the data.   You can use the files to build out a content site with pages and posts, or perhaps build out an ultra-fast ecommerce site using the product-oriented data model.   Here's a simple example:  

import fs from 'fs';
import path from 'path';

// Function to load posts from the JSON file
export function loadPosts() {
  const postsPath = path.join(process.cwd(), 'perspect.posts.json');

  try {
    const postsData = fs.readFileSync(postsPath, 'utf-8');
    const postDataJson = JSON.parse(postsData);
    return postDataJson.posts;
  } catch (error) {
    console.error('No file called posts.json');
    return []; // Return an empty array as a fallback
  }
}

  This function attempts to read a JSON file containing posts, parse its contents, and return the posts data. If the file is not found or an error occurs during reading or parsing, it logs an error and returns an empty array as a fallback. Let me know if you need any further assistance!    In this example, we're reading perspect.posts.json from the file system by calling the loadPosts() function. Here's an explanation of all the possible content you could read from the file system during the build process:

  • perspect.posts.json: An array of blog posts, ordered by date
  • perspect.pages.json: An array of pages, un-ordered
  • perspect.product_categories.json: An array of product categories, each of which contains an array of products
  • perspect.stripe_data.json: An object containing Stripe publishable test key, live key and account id

We, of course, have this data persisted in databases on the server, but the files used during the build process are not persisted beyond the build step unless you take actions to do so. The files are added during the build process and then deleted afterwards.