Add Last Updated Date to the NextJS website Automatically
Adam C. |

For a constantly changing information site, it's better to display the last updated date on the website so that the visitors can have a better sense of the age of the data. Here are two ways to do it with NextJS.

Photo by Icons8 Team on Unsplash

In getStaticProps()

getStaticProps is called once during the build to create a static page, so when we define the last updated date in this function, then it could be passed as props to display in the generated static page. For example:

export async function getStaticProps() {
  const date = new Date();
  const isoDateTime = new Date(
    date.getTime() - date.getTimezoneOffset() * 60000
  ).toISOString();
  const lastUpdated = isoDateTime.slice(0, 10);

  return {
    props: {
      lastUpdated: lastUpdated
    } // will be passed to the page component as props
  };
}

Use ENV Variable

Method one only works for static pages, for server-side rendering, it does not work, because the date will be generated when the page is rendered. So it's better if we have an environment variable, which could be used as a global variable.  We can set the variable using .env /.env.local, but it's not ideal, because we have to remember to update the date in the file before we run a build.  To make a dynamic environment variable, we can use a build script. It will be like this:

#!/bin/bash

DATE_WITH_TIME=`date "+%Y-%m-%d"`

NEXT_PUBLIC_LASTMOD=$DATE_WITH_TIME npm run build

Say we name this file: rebuild-with-ts.sh, so instead of running npm run build, we can run sh rebuild-with-ts.sh. After that, we can use the process.env.NEXT_PUBLIC_LASTMOD in any component where we want to show the last build date. Is it cool?

Hope this helps.