Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ReferenceError: document is not defined. Server Side rendering does not seem to work. #6

Open
insipidish opened this issue Sep 16, 2016 · 2 comments · May be fixed by #22
Open

ReferenceError: document is not defined. Server Side rendering does not seem to work. #6

insipidish opened this issue Sep 16, 2016 · 2 comments · May be fixed by #22

Comments

@insipidish
Copy link

Hi

I am trying to use the Markup component while rendering server side with preact-render-to-string.
I get the following error: 'ReferenceError: document is not defined'

Could you suggest a work around?

@developit
Copy link
Owner

Ah yeah that's a good point. This uses the browser's built-in DOM parser, which isn't available under node. Should be possible to detect node and require() in a simple parser lib though! Will need to update the code :)

te-online added a commit to te-online/preact-markup that referenced this issue Apr 13, 2018
@danielweck
Copy link

danielweck commented Mar 30, 2021

Preact WMR injects a NodeJS DOMParser for static SSR (aka "prerender"):

globalThis.DOMParser = new (require('jsdom').JSDOM)('').window.DOMParser;

https://github.com/preactjs/wmr/blob/7077053172e4ef347397cdde375c806ab8f32d8e/docs/public/prerender.js#L6-L12

(PR context: https://github.com/preactjs/wmr/pull/497/files )

This way, this never fails:

try {
doc = new DOMParser().parseFromString(wrappedMarkup, mime);
} catch (err) {
parserError = err;
}

...and this iframe-based fallback never gets called in the html case:

function buildParserFrame() {
if (document.implementation && document.implementation.createHTMLDocument) {
return document.implementation.createHTMLDocument('');
}
let frame = document.createElement('iframe');
frame.style.cssText = 'position:absolute; left:0; top:-999em; width:1px; height:1px; overflow:hidden;';
frame.setAttribute('sandbox', 'allow-forms');
document.body.appendChild(frame);
return frame.contentWindow.document;
}

Related PRs:

#24

#22

#40

#18

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants