next/document#DocumentContext TypeScript Examples

The following examples show how to use next/document#DocumentContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: _document.tsx    From next-page-tester with MIT License 6 votes vote down vote up
static async getInitialProps(ctx: DocumentContext) {
    const initialProps = await Document.getInitialProps(ctx);
    const styles = extractCritical(initialProps.html);

    return {
      ...initialProps,
      styles: (
        <>
          {initialProps.styles}
          <style
            data-emotion-css={styles.ids.join(' ')}
            dangerouslySetInnerHTML={{ __html: styles.css }}
          />
        </>
      ),
    };
  }
Example #2
Source File: _document.tsx    From halstack-react with Apache License 2.0 6 votes vote down vote up
static async getInitialProps(ctx: DocumentContext) {
    const sheet = new ServerStyleSheet()
    const originalRenderPage = ctx.renderPage

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) =>
            sheet.collectStyles(<App {...props} />),
        })

      const initialProps = await Document.getInitialProps(ctx)
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      }
    } finally {
      sheet.seal()
    }
  }
Example #3
Source File: _document.tsx    From FaztCommunityMatch with MIT License 6 votes vote down vote up
static async getInitialProps(
    ctx: DocumentContext
  ): Promise<DocumentInitialProps> {
    const sheet = new ServerStyleSheet()
    const originalRenderPage = ctx.renderPage

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) =>
            sheet.collectStyles(<App {...props} />)
        })

      const initialProps = await Document.getInitialProps(ctx)
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        )
      }
    } finally {
      sheet.seal()
    }
  }
Example #4
Source File: _document.tsx    From Demae with MIT License 6 votes vote down vote up
static async getInitialProps(ctx: DocumentContext) {
		const styledComponentsSheet = new ServerStyleSheet()
		const materialSheets = new ServerStyleSheets()
		const originalRenderPage = ctx.renderPage;

		try {
			ctx.renderPage = () => originalRenderPage({
				enhanceApp: App => props => styledComponentsSheet.collectStyles(materialSheets.collect(<App {...props} />))
			})
			const initialProps = await Document.getInitialProps(ctx)
			return {
				...initialProps,
				styles: (
					<React.Fragment>
						{initialProps.styles}
						{materialSheets.getStyleElement()}
						{styledComponentsSheet.getStyleElement()}
					</React.Fragment>
				)
			}
		} finally {
			styledComponentsSheet.seal()
		}
	}
Example #5
Source File: _document.tsx    From portfolio with MIT License 6 votes vote down vote up
static async getInitialProps(
    ctx: DocumentContext,
  ): Promise<DocumentInitialProps> {
    const initialProps = await Document.getInitialProps(ctx);
    const styles = CssBaseline.flush();

    return {
      ...initialProps,
      styles: (
        <>
          {initialProps.styles}
          {styles}
        </>
      ),
    };
  }
Example #6
Source File: _document.tsx    From glaze with MIT License 6 votes vote down vote up
static async getInitialProps(
    ctx: DocumentContext,
  ): Promise<DocumentInitialProps> {
    const injector = new VirtualStyleInjector();

    const originalRenderPage = ctx.renderPage;
    ctx.renderPage = (): ReturnType<typeof ctx.renderPage> =>
      originalRenderPage({
        enhanceApp: (App) => (props): JSX.Element => (
          // eslint-disable-next-line @typescript-eslint/camelcase, no-undef
          <StyleInjectorProvider injector={injector} nonce={__webpack_nonce__}>
            <App {...props} />
          </StyleInjectorProvider>
        ),
      });

    const initialProps = await Document.getInitialProps(ctx);
    return { ...initialProps, styles: injector.getStyleElement() };
  }
Example #7
Source File: create-get-initial-props.tsx    From mantine with MIT License 6 votes vote down vote up
export function createGetInitialProps(): (ctx: DocumentContext) => any {
  const stylesServer = createStylesServer();

  return async function getInitialProps(ctx: DocumentContext) {
    const initialProps = await NextDocument.getInitialProps(ctx);
    return {
      ...initialProps,
      styles: (
        <>
          {initialProps.styles}
          <ServerStyles html={initialProps.html} server={stylesServer} />
        </>
      ),
    };
  };
}
Example #8
Source File: _document.tsx    From Money-printer-go-BRRR with MIT License 6 votes vote down vote up
static async getInitialProps(ctx: DocumentContext) {
    const sheet = new ServerStyleSheet();
    const originalRenderPage = ctx.renderPage;

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) =>
            sheet.collectStyles(<App {...props} />),
        });

      const initialProps = await Document.getInitialProps(ctx);
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      };
    } finally {
      sheet.seal();
    }
  }
Example #9
Source File: _document.tsx    From mui-toolpad with MIT License 6 votes vote down vote up
static async getInitialProps(
    ctx: DocumentContext,
  ): Promise<DocumentInitialProps & ToolpadDocumentProps> {
    const originalRenderPage = ctx.renderPage;

    // You can consider sharing the same emotion cache between all the SSR requests to speed up performance.
    // However, be aware that it can have global side effects.
    const cache = createEmotionCache();
    const { extractCriticalToChunks } = createEmotionServer(cache);

    ctx.renderPage = () =>
      originalRenderPage({
        enhanceApp: (App: any) =>
          function EnhancedApp(props) {
            return <App emotionCache={cache} {...props} />;
          },
      });

    const initialProps = await Document.getInitialProps(ctx);
    // This is important. It prevents emotion to render invalid HTML.
    // See https://github.com/mui/material-ui/issues/26561#issuecomment-855286153
    const emotionStyles = extractCriticalToChunks(initialProps.html);
    const emotionStyleTags = emotionStyles.styles.map((style) => (
      <style
        data-emotion={`${style.key} ${style.ids.join(' ')}`}
        key={style.key}
        // eslint-disable-next-line react/no-danger
        dangerouslySetInnerHTML={{ __html: style.css }}
      />
    ));

    return {
      ...initialProps,
      // Styles fragment is rendered after the app and page rendering finish.
      styles: [...React.Children.toArray(initialProps.styles), ...emotionStyleTags],
      config,
    };
  }
Example #10
Source File: _document.tsx    From next-page-tester with MIT License 6 votes vote down vote up
static async getInitialProps(ctx: DocumentContext) {
    return ctx.renderPage({
      enhanceApp: (App) => (props) => (
        <CounterContext.Provider value={{ count: 150 }}>
          <App {...props} />
        </CounterContext.Provider>
      ),
    });
  }
Example #11
Source File: _document.tsx    From geist-ui with MIT License 6 votes vote down vote up
static async getInitialProps(ctx: DocumentContext) {
    const initialProps = await Document.getInitialProps(ctx)
    const styles = CssBaseline.flush()

    return {
      ...initialProps,
      styles: (
        <>
          {initialProps.styles}
          {styles}
        </>
      ),
    }
  }
Example #12
Source File: _document.tsx    From next-page-tester with MIT License 6 votes vote down vote up
static async getInitialProps(ctx: DocumentContext) {
    const page = ctx.renderPage((App) => (props) => (
      <StyletronProvider value={styletron}>
        <App {...props} />
      </StyletronProvider>
    ));

    const stylesheets = (styletron as Server).getStylesheets() || [];

    return { ...page, stylesheets };
  }
Example #13
Source File: _document.tsx    From nextclade with MIT License 6 votes vote down vote up
static async getInitialProps(ctx: DocumentContext): Promise<DocumentInitialProps> {
    const sheet = new ServerStyleSheet()
    const originalRenderPage = ctx.renderPage

    try {
      ctx.renderPage = () =>
        originalRenderPage({ enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />) })
      const initialProps = await NextDocument.getInitialProps(ctx)
      const styles = [initialProps.styles, sheet.getStyleElement()]
      return { ...initialProps, styles }
    } finally {
      sheet.seal()
    }
  }
Example #14
Source File: _document.tsx    From office-hours with GNU General Public License v3.0 6 votes vote down vote up
static async getInitialProps(
    ctx: DocumentContext
  ): Promise<DocumentInitialProps> {
    const sheet = new ServerStyleSheet();
    const originalRenderPage = ctx.renderPage;

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) =>
            sheet.collectStyles(<App {...props} />),
        });

      const initialProps = await Document.getInitialProps(ctx);
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      };
    } finally {
      sheet.seal();
    }
  }
Example #15
Source File: _document.tsx    From nextjs-hasura-fullstack with MIT License 6 votes vote down vote up
static async getInitialProps(ctx: DocumentContext) {
    resetServerContext()
    try {
      const initialProps = await NextDocument.getInitialProps(ctx)
      return {
        ...initialProps,
        styles: <>{initialProps.styles}</>,
      }
      // eslint-disable-next-line no-empty
    } finally {
    }
  }
Example #16
Source File: index.tsx    From resume-builder with MIT License 6 votes vote down vote up
static async getInitialProps(ctx: DocumentContext) {
        const sheet = new ServerStyleSheet();
        const originalRenderPage = ctx.renderPage;

        try {
            ctx.renderPage = () =>
                originalRenderPage({
                    enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
                });

            const initialProps = await Document.getInitialProps(ctx);
            return {
                ...initialProps,
                styles: (
                    <>
                        {initialProps.styles}
                        {sheet.getStyleElement()}
                    </>
                ),
            };
        } finally {
            sheet.seal();
        }
    }
Example #17
Source File: _document.tsx    From typescript-fun with MIT License 6 votes vote down vote up
static async getInitialProps({ renderPage }: DocumentContext) {
    AppRegistry.registerComponent(config.name, () => Main);
    // @ts-ignore React Native Web custom API.
    const { getStyleElement } = AppRegistry.getApplication(config.name);
    const page = renderPage();
    const styles = [
      // eslint-disable-next-line react/jsx-key
      <style dangerouslySetInnerHTML={{ __html: normalizeNextElements }} />,
      getStyleElement(),
    ];
    return { ...page, styles: React.Children.toArray(styles) };
  }
Example #18
Source File: index.tsx    From Insomniac-NextJS-boilerplate with MIT License 6 votes vote down vote up
static async getInitialProps(ctx: DocumentContext) {
    const styledComponentSheet = new StyledComponentSheets();
    const materialUiSheets = new MaterialUiServerStyleSheets();
    const originalRenderPage = ctx.renderPage;

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) =>
            styledComponentSheet.collectStyles(
              materialUiSheets.collect(<App {...props} />)
            ),
        });

      const initialProps = await Document.getInitialProps(ctx);
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {materialUiSheets.getStyleElement()}
            {styledComponentSheet.getStyleElement()}
          </>
        ),
      };
    } finally {
      styledComponentSheet.seal();
    }
  }
Example #19
Source File: _document.tsx    From ya-webadb with MIT License 6 votes vote down vote up
static async getInitialProps(context: DocumentContext): Promise<DocumentInitialProps> {
        resetIds();

        const { html, head, styles, ...rest } = await Document.getInitialProps(context);

        return {
            ...rest,
            html,
            head: [
                ...(head ?? []),
                <script key="fluentui" dangerouslySetInnerHTML={{
                    __html: `
                        window.FabricConfig = window.FabricConfig || {};
                        window.FabricConfig.serializedStylesheet = ${stylesheet.serialize()};
                    `
                }} />
            ],
            styles: (
                <>
                    {styles}
                    <style dangerouslySetInnerHTML={{ __html: stylesheet.getRules() }} />
                </>
            )
        };
    }
Example #20
Source File: _document.tsx    From twitch-clone with MIT License 6 votes vote down vote up
static async getInitialProps(
    ctx: DocumentContext,
  ): Promise<DocumentInitialProps> {
    const sheet = new ServerStyleSheet();
    const originalRenderPage = ctx.renderPage;

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) =>
            sheet.collectStyles(<App {...props} />),
        });

      const initialProps = await Document.getInitialProps(ctx);
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      };
    } finally {
      sheet.seal();
    }
  }
Example #21
Source File: _document.tsx    From frontend with GNU General Public License v3.0 6 votes vote down vote up
static async getInitialProps(ctx: DocumentContext): Promise<DocumentInitialProps> {
    const sheet = new ServerStyleSheet();
    const originalRenderPage = ctx.renderPage;

    ctx.renderPage = () =>
      originalRenderPage({
        enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
      });

    const initialProps = await Document.getInitialProps(ctx);
    return {
      ...initialProps,
      styles: (
        <>
          {initialProps.styles}
          {sheet.getStyleElement()}
        </>
      ),
    };
  }
Example #22
Source File: _document.tsx    From website with Apache License 2.0 6 votes vote down vote up
static async getInitialProps(ctx: DocumentContext): Promise<{
    styles: JSX.Element;
    html: string;
    head?: (JSX.Element | null)[] | undefined;
  }> {
    const sheet = new ServerStyleSheet();
    const originalRenderPage = ctx.renderPage;

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: App => props => sheet.collectStyles(<App {...props} />),
        });

      const initialProps = await Document.getInitialProps(ctx);
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      };
    } finally {
      sheet.seal();
    }
  }
Example #23
Source File: _document.tsx    From Teyvat.moe with GNU General Public License v3.0 6 votes vote down vote up
static async getInitialProps(context: DocumentContext): Promise<DocumentInitialProps> {
    // Render app and page and get the context of the page with collected side effects.
    const sheets = new ServerStyleSheets({
      // injectFirst: true,
      serverGenerateClassName: generateClassName,
    });
    const originalRenderPage = context.renderPage;

    context.renderPage = () =>
      originalRenderPage({
        // The method wraps your React node in a provider element.
        // It collects the style sheets during the rendering so they can be later sent to the client.
        enhanceApp: (App) => (props) => sheets.collect(<App {...props} />),
      });

    console.info(`Performing SSR for path ${context.pathname} (${context.locale})`);

    const initialProps = await Document.getInitialProps(context);

    return {
      ...initialProps,
      // Styles fragment is rendered after the app and page rendering finish.
      styles: [...Children.toArray(initialProps.styles), sheets.getStyleElement()],
    };
  }
Example #24
Source File: _document.tsx    From next-right-now-admin with MIT License 6 votes vote down vote up
static async getInitialProps(ctx: DocumentContext): Promise<DocumentInitialProps> {
    try {
      Sentry.addBreadcrumb({ // See https://docs.sentry.io/enriching-error-data/breadcrumbs
        category: fileLabel,
        message: `Preparing document (${isBrowser() ? 'browser' : 'server'})`,
        level: Sentry.Severity.Debug,
      });

      const initialProps: DocumentInitialProps = await Document.getInitialProps(ctx);
      const { req }: NextPageContext = ctx;
      const cookies: Cookies = NextCookies(ctx); // Parses Next.js cookies in a universal way (server + client)
      const lang: string = universalLanguageDetect({
        supportedLanguages: SUPPORTED_LANGUAGES, // Whitelist of supported languages, will be used to filter out languages that aren't supported
        fallbackLanguage: LANG_EN, // Fallback language in case the user's language cannot be resolved
        acceptLanguageHeader: get(req, 'headers.accept-language'), // Optional - Accept-language header will be used when resolving the language on the server side
        serverCookies: cookies, // Optional - Cookie "i18next" takes precedence over navigator configuration (ex: "i18next: fr"), will only be used on the server side
        errorHandler: (error: Error, level: ERROR_LEVELS, origin: string, context: object): void => {
          Sentry.withScope((scope): void => {
            scope.setExtra('level', level);
            scope.setExtra('origin', origin);
            scope.setContext('context', context);
            Sentry.captureException(error);
          });
          logger.error(error.message);
        },
      });

      return { ...initialProps, lang };
    } catch (e) {
      // If an error happens, log it and then try to render the page again with minimal processing
      // This way, it'll render something on the client. (otherwise, it'd completely crash the server and render "Internal Server Error" on the client)
      Sentry.captureException(e);

      const initialProps: DocumentInitialProps = await Document.getInitialProps(ctx);
      return { ...initialProps };
    }
  }
Example #25
Source File: _document.tsx    From telegram-standup-bot with MIT License 6 votes vote down vote up
static async getInitialProps(ctx: DocumentContext) {
    const initialProps = await Document.getInitialProps(ctx);
    const styles = CssBaseline.flush();

    return {
      ...initialProps,
      styles: (
        <>
          {initialProps.styles}
          {styles}
        </>
      ),
    };
  }
Example #26
Source File: _document.tsx    From NextPay with MIT License 6 votes vote down vote up
static async getInitialProps(ctx: DocumentContext) {
    const sheet = new ServerStyleSheet();
    const originalRenderPage = ctx.renderPage;

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: App => props => sheet.collectStyles(<App {...props} />),
        });

      const initialProps = await Document.getInitialProps(ctx);
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      };
    } finally {
      sheet.seal();
    }
  }
Example #27
Source File: _document.tsx    From Cromwell with MIT License 6 votes vote down vote up
static async getInitialProps(ctx: DocumentContext) {

    const originalRenderPage = ctx.renderPage;
    const cache = createEmotionCache();
    const { extractCriticalToChunks } = createEmotionServer(cache);

    ctx.renderPage = () =>
      originalRenderPage({
        enhanceApp: (App: any) => (props) => <App emotionCache={cache} {...props} />,
      })

    const initialProps = await Document.getInitialProps(ctx);
    // This is important. It prevents emotion to render invalid HTML.
    // See https://github.com/mui-org/material-ui/issues/26561#issuecomment-855286153
    const emotionStyles = extractCriticalToChunks(initialProps.html);
    const emotionStyleTags = emotionStyles.styles.map((style) => (
      <style
        data-emotion={`${style.key} ${style.ids.join(' ')}`}
        key={style.key}
        dangerouslySetInnerHTML={{ __html: style.css }}
      />
    ));

    return {
      ...initialProps,
      // Styles fragment is rendered after the app and page rendering finish.
      styles: [...React.Children.toArray(initialProps.styles), ...emotionStyleTags],
    }
  }
Example #28
Source File: _document.tsx    From storefront with MIT License 6 votes vote down vote up
static async getInitialProps(ctx: DocumentContext) {
    const sheets = new ServerStyleSheets();
    const originalRenderPage = ctx.renderPage;

    ctx.renderPage = () =>
      originalRenderPage({
        enhanceApp: (App) => (props) => sheets.collect(<App {...props} />),
      });

    const initialProps = await Document.getInitialProps(ctx);

    return {
      ...initialProps,
      // Styles fragment is rendered after the app and page rendering finish.
      styles: [...React.Children.toArray(initialProps.styles), sheets.getStyleElement()],
    };
  }
Example #29
Source File: _document.tsx    From Cromwell with MIT License 6 votes vote down vote up
static async getInitialProps(ctx: DocumentContext) {
        const originalRenderPage = ctx.renderPage;
        const cache = createEmotionCache();
        const { extractCriticalToChunks } = createEmotionServer(cache);
        ctx.renderPage = () =>
            originalRenderPage({
                enhanceApp: (App: any) => (props) => <App emotionCache={cache} {...props} />,
            })

        const initialProps = await Document.getInitialProps(ctx);
        // This is important. It prevents emotion to render invalid HTML.
        // See https://github.com/mui-org/material-ui/issues/26561#issuecomment-855286153
        const emotionStyles = extractCriticalToChunks(initialProps.html);
        const emotionStyleTags = emotionStyles.styles.map((style) => (
            <style
                data-emotion={`${style.key} ${style.ids.join(' ')}`}
                key={style.key}
                dangerouslySetInnerHTML={{ __html: style.css }}
            />
        ));

        return {
            ...initialProps,
            // Styles fragment is rendered after the app and page rendering finish.
            styles: [...React.Children.toArray(initialProps.styles), ...emotionStyleTags],
        }
    }