Skip to content

Run client-side JS in Astro MDX

I wanted to add some bits of client-side JS in a .mdx file in Astro.

Just a one-liner to redirect after 2 seconds, nothing too crazy:

setTimeout(() => (location.href = '/'), 2000)

In a .astro component I’d normally use:

<script>
  setTimeout(() => (location.href = '/'), 2000)
</script>

but this didn’t work because in the browser what we get is (due to MDX compiler, escaping, etc):

<script><p>setTimeout(() =&gt; (location.href = ’/’), 2000)</p></script>

I ended up using this syntax:

<script>{`
  setTimeout(() => (location.href = '/'), 2000)
`}</script>

and this worked fine.


I wrote 21 books to help you become a better developer:

  • HTML Handbook
  • Next.js Pages Router Handbook
  • Alpine.js Handbook
  • HTMX Handbook
  • TypeScript Handbook
  • React Handbook
  • SQL Handbook
  • Git Cheat Sheet
  • Laravel Handbook
  • Express Handbook
  • Swift Handbook
  • Go Handbook
  • PHP Handbook
  • Python Handbook
  • Linux Commands Handbook
  • C Handbook
  • JavaScript Handbook
  • Svelte Handbook
  • CSS Handbook
  • Node.js Handbook
  • Vue Handbook
...download them all now!

Related posts that talk about astro: