diff --git a/.vscode/settings.json b/.vscode/settings.json index 1fb8e806..dd9c9647 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -16,5 +16,8 @@ }, "[javascript]": { "editor.defaultFormatter": "denoland.vscode-deno" + }, + "[markdown]": { + "editor.defaultFormatter": "denoland.vscode-deno" } } diff --git a/docs/latest/concepts/islands.md b/docs/latest/concepts/islands.md index c51a8ffa..3bd3d0c5 100644 --- a/docs/latest/concepts/islands.md +++ b/docs/latest/concepts/islands.md @@ -4,8 +4,9 @@ description: | --- Islands enable client side interactivity in Fresh. Islands are isolated Preact -components that are rendered on the client. This is different from all other -components in Fresh, as they are usually just rendered on the server. +components that are rendered on the server and then hydrated on the client. This +is different from all other components in Fresh, as they are usually rendered on +the server only. Islands are defined by creating a file in the `islands/` folder in a Fresh project. The name of this file must be a PascalCase or kebab-case name of the @@ -168,3 +169,31 @@ export default function Home() { ); } ``` + +## Rendering islands on client only + +When using client-only APIs, like `EventSource` or `navigator.getUserMedia`, +this component will not run on the server as it will produce an error like: + +``` +An error occurred during route handling or page rendering. ReferenceError: EventSource is not defined + at Object.MyIsland (file:///Users/someuser/fresh-project/islandsmy-island.tsx:6:18) + at m (https://esm.sh/v129/preact-render-to-string@6.2.0/X-ZS8q/denonext/preact-render-to-string.mjs:2:2602) + at m (https://esm.sh/v129/preact-render-to-string@6.2.0/X-ZS8q/denonext/preact-render-to-string.mjs:2:2113) + .... +``` + +Use the `IS_BROWSER` flag as a guard to fix the issue: + +```tsx islands/my-island.tsx +import { IS_BROWSER } from "$fresh/runtime.ts"; + +export function MyIsland() { + // Return any prerenderable JSX here which makes sense for your island + if (!IS_BROWSER) return
; + + // All the code which must run in the browser comes here! + // Like: EventSource, navigator.getUserMedia, etc. + return
; +} +```