Jamstack: Javascript, APIs & Markup

This article is designed to give you a quick self-introduction containing all essential information related to Jamstack- a streamlined outlook to Frontend web development. Jamstack allows developers to quickly create and service websites. JAM is an acronym for JavaScript, APIs, and Markup. Read on to understand more about this pioneering software in modern web development.

What is Jamstack?

Jamstack is an architecture designed to make the web faster, more secure, and easier to scale. It builds on many of the tools and workflows which developers love and bring maximum productivity.

You can read much more in depth about it here.

The core principles of Jamstack are to offer better performance, higher security with cheaper and faster scaling features, while also offering a better overall developer experience. Pre-rendering and decoupling services, enabling sites and applications can be delivered with greater confidence and resilience than ever before.

Jamstack breaks down to:

  • JavaScript for dynamic functionalities.
  • API for server side operations over HTTPS with JavaScript.
  • Markup for websites are served as static HTML files. These can be generated from source files, such as Markdown, using a Static Site Generator (A static site generator is a software application that creates HTML pages from templates or components and a given content source.).

jam.png

How Jamstack works.

It can more easily be understood with the help of an example:

Let's suppose John builds a web application for weather updates. His backend application creates HTML pages that show the weather, then sends those pages to the user. However, the web application is somewhat slow. Before a user can view those pages, they have to wait for the backend application to run, the HTML to be generated and the HTML to reach their device.

John uses Jamstack to rebuild the application. He creates a series of lightweight HTML pages that the user will see when they first open up the website and, at the same time, API calls are made to get the live updates on weather and fill in the required places. Now, this makes John's website faster as it uses CDN to store the static HTML pages.

Let's see what Jamstack looks like in action. In this article, we will be using Gatsby.js as the static site generator. We will try to create a simple application. Something that gives a clear understanding of how Jamstack works using Gatsby.

Gatsby is a React-based open-source framework for creating websites and apps and uses GraphQL as the query language.

The following are the steps to use Jamstack with Gatsby.js:

  • Install gatsby-cli.

Get detailed information on how to set it up here . If you are using NPM, these are the following steps:

npm install -g gatsby-cli
npm init gatsby
cd gatsby-folder
npm run develop

Now hit the endpoint URL for the website and use http://localhost:8000/ to view the website and http://localhost:8000/___graphql to view GraphiQL in an in-browser IDE.

  • Now whatever Javascript file we create under the /pages/ folder will serve as a different API endpoint URL (http://localhost:8000/<the-name-of-file>)

  • We go through the recommended approach of creating a gatsby-config.js file, as here we can maintain all of the configurations and plugins as the development of the application proceeds.

module.exports = {
  siteMetadata: {
    title: "title-of-you-choice",
  },
  plugins: [
    ...
  ],
};

We can also query this data used in the application. For example, here we can query siteMetadata in GraphiQL using:

query TestQuery{
     site{
         siteMetadata{
                title
              }
       }
}
  • Now, we create a folder, /pages/, that will contain all the markdown files. A sample of the markdown file is titled first.md, which is as below:
---

title: First
date: 2020-09-09

---

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore 
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut 
aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse 
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in 
culpa qui officia deserunt mollit anim id est laborum.

Learn how to write a markdown file here.

  • Now, we will add the required plugins in the gatsby-config.js file:

gatsby-source-filesystem -> It is a Gatsby source plugin for sourcing data into your Gatsby application from your local filesystem and allows to read all files from any folder.

gatsby-transformer-remark -> It transforms markdown files into MarkdownRemark nodes from which you can query an HTML representation of the markdown.

module.exports = {
  siteMetadata: {
    title: "Aditya Prakash",
  },
  plugins: [
    {
      resolve: "gatsby-source-filesystem",
      options:{
        name: "data",
        path: "/Users/adityaprakash/Documents/JAM/my-gatsby-site/pages"
      },
    },
    "gatsby-transformer-remark"
  ],
};
  • Now, we need to create and update some files to create a proper workflow:

Create a gatsby-node.js file:

const { createFilePath } = require("gatsby-source-filesystem");
const path = require("path");


exports.onCreateNode = ({ node, getNode, actions}) => {
    const { createNodeField } = actions;
    if (node.internal.type === "MarkdownRemark") {
        const slug = createFilePath({node, getNode, basePath: `pages`});
        createNodeField({
            node,
            name: "slug",
            value: slug
        });
    }
};

exports.createPages = async ({graphql, actions}) => {
    const {createPage} = actions;
    const result = await graphql(`
        {
            allMarkdownRemark {
                edges{
                    node {
                        fields{
                            slug
                        }
                    }
                }
            }
        }
    `);

    result.data.allMarkdownRemark.edges.forEach(({node}) => {
        const slug = node.fields.slug
        console.log(slug)
        createPage({
            path: slug,
            component: path.resolve("./src/templates/page.js"),
            context: {
                slug: node.fields.slug
            }
        });
    });
};

This file is used to dynamically create a single HTML page for each markdown file in /pages/ folder. This is done with the help of onCreateNode, which is called when a new node is created and createPages to tell plugins to add pages.

Create a layout.js file:

import React from "react";
import {useStaticQuery, graphql} from "gatsby";

const Layout = ({children}) => {

    const data=useStaticQuery(graphql`
    query MyQuery {
        site{
          siteMetadata{
            title
          }
        }
      }      
    `);

    return(
        <>
        <header>
            <h1>{data.site.siteMetadata.title}</h1>
        </header>
        <main>{children}</main>
        </>
    );
}

export default Layout;

This file is a general layout template for the website.

Create a page.js file:

import React from "react";
import {graphql} from "gatsby";
import Layout from "../components/layout";

export const query = graphql`
    query PageQuery($slug: String!) {
        markdownRemark(fields: {slug: {eq: $slug}}) {
            frontmatter {
                date(formatString: "MMM, DD YYYY")
                title
            }
            html
        }
    }
`;

export default ({data}) => (
    <Layout>
        <h3>{data.markdownRemark.frontmatter.title}</h3>
        <span>{data.markdownRemark.frontmatter.date}</span>
        <div dangerouslySetInnerHTML={{__html: data.markdownRemark.html}}/>
    </Layout>
);

This page is used to create an output whenever endpoint URL for a single page in /pages/ folder is opened. The slug here is passed from the gatsby-node.js file.

Update the index.js file:

import * as React from "react"
import Layout from '../components/layout';
import {graphql} from "gatsby";

export const query= graphql`
query pages {
  allMarkdownRemark {
    edges {
      node {
        frontmatter {
          date(formatString: "MMM, DD YY")
          title
        }
        id
        excerpt
      }
    }
  }
}
`;

export default ({data}) => (
 <Layout>
    {data.allMarkdownRemark.edges.map(edge => {
      const {frontmatter, excerpt, id} = edge.node;

      return (
        <div key={id}>
          <h3>{frontmatter.title}</h3>
          <span>{frontmatter.date}</span>
          <div dangerouslySetInnerHTML={{__html: excerpt}}/>
        </div>
      );
    })}
  </Layout>
);

This file displays all the information for each page in /pages/ folder.

Now run:

npm run develop

The output is as follows:

The home page: Screenshot 2021-02-15 at 9.43.32 AM.png

The output for an individual markdown file:

http://localhost:8000/<fil-name>

Screenshot 2021-02-15 at 9.43.49 AM.png

Now, add another markdown file in the /pages/ folder and it will become available to the website.

Screenshot 2021-02-15 at 9.44.01 AM.png

Output of a wrong endpoint URL: Screenshot 2021-02-15 at 9.44.27 AM.png

It is helpful as it shows all the available pages that can be found.😁

Tip => Try to use GraphiQL to understand how queries used in the codes above are used.

Screenshot 2021-02-15 at 9.44.46 AM.png

Hope, this article helps you to understand the basics for Jamstack using Gatsby and how the markdown files are used. I hope this article urged you to try your hand at Jamstack and experience how it makes Frontend development simple and streamlined.

Thank you for reading.😊

Catalin Pit's photo

Great article! 👏

Matej Bošnjak's photo

Let's suppose John builds a web application for weather updates. His backend application creates HTML pages that show the weather, then sends those pages to the user. However, the web application is somewhat slow.

  • Only implies that app might be built with unstable tools, but could have good fundamentals. Furthermore server side rendering today is pretty fast, Jamstack isn't the ultimate solution, nor would be a good one for weather app :)

On the other hand static HTML pages were one among first things on the internet, and Jamstack is not really an ultimate inovation in my opinion but only a better way to implement older concept as a new product. Also, Static HTML sites can be easily built without entering into Jamstack tools.

Title might be misleading as one might expect more basic fundamentals of Jamstack, not actually diving into one of several Jamstack tools without much info, and here's why:

Jamstack allows developers to quickly create and service websites.

Not entirely true, as Jamstack is arhitecture on top of another product which one should learn first - think about inexperienced developers first. Also, any inexperienced developer who's not familiar with Jamstack wouldn't benefit much as you didn't explain your code at all.

...containing all essential information...

Well, also would disagree, based on my previous words. If you want to give essential information, it's not by diving into one of several Jamstack tools and show some unexplained code, but rather on which occasions would Jamstack arhitecture be good for a user considering all that Jamstack offers. There's pros and cons for everything. Best tool for an app/website is often not the easiest one, it takes more consideration.

Essential info would be

  • What it is more in depth
  • How it works
  • What are advantages
  • What are disadvantages
  • Then it could come your tool of choise and why (Or might keep that for another blog post)

As you stated, Gatsby is react based one. But, what is React?

Same thing you have with Next.js which is also React based. Grindsome and Nuxt.js are Vue based. There's another one called Scully, which is newer and 1.0 release was this year - Angular based, tested it, works great.

I hope this gives you idea for more and better content on this matter.

Aditya Prakash's photo

Thank you for the suggestion. I will definitely keep it in mind. Also looking for your reviews in future