Skip to content

Commit

Permalink
fix(components): use typeof document (remix-run#2025)
Browse files Browse the repository at this point in the history
  • Loading branch information
kentcdodds authored Feb 18, 2022
1 parent 2612b4c commit c1adcc6
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 5 deletions.
24 changes: 24 additions & 0 deletions docs/pages/gotchas.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,4 +92,28 @@ You may ask why we don't just bundle everything for the server. We could, but th

With major deployment platforms now supporting ESM server side, we're confident the future is brighter than the past here. We're still working on a solid dev experience for ESM server builds, our current approach relies on some things that you can't do in ESM. We'll get there.

## `typeof window` checks

Because the same JavaScript code can run in the browser as well as the server, sometimes you need to have a part of your code that only runs in one context or the other:

```ts bad
if (typeof window === "undefined") {
// running in a server environment
} else {
// running in a browser environment
}
```

This works fine in a Node.js environment, however, Deno actually supports `window`! So if you really want to check whether you're running in the browser, it's better to check for `document` instead:

```ts good
if (typeof document === "undefined") {
// running in a server environment
} else {
// running in a browser environment
}
```

This will work for all JS environments (Node.js, Deno, Workers, etc.).

[esbuild]: https://esbuild.github.io/
7 changes: 3 additions & 4 deletions examples/pm-app/app/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,14 @@ export function getUserFromDisplayName<
}

export const canUseDOM: boolean = !!(
typeof window !== "undefined" &&
typeof window.document !== "undefined" &&
typeof window.document.createElement !== "undefined"
typeof document !== "undefined" &&
typeof document.createElement !== "undefined"
);

export function getClientSafeEnvVariable<
K extends keyof RemoveIndex<Exclude<Window["ENV"], undefined>>
>(key: K): Exclude<Window["ENV"], undefined>[K] {
if (typeof window !== "undefined") {
if (typeof document !== "undefined") {
try {
const ENV = window.ENV;
if (!ENV) {
Expand Down
2 changes: 1 addition & 1 deletion packages/remix-react/components.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1132,7 +1132,7 @@ export function useSubmitImpl(key?: string): SubmitFunction {
}
}

if (typeof window === "undefined") {
if (typeof document === "undefined") {
throw new Error(
"You are calling submit during the server render. " +
"Try calling submit within a `useEffect` or callback instead."
Expand Down

0 comments on commit c1adcc6

Please sign in to comment.