Skip to content

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

Open

Description

@insipidish

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?

Activity

  1. developit commented on Sep 16, 2016

    @developit
    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 :)

  2. added a commit that references this issue on Apr 13, 2018
    2126bfd
  3. danielweck commented on Mar 30, 2021

    @danielweck

    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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions