How to Check If Your Astro App (or Vite) is Running in a Browser

This article was published on Nov 15, 2023, and takes less than a minute to read.

While coding an Astro application, I wondered how I could check whether the code was running on the Browser.

Astro runs Vite under the hood, and on Vite land, we have an easy way of doing that:

const isBrowser = import.meta.env.SSR === false

if(isBrowser){
  // browser code
}

This is handy because even when building a static site, Vite will pre-process code on the server side, meaning that if we check window or document, it will throw an error.