Content: Run client-side JS in Astro MDX

Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026

The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.


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.

Lessons in this unit:

0: Introduction
1: Markdown in Astro
2: Images
3: Content collections
4: Embed images in markdown without relative path
5: ▶︎ Run client-side JS in Astro MDX