Skip to content

Dynamic footer date for static websites

Astro ^4.0.0

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).

Server side date: the issue

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

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.

    <script is:inline>
    document.getElementById("footer-year").innerText = new Date().getFullYear();
    </script>

Full code

---
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>