Add test for React SSR + window (#581)

* Add test for React SSR + window

* Add helpful error message on window undefined in SSR

Fixes #551
This commit is contained in:
Drew Powers 2021-06-29 19:37:50 -06:00 committed by GitHub
parent 44355d4ca9
commit d1785d80c3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 45 additions and 1 deletions

View file

@ -48,7 +48,12 @@ type LoadResultSuccess = {
};
type LoadResultNotFound = { statusCode: 404; error: Error; collectionInfo?: CollectionInfo };
type LoadResultRedirect = { statusCode: 301 | 302; location: string; collectionInfo?: CollectionInfo };
type LoadResultError = { statusCode: 500 } & ({ type: 'parse-error'; error: CompileError } | { type: 'not-found'; error: CompileError } | { type: 'unknown'; error: Error });
type LoadResultError = { statusCode: 500 } & (
| { type: 'parse-error'; error: CompileError }
| { type: 'ssr'; error: Error }
| { type: 'not-found'; error: CompileError }
| { type: 'unknown'; error: Error }
);
export type LoadResult = (LoadResultSuccess | LoadResultNotFound | LoadResultRedirect | LoadResultError) & { collectionInfo?: CollectionInfo };
@ -250,6 +255,19 @@ async function load(config: RuntimeConfig, rawPathname: string | undefined): Pro
};
}
if (err instanceof ReferenceError && err.toString().includes('window is not defined')) {
return {
statusCode: 500,
type: 'ssr',
error: new Error(
`[${reqPath}]
The window object is not available during server-side rendering (SSR).
Try using \`import.meta.env.SSR\` to write SSR-friendly code.
https://github.com/snowpackjs/astro/blob/main/docs/reference/api-reference.md#importmeta`
),
};
}
if (err instanceof NotFoundError && rawPathname) {
const fileMatch = err.toString().match(/\(([^\)]+)\)/);
const missingFile: string | undefined = (fileMatch && fileMatch[1].replace(/^\/_astro/, '').replace(/\.proxy\.js$/, '')) || undefined;

View file

@ -0,0 +1,7 @@
import React from 'react';
function GetSearch() {
return (<div>{window.location.search}</div>);
}
export default GetSearch

View file

@ -0,0 +1,8 @@
---
import GetSearch from '../components/GetSearch.jsx';
---
<html>
<body>
<GetSearch />
</body>
</html>

View file

@ -42,6 +42,17 @@ React('Can load React', async () => {
assert.equal($('#arrow-fn-component').length, 1, 'Can use function components');
});
React('Throws helpful error message on window SSR', async () => {
const result = await runtime.load('/window');
assert.match(
result.error.toString('utf8'),
`[/window]
The window object is not available during server-side rendering (SSR).
Try using \`import.meta.env.SSR\` to write SSR-friendly code.
https://github.com/snowpackjs/astro/blob/main/docs/reference/api-reference.md#importmeta`
);
});
React('Can load Vue', async () => {
const result = await runtime.load('/');
if (result.error) throw new Error(result.error);