Skip to content
Go back

Automating 'Last Updated' Dates in Next.js with Node's fs Module

Updated: (Originally published 16 Sep, 2025 )

Keeping timestamps accurate on blog posts, documentation, or static pages can be a surprisingly tedious task. It’s easy to forget to update a “Last Updated” line when publishing new content. That’s where a little automation can save you from human error.

Recently, I solved this in a Next.js project by pulling the file’s modified date directly from the filesystem using Node’s built-in fs module. In this scenario, it was important for one particular file to have the “date published” match the date the change is made/goes live - which in my case is usually the same day it’s handed to me.

The Helper Function

Here’s the utility function I wrote:

// eslint-disable-next-line @typescript-eslint/no-var-requires
const fs = require('fs');
function getFileTimestamp(filePath) {
try {
const stats = fs.statSync(filePath);
const mtime = stats.mtime;
return mtime.toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
});
} catch (error) {
// eslint-disable-next-line no-console
console.error('Error getting file timestamp:', error);
return null;
}
}
module.exports = { getFileTimestamp };

Note: This embedded Gist contains the most up-to-date version of the script, which may differ slightly from the explanation.

This does one thing: given a file path, it looks up the file’s metadata and returns the last modified date in a nicely formatted string, like September 17, 2025.

If the file doesn’t exist or there’s some other issue, it catches the error and returns null.

Plugging Into Next.js

Next.js makes it easy to expose environment variables at build time. In next.config.js, I called the function and set the result as an environment variable:

const { getFileTimestamp } = require("./getFileTimestamp");

const filePath = "./content/my-doc.md"; // wherever your source file lives

const nextConfig = {
    env: {
        FILE_TIMESTAMP: getFileTimestamp(filePath),
    },
};

module.exports = nextConfig;

Now, the FILE_TIMESTAMP is baked into the build and available throughout the app.

Using It in a Page

On any page, you can grab the environment variable:

const fileTimestamp = process.env.FILE_TIMESTAMP;

And render it in your template:

<p>Last Updated: {fileTimestamp}</p>

That’s it — your page will always show the true last modified date of the source file without you lifting a finger.

Why This Matters

For documentation sites, blogs, or anything where freshness matters, this small utility goes a long way.

Improvement Ideas

This simple utility works great as-is for my specific use-case, but there are a few ways to extend or refine it:

A small script like this can scale nicely depending on your project’s needs.


Share this post on:

Previous Post
Docker Override – Extending Your Docker Compose
Next Post
What is Testivus' wisdom concerning the proper percentage of test coverage?