Skip to content

Run client-side JS in Astro MDX

New Courses Coming Soon

Join the waiting lists

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:

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

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:

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

and this worked fine.

→ Read my Astro Tutorial on The Valley of Code

Here is how can I help you: