Skip to content

[ssr] SSR rendering in NextJS #2391

@kacper-serewis

Description

@kacper-serewis

Description

I'm trying to render a lit component via SSR in NextJS, the default behavior is that it fails to import the component because there is no window property at the server-side rendering.

To fix that, I've imported @lit-labs/ssr/lib/install-global-dom-shim.js before importing my lit component.

Unfortunately, some packages relay their SSR-detection on the availability of window property.
And because of the installed shim, packages will fail to detect the valid environment and will be executing client-side code on the server.

The shim installed by @lit-labs/ssr does not contain all of the functions of the real, client-sided, window property.

In my case, the package styled-jsx tries to execute the following line of code:
var node = this._isBrowser && document.querySelector('meta[property="csp-nonce"]');.

This results in an exception because the _isBrowser property is true on the server-side.
Hardcoding this property results in compiling without any problems.

Steps to Reproduce

  1. Write this code

element.ts

import "@lit-labs/ssr/lib/install-global-dom-shim.js";
import {html, css, LitElement} from 'lit';
import {customElement, property} from 'lit/decorators.js';

@customElement('simple-greeting')
export class SimpleGreeting extends LitElement {
  static styles = css`p { color: blue }`;

  @property()
  name = 'Somebody';

  render() {
    return html`<p>Hello, ${this.name}!</p>`;
  }
}

index.js

import "element"

export default function Home(){
  return ( <simple-greeting></simple-greeting> )
}
  1. npm run build

Expected Results

Use of lit element in NextJS using SSR (which is enabled by default), without adding any new server-side specific functionality to the element itself.

Actual Results

Exception is thrown when builiding:
error - TypeError: document.querySelector is not a function

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

Status

✅ Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions