Getting production issue! ReferenceError self is not defined

this has worked till now…

do you populate the server components as well now?

… or is there an argument to read server-code?

curious how / when does this data get fetched?

const pageData = (/* SIPSBY JSON TEMPLATE BEGIN *//* SIPSBY JSON TEMPLATE END */);

I subtstitute it into the page when rendering. I just paste the JSON straight in there

(the backend pastes it in) …

I’ll show you the code in a sec

injectConfigs = {
   'html': {'regex': r'<!-- SIPSBY HTML TEMPLATE BEGIN -->.*<!-- SIPSBY HTML TEMPLATE END -->'},
   'json': {'regex': r'/\* SIPSBY JSON TEMPLATE BEGIN \*/.*/\* SIPSBY JSON TEMPLATE END \*/'},
}

injectConfig = self.injectConfigs[options.get('inject', 'html')]
regex = re.compile(injectConfig['regex'], re.MULTILINE | re.DOTALL) #TODO: Optimize by caching. Can remove regex completely


#Merge in our HTML content (which is also in template format). Using function form
#of sub for content to prevent sub from processing escapes in content
return regex.sub(lambda m: content, baseTemplate)

for this case we are using the ‘json’ config

content here should be the plasmic JSON, and baseTemplate the file you saw earlier.

maybe TMI, but after this, I am passing this all to a javascript server that renders the code (the above is python)…

Part of the render-code:

/**
 * Copyright (C) 2017-2022 Sips by - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 * ~
 **/
import { ApolloProvider, ApolloClient, gql }from '@apollo/client';
import ReactDOMServer from 'react-dom/server';
import React from 'react';
import requireFromString from 'require-from-string';
import { transformSync } from '@babel/core';
import { ServerStyleSheets } from '@mui/styles/';


import LRU from 'lru-cache';
import stringHash from 'string-hash';

const COMPONENT_DIR = process.env.JSXSERVER_COMPDIR || 'shopify/jsx';
const REL_DIR = COMPONENT_DIR.startsWith('/') ? '' : `${process.env.JSXSERVER_REL || '.'}/`;

//Dynamic import for jsx we use here, as we use compiled versions in production
const { createCache } = require(`${REL_DIR}${COMPONENT_DIR}/assets/localstate.js`);

let moduleCache = new LRU({
  max:    100,
  ttl:    3600 * 1000, //Items stay in cache for up to an hr
});

function reportTime(tStart, location) {
  let hrElapsed = process.hrtime(tStart);
  let elapsed = hrElapsed[0] * 1000.0 + hrElapsed[1] / 1000000.0;

  [console.info](http://console.info)(`Exec Time ${location}: ${elapsed} ms`);
}


/* Uses LRU cache to cache JSX imports from database to reduce compiler invocations */
function requireFromCache(reactBody) {

  //Calc code hash. Will be used for lookup
  const codeHash = stringHash(reactBody);

  let item = moduleCache.get(codeHash);
  /* eslint-disable-next-line eqeqeq */ /* TODO: Refactor to use !== and verify behavior */
  if (item === undefined || item[2] != reactBody) {
    //Recreate content
    const tTranslate = process.hrtime();
    const { code } = transformSync(reactBody, {
      extends: './.babelrc',
      envName: 'server'
    });
    reportTime(tTranslate, 'translate');

    const tImport = process.hrtime();
    let { Content, reset } = requireFromString(code, { appendPaths: [COMPONENT_DIR] });
    reportTime(tImport, 'moduleImport');

    item = [Content, code, reactBody, reset];
    moduleCache.set(codeHash, item);

    console.log('rendered');
  }
  else {
    console.log('from LRU');
  }
  return item;
}



export default function render(request) {
  const { reactBody, gqlData, gqlQuery } = request.body;

  const cache = createCache();
  /* eslint-disable-next-line eqeqeq */ /* TODO: Refactor to use !== and verify behavior */
  if (gqlQuery != '') {
    cache.writeQuery({query: gql(gqlQuery), data: gqlData});
  }

  const client = new ApolloClient({
    link: null,
    cache,
    defaultOptions: {
      fetchPolicy: 'cache-only'
    },
  });

  //Google Material UI does not use emotion, and has a different system for managing css
  const gmuiSheets = new ServerStyleSheets();


  //Wrap body in fragment to allow things to sit next to eachother

  //Translate code from JSX to JS
  try {

    //Create React component
    const [Content, code, , reset] = requireFromCache(reactBody);

    //Reset any module state before rendering. Undefined check is only necessary the first time
    //the version with reset in cache result is available, and can bere moved later (to deal with existing cache not having reset)
    if (reset !== undefined) {
      reset();
    }

    //Render view
    let html = ReactDOMServer.renderToString(
      gmuiSheets.collect(
        <ApolloProvider client={client}>
          <Content />
        </ApolloProvider>
      )
    );

    //Prepend material ui CSS to generated HTML
    const gmuiCSS = gmuiSheets.toString();
    html = `<style id="jss-server-side">${gmuiCSS}</style>${html}`;

    return {
      html: html,
      finalState: JSON.stringify(cache.extract()),
      code: code,
      error: null,
    };
  } catch (error) {
    const errString = error.stack; //error.stack necessary to send stack back to django
    console.log('ERROR: ', errString);
    console.log('Stack trace');
    console.trace('Stack trace'); //console.trace broken on node 8, outputs [object Object]\n<trace> instead of this string
    console.log('EXTA INFO ON ERROR OBJECT??: ', Object.keys(error));
    return { html: null, finalState: null, code: null, error: errString };
  }
}

@chungwu … however the root cause here is the self in the code coming from plasmic… It was not there before… why is it there now?

I am not modifying that JSON in any way…

thanks! yes that came from changes on our side. In general, different code needs to be run on the server for SSR or on the client for hydration; the error here is caused by using browser code on the server. I’m going to make a quick change that should bypass this error for now, and a deeper change that will make it possible for you to do things the right way, instead of always using browser modules on the server

appreciated @chungwu

@chungwu not to rush, but do you have a sense of ETA?

(we discovered some pages that are badly broken on certain devices, and I need to get a fix out :slightly_smiling_face: ) … ref https://plasmiccommunity.slack.com/archives/C01NR9R0MS7/p1667503257216069

sorry just need a little time to test and deploy the changes

maybe ~1-2 hours

ok, thank you. I appreciate that you run through regression testing first :slightly_smiling_face:

could you try this again? you’ll need to publish a new version of the site