1

How to detect if astro rendering happens in browser or on the server side?

Found no info in official reference and troubleshooting guide.

The only 'advice' I found is to use 'client:only'.

UPDATE Solution found


    export const isCLientSide = typeof window !== 'undefined'

Dmitry Kaigorodov
  • 1,512
  • 18
  • 27

2 Answers2

1

You can check for the window object using globalThis. If window is present, you are on the client.

if (globalThis.window) {
    console.log('Hello client-side!')
}

if (!globalThis.window) {
    console.log('Hello server-side!')
}
The Otterlord
  • 1,680
  • 10
  • 20
0

You can check if the code is running on the server by using import.meta.env.SSR provided by Vite.

if (import.meta.env.SSR) {
  // The app is running on the server.
} else {
  // Running in the browser.
}

For example for a code that uses the window object and should only run on the client:

function clientCode() {
  if (import.meta.env.SSR) return;

  // Run client code.
  window.alert('...');
}
Pierre
  • 12,468
  • 6
  • 44
  • 63