Skip to main content

Command Palette

Search for a command to run...

Pass Astro server data to the client

Updated
1 min read
J

Frontend engineer

The Astro docs provide an example for passing server data to the client. That’s not quite as robust as what I wanted for my requirements, so here’s a slightly different approach:

<!-- `account` is a variable defined in "front matter", i.e. Astro server code -->
<script data-server={JSON.stringify({account})}>
  const {account} = JSON.parse(document.currentScript.dataset.server);
  console.log(account.name);
</script>

Like Astro suggests, I set stringified data as a data-* attribute. In cases where I need to work with that data client-side outside of a component I prefer to combine the data I need into a single "server" attribute and set that on the page's script. Then I parse that one object and it’s all ready to go.