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
---const year = new Date().getFullYear()---
<footer> <p>© {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.
-
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()--- -
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>© <span id="footer-year">{year}</span> - All rights reserved</p></footer> -
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><script is:inline>const handleFooterDate = () => {document.getElementById("footer-year").innerText = new Date().getFullYear();};handleFooterDate();document.addEventListener("astro:after-swap", () => handleFooterDate());</script><script is:inline data-astro-rerun>document.getElementById("footer-year").innerText = new Date().getFullYear();</script>
Full code
---const year = new Date().getFullYear()---
<footer> <p>© <span id="footer-year">{year}</span> - All rights reserved</p></footer>
<script is:inline> document.getElementById("footer-year").innerText = new Date().getFullYear();</script>
---const year = new Date().getFullYear()---
<footer> <p>© <span id="footer-year">{year}</span> - All rights reserved</p></footer>
<script is:inline> const handleFooterDate = () => { document.getElementById("footer-year").innerText = new Date().getFullYear(); };
handleFooterDate(); document.addEventListener("astro:after-swap", () => handleFooterDate());</script>
---const year = new Date().getFullYear()---
<footer> <p>© <span id="footer-year">{year}</span> - All rights reserved</p></footer>
<script is:inline data-astro-rerun> document.getElementById("footer-year").innerText = new Date().getFullYear();</script>