Skip to content

Dynamic footer date for static websites

Widely compatibleRendering:Prerendered: RecommendedOn-demand: WorksAstro>=4.0.0

Works across all listed Astro environments.

  • Prerendered: Avoids stale build-time copyright years on statically generated pages while keeping a fallback for browsers without JavaScript.
  • On-demand: Works, though unnecessary on server-rendered routes because new Date().getFullYear() already runs on every request.

Having a copyright notice with the current year such as © 2024 - All rights reserved is a common need (although it doesn’t legally enforce anything).

src/components/Footer.astro
---
const year = new Date().getFullYear()
---
<footer>
<p>&copy; {year} - All rights reserved</p>
</footer>

However it will only display the year when the website was last built! It will only update next time you rebuild your site.

The solution is to use client-side JavaScript to get the current year when the page loads.

  1. We prepare a date fallback at build time. If the user’s browser can’t run JavaScript, we need to show the last known date.

    ---
    const year = new Date().getFullYear()
    ---
  2. We write the markup. We have a span with an id of footer-year so that it can be referenced from our script. It has a default value of the fallback date of step 1.

    <footer>
    <p>&copy; <span id="footer-year">{year}</span> - All rights reserved</p>
    </footer>
  3. In our script we can get the <span> element by its id and update its content to the current year. The code differs depending on your Astro version, and whether you’re using View Transitions (<ClientRouter /> in Astro 5+).

    <script is:inline>
    document.getElementById("footer-year").innerText = new Date().getFullYear();
    </script>
---
const year = new Date().getFullYear()
---
<footer>
<p>&copy; <span id="footer-year">{year}</span> - All rights reserved</p>
</footer>
<script is:inline>
document.getElementById("footer-year").innerText = new Date().getFullYear();
</script>

Compatibility

EnvironmentSupportVersion
Framework
AstroWorks>=4.0.0
RenderingAstro docs
PrerenderedRecommended[1]Any version
On-demandWorks[2]Any version

Notes

  1. Prerendered: Avoids stale build-time copyright years on statically generated pages while keeping a fallback for browsers without JavaScript.
  2. On-demand: Works, though unnecessary on server-rendered routes because new Date().getFullYear() already runs on every request.
Compatibility legend:Recommended — Best practiceWorks — SupportedDoesn't work — Unsupported